object-oriented programming (java). 2 topics covered today unit 1.1 java applications –1.1.3...

33
Object-Oriented Programming (Ja va)

Upload: winfred-gordon

Post on 13-Jan-2016

234 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Object-Oriented Programming (Java). 2 Topics Covered Today Unit 1.1 Java Applications –1.1.3 Beginning with the Java API –1.1.4 Console I/O

Object-Oriented Programming (Java)

Page 2: Object-Oriented Programming (Java). 2 Topics Covered Today Unit 1.1 Java Applications –1.1.3 Beginning with the Java API –1.1.4 Console I/O

2

Topics Covered Today

• Unit 1.1 Java Applications– 1.1.3 Beginning with the Java API– 1.1.4 Console I/O

Page 3: Object-Oriented Programming (Java). 2 Topics Covered Today Unit 1.1 Java Applications –1.1.3 Beginning with the Java API –1.1.4 Console I/O

3

Java API

• API stands for Application Programming Interface( 应用程序接口 ).

• Java API 是 Java 提供给应用程序的类库,这些库经过仔细的编写,严格地与广泛地测试。

• Most programs use both features from the Java API and essential language features.

• http://java.sun.com/j2se/1.5.0/docs/api/

Lenovo User
本质
Page 4: Object-Oriented Programming (Java). 2 Topics Covered Today Unit 1.1 Java Applications –1.1.3 Beginning with the Java API –1.1.4 Console I/O

4

Package

• The classes in the Java API are grouped into packages.– Java 用包来管理类名空间,为了解决同名的类有可能发生

冲突的问题,包实际提供了一种命名机制和可见性限制机制 .

• A package is simply a collection of related classes– 所有的图形界面的类都放在 java.awt 这个包中,– 与网络功能有关的类都放到 java.net 这个包中。

• The fully qualified name of a class that is part of a package is the package name and the class name separated by a dot.– java.awt.Color

Page 5: Object-Oriented Programming (Java). 2 Topics Covered Today Unit 1.1 Java Applications –1.1.3 Beginning with the Java API –1.1.4 Console I/O

5

import Statement

• 如果在源程序中用到了除 java.lang 这个包以外的类,无论是系统的类还是自己定义的包中的类,都必须用 import 语句标识,以通知编译器在编译时找到相应的类文件。

• 如果要从一个包中引入多个类则在包名后加上“ .*” 表示 , 如– import java.awt.Color;– import java.awt.*;

• Classes java.lang.* are automatically imported

Page 6: Object-Oriented Programming (Java). 2 Topics Covered Today Unit 1.1 Java Applications –1.1.3 Beginning with the Java API –1.1.4 Console I/O

6

Example

import java.lang.String; import java.io.FileWriter; import java.io.IOException; public class test {

public static void main(String[] args) {try {

FileWriter fw = new FileWriter("hello.txt");String h = "Hello"; String w = "World";fw.write(h+ " " + w); fw.close ();

}catch (IOException e) {

System.out.println("Error writing to file:" + e);}

}}

Qualified names

Simple name

Page 7: Object-Oriented Programming (Java). 2 Topics Covered Today Unit 1.1 Java Applications –1.1.3 Beginning with the Java API –1.1.4 Console I/O

7

The java.lang.String Class (1)

• Java 中没有处理字符串的基本类型,但是有一个 String 类可以用来存储和处理字符串。

• String 类的成员函数:– String(). Constructs a new String object that represents an empty

character sequence. – String(char[] value). Constructs a new String object that represe

nts the sequence of characters contained in the character array. – String(String original). Constructs a new String object that repre

sents the same sequence of characters as the argument. – int size(). Obtains the number of characters in the String. – char charAt(int index). Returns the character at the specified ind

ex.

Page 8: Object-Oriented Programming (Java). 2 Topics Covered Today Unit 1.1 Java Applications –1.1.3 Beginning with the Java API –1.1.4 Console I/O

8

The java.lang.String Class (2)

– boolean equals(Object anObject). Returns true if the specified Object represents a String with the same sequence of characters.

– int indexOf(int ch). Returns the index of the first occurrence of the character.

– int indexOf(String str). Returns the index of the first occurrence of the String.

– boolean startsWith(String prefix). Checks if the String has the specified prefix.

– String substring(int beginIndex, int endIndex). Returns a substring.

Page 9: Object-Oriented Programming (Java). 2 Topics Covered Today Unit 1.1 Java Applications –1.1.3 Beginning with the Java API –1.1.4 Console I/O

9

The java.lang.String Class (3)

• String 类的操作: – String 中提供字符串的比较的方法: equals( ) 和 equalsIgnor

eCase( )– 它们与运算符‘ = =’ 实现的比较是不同的。

• 运算符‘ = =’ 比较两个对象是否引用同一个实例,• 而 equals( ) 和 equalsIgnoreCase( ) 则比较两个字符串中对应的每个字

符值是否相同。– 字符串的转化

• java.lang.Object 中提供了方法 toString( ) 把对象转化为字符串。– 字符串 "+" 操作

• 运算符‘ +’ 可用来实现字符串的连接:   String s = “He is ”+age+“ years old.”;

• 注意:除了对运算符 "+" 进行了重载外, java 不支持其它运算符的重载。

Page 10: Object-Oriented Programming (Java). 2 Topics Covered Today Unit 1.1 Java Applications –1.1.3 Beginning with the Java API –1.1.4 Console I/O

10

The java.util.StringTokenizer Class (1)

• Tokenizing is the process of breaking a string into smaller pieces called tokens. – 例:下面字符串用空格化分,可分为几个字符串?

"This string has five tokens"

• Popular delimiters( 分割符 ) include the white space, underscore ( _ ) and the comma ( , ).

Page 11: Object-Oriented Programming (Java). 2 Topics Covered Today Unit 1.1 Java Applications –1.1.3 Beginning with the Java API –1.1.4 Console I/O

11

The java.util.StringTokenizer Class (2)

• StringTokenizer 类在 java.util 包中,常用的方法有:– StringTokenizer(String str). Constructs a string tokenizer. The to

kenizer uses the default delimiter set, white space.

– StringTokenizer(String str, String delim). Constructs a string tokenizer. The argument delim contains the character delimiters for separating tokens.

– boolean hasMoreTokens(). Tests if there are more tokens to extract.

– String nextToken(String delim). Returns the next token in the string.

– int countTokens(). Obtains the number of tokens left to be extracted, not the number of tokens in the string.

Page 12: Object-Oriented Programming (Java). 2 Topics Covered Today Unit 1.1 Java Applications –1.1.3 Beginning with the Java API –1.1.4 Console I/O

12

The java.util.StringTokenizer Class (3)

import java.util.*;

public class ProductInfo {

public static void main(String[] args) {

String data = "Mini Discs 74 Minute (10-Pack)_5_9.00";

StringTokenizer tknzr = new StringTokenizer(data, "_");

String name = tknzr.nextToken();

String quantity = tknzr.nextToken();

String price = tknzr.nextToken();

System.out.println("Name: " + name);

System.out.println("Quantity: " + quantity);

System.out.println("Price: " + price);

}

}

Page 13: Object-Oriented Programming (Java). 2 Topics Covered Today Unit 1.1 Java Applications –1.1.3 Beginning with the Java API –1.1.4 Console I/O

13

Java’s Primitive Types

• 整型:– byte : 8-bit

– short : 16-bit

– int : 32-bit

– long : 64-bit

• 浮点型:– float : 32-bit

– double : 64-bit

• 字符型: char 16-bit

• 布尔型: boolean

Page 14: Object-Oriented Programming (Java). 2 Topics Covered Today Unit 1.1 Java Applications –1.1.3 Beginning with the Java API –1.1.4 Console I/O

14

The Wrapper Classes (1)

• 为了保证处理数据的一致性, Java 将基本数据类型也封装成了类,这些类统称为 wrapped classes 。– java.lang.Byte – java.lang.Short – java.lang.Integer – java.lang.Long – java.lang.Character– java.lang.Float– java.lang.Double– java.lang.Boolean

Page 15: Object-Oriented Programming (Java). 2 Topics Covered Today Unit 1.1 Java Applications –1.1.3 Beginning with the Java API –1.1.4 Console I/O

15

The Wrapper Classes (2)

public class WrapperConversion { public static void main(String[] args) {

Integer objectValue = new Integer(100);int intValue = objectValue.intValue(); long longValue = objectValue.longValue(); double doubleValue = objectValue.doubleValue(); String stringValue = objectValue.toString();

System.out.println("objectValue: " + objectValue); System.out.println("intValue: " + intValue);

System.out.println("longValue: " + longValue); System.out.println("doubleValue: " + doubleValue); System.out.println("stringValue: " + stringValue); } }

Page 16: Object-Oriented Programming (Java). 2 Topics Covered Today Unit 1.1 Java Applications –1.1.3 Beginning with the Java API –1.1.4 Console I/O

16

The Wrapper Classes (3)

import java.util.*;

public class ProductInfo {

public static void main(String[] args) {

String data = "Mini Discs 74 Minute (10-Pack)_5_9.00";

StringTokenizer tknzr = new StringTokenizer(data, "_");

String name = tknzr.nextToken();

int quantity = Integer.parseInt(tknzr.nextToken());

double price = Double.parseDouble(tknzr.nextToken());

System.out.println("Name: " + name);

System.out.println("Quantity: " + quantity);

System.out.println("Price: " + price);

}

}

Page 17: Object-Oriented Programming (Java). 2 Topics Covered Today Unit 1.1 Java Applications –1.1.3 Beginning with the Java API –1.1.4 Console I/O

17

Primitives and Wrappers

• Primitives in Java aren't objects at all.

• Wrapper classes are object versions of the primitive types.

• Things get annoying when you have to go back and forth between the two - converting a primitive to its wrapper, using it, then converting the object's value back to a primitive.

• Happily, Tiger finally takes care of this issue.

Page 18: Object-Oriented Programming (Java). 2 Topics Covered Today Unit 1.1 Java Applications –1.1.3 Beginning with the Java API –1.1.4 Console I/O

18

New Java Language Feature

• Java 5.0 introduced new language features– http://java.sun.com/j2se/1.5.0/docs/guide/language/

• Autoboxing( 自动装箱 ) /unboxing( 自动拆箱 )– Automatically converts primitives (such as int) to wrap

per classes (such as Integer) – Data value Object (of matching class)

Page 19: Object-Oriented Programming (Java). 2 Topics Covered Today Unit 1.1 Java Applications –1.1.3 Beginning with the Java API –1.1.4 Console I/O

Autoboxing/Unboxing Example(Classical Approach)

• Traditional “boxing” example:

List ssnList = new ArrayList(); . . .int ssn = getSocSecNum(); . . .Integer ssnInteger = new Integer(ssn);ssnList.add(ssnInteger);

• Why do I have to convert from int to Integer?

Page 20: Object-Oriented Programming (Java). 2 Topics Covered Today Unit 1.1 Java Applications –1.1.3 Beginning with the Java API –1.1.4 Console I/O

20

Autoboxing/Unboxing Example(New Approach)

• “Autoboxing” example:

List ssnList = new ArrayList(); . . .int ssn = getSocSecNum(); . . .ssnList.add(ssn);

• No need for an explicit conversion to Integer.

Page 21: Object-Oriented Programming (Java). 2 Topics Covered Today Unit 1.1 Java Applications –1.1.3 Beginning with the Java API –1.1.4 Console I/O

21

Unboxing(Converting Wrapper Types to Primitives)

• “Autoboxing/unboxing” example:

// Boxing

int foo = 0;

Integer integer = foo;

// Simple Unboxing

int bar = integer;

Page 22: Object-Oriented Programming (Java). 2 Topics Covered Today Unit 1.1 Java Applications –1.1.3 Beginning with the Java API –1.1.4 Console I/O

22

Autoboxing / Unboxing

• The need to explicitly convert between primitive types and wrapper objects.– Such as primitive type int, and wrapper object Integer.– Can’t put primitives into Collections.

• Autoboxing and Unboxing– Automatic conversion by the compiler– Eliminates casts

• Compiler performs these conversions for us.

Page 23: Object-Oriented Programming (Java). 2 Topics Covered Today Unit 1.1 Java Applications –1.1.3 Beginning with the Java API –1.1.4 Console I/O

23

Unboxing(Converting Wrapper Types to Primitives)

• Null value assignment:

Integer i = null;

int j = i;

– i is assigned null (which is legal), and then i is unboxed into j. However, null isn't a legal value for a primitive, so this code throws a NullPointerException.

Page 24: Object-Oriented Programming (Java). 2 Topics Covered Today Unit 1.1 Java Applications –1.1.3 Beginning with the Java API –1.1.4 Console I/O

24

Incrementing and Decrementing Wrapper Types

• Every operation available to a primitive should be available to its wrapper-type counterpart, and vice versa:

Integer counter = 1; while (true) { System.out.printf("Iteration %d%n", counter++); if (counter > 1000) break; }

– Remember that counter is an Integer. So the value in counter was first auto-unboxed into an int, as that's the type required for the ++ operator. Once the value is unboxed, it is incremented. Then, the new value has to be stored back in counter, which requires a boxing operation.

Page 25: Object-Oriented Programming (Java). 2 Topics Covered Today Unit 1.1 Java Applications –1.1.3 Beginning with the Java API –1.1.4 Console I/O

25

Levels of Java API

• Each JDK defines a standard set of API classes and methods

• Sun provides standard extensions to the standard API

• Others can and do provide Java APIs

Page 26: Object-Oriented Programming (Java). 2 Topics Covered Today Unit 1.1 Java Applications –1.1.3 Beginning with the Java API –1.1.4 Console I/O

Console I/O

Page 27: Object-Oriented Programming (Java). 2 Topics Covered Today Unit 1.1 Java Applications –1.1.3 Beginning with the Java API –1.1.4 Console I/O

27

w

h

e

l

lo o r l

d

InputStreame.g. from disk file

Filter InputStreamread( )

Stream

• 在程序中提供一种将数据源连接到应用程序的方法,这样的方式叫做流 (stream) 。流是数据的真正流动 .

Page 28: Object-Oriented Programming (Java). 2 Topics Covered Today Unit 1.1 Java Applications –1.1.3 Beginning with the Java API –1.1.4 Console I/O

28

Stream Input/Output

• Stream– A connection carrying a sequence of data

• Bytes InputStream, OutputStream– Byte streams are used for data-based I/O, called input streams and o

utput streams

• Characters FileReader, PrintWriter– Character streams are used for text-based I/O, called readers and writ

ers

– From a source to a destination• Keyboard • File• Network• Memory

Page 29: Object-Oriented Programming (Java). 2 Topics Covered Today Unit 1.1 Java Applications –1.1.3 Beginning with the Java API –1.1.4 Console I/O

29

Standard Input/Output

• Standard I/O – Provided in System class in java.lang – System.in

• An instance of InputStream• To input bytes from keyboard

– System.out • An instance of PrintStream• To allow output to the screen

– System.err • An instance of PrintStream• To allow error messages to be sent to screen

Page 30: Object-Oriented Programming (Java). 2 Topics Covered Today Unit 1.1 Java Applications –1.1.3 Beginning with the Java API –1.1.4 Console I/O

30

java.io package

• Class java.io.BufferedReader– public BufferedReader(Reader in)

• Create a buffering character-input stream that uses a default-sized input buffer.

– readline(): Read a line of text.

– read(): Read a single character.

• Class java.io.PrintWriter– public PrintWriter(OutputStream out, boolean autoFlush)

• Create a new PrintWriter from an existing OutputStream.

• Print formatted representations of objects to a text-output stream.

– print(String s): Print a string

– println(String s):Print a string and then terminate the line

Page 31: Object-Oriented Programming (Java). 2 Topics Covered Today Unit 1.1 Java Applications –1.1.3 Beginning with the Java API –1.1.4 Console I/O

31

Template of a class using Console I/O

import java.io.*;

public class AnyClassUsingIO {

private static BufferedReader stdIn = new

BufferedReader(new InputStreamReader(System.in));

private static PrintWriter stdOut = new

PrintWriter(System.out, true);

private static PrintWriter stdErr = new

PrintWriter(System.err, true);

/* other variables */

/* methods */

}

Page 32: Object-Oriented Programming (Java). 2 Topics Covered Today Unit 1.1 Java Applications –1.1.3 Beginning with the Java API –1.1.4 Console I/O

32

4 examples in unit 1.1.4

• PrintlnDemo.java

• PrintDemo.java

• Hello.java

• ReadThreeIntegers.java

Page 33: Object-Oriented Programming (Java). 2 Topics Covered Today Unit 1.1 Java Applications –1.1.3 Beginning with the Java API –1.1.4 Console I/O

33

Using the printf( ) Convenience Method

• Tiger gives us the ability to type printf( ).import java.io.*;public class PrintTester { public static void main(String[] args) { String filename = args[0]; try { File file = new File(filename); FileReader fileReader = new FileReader(file); BufferedReader reader = new BufferedReader(fileReader); String line; int i = 1; while ((line = reader.readLine( )) != null) { System.out.printf("Line %d: %s%n", i++, line); } } catch (Exception e) { System.err.printf("Unable to open file named '%s': %s", filename, e.getMessage( )); } } }