You are on page 1of 499

1

Java

Java
Java
Java

1
1.1

Java

Java

Java Sun Green


E-mail
C++ C++
C++ OakJava Oak
Sun SGI
Oak Mark Ardreesen Mosaic Netscape Oak
Java HotJava Sun Scott
McNealy Java Internet
Java Sun Java Java Media APIS
Security APIsManagement APIsJava AppletJava RMIJavaBeanJavaOSJava Servlet
JavaServer Page JDBC Java
1990 Sun James Gosling Oak

1995 1 Oak Java1995 5 23 Sun Sun World 95


Java HotJava
1995 8 12 Netscape Oracle Borland SGI
Adobe IBM AT&T Intel Java
1996 1 Sun JavaSoft
Java Alan Baratz Java
JDKJava Development Kit1.0 Java

1996 2 Sun Java PicoJava


MicroJava UltraJava
Java JDBCJava Database Connectivity
1996 3 Sun Java WorkShop

1996 4 Microsoft SCO AppleNEC


Java Sun HPIBMMicrosoft
NovellSGISCOTamdem Java
1996 5 HP Sybase Java Java
Java 5 29 Sun
JavaOne Java Sun
Java
1996 8 JavaWorkShop Sun
1996 9 Addison-Wesley Sun Java Java
1996 10 Java Sun JavaBean
Java JITJust-In-Time Java
WorkShop Solaris JIT10 29 Sun Java
JavaStation 65 85 Java
7 Java Java Java Solstice
Java HotJava Views Java TutorJava Card API
Sun Java Card API API
Java Card Java
1996 11 IBM JavaOS HotJava Novell Java
WorkShop Sun IBM Java
IBM Java
1996 12 Xerox Java JavaOS Sun JDK1.1
Java JavaBean Java APIs JavaServer
Java Web ServerJava NC Server JavaServer ToolkitSun
100% Java
1997 1 SAS Java Sun JavaBean
8
1997 2 Sun ARM JavaOS ARM
RISC Informix Universal Server
JDK1.1Netscape Netscape Communicator Java

API
1997 3 HP Java WorkShop HP-UX
AG Java Informix
JavaOS Novell Java Studio
Sun JavaOS 1.0
Java
JavaOS Sun HotJava Browser 1.0 Java

1996 6 Sun JSP1.0 JDK1.3 Java Web Server 2.0


1999 11 Sun JSP1.1 JSWDK1.0.1 Java Servlet 2.2
2000 9 Sun JSP1.2 Java Servlet 2.3 API

1.2

Java

Java Sun Internet


Wintel
Java IBMAppleDECAdobe
SiliconGraphicsHPOracleTOSHIBA MicrosoftJava

Java Inprise JBuilderSun


Java JDK JRESysbase Oracle
HTML Java
Intranet Java
Intranet Internet

Internet Web AppletServletJSP Web

1.3

Java

1.3.1

Java

Java Windows
9xWindows NTSolarisLinuxMacOS

Java C++ C++


Java C++Java
C++ C++ Java

C++ Java Java


Java C++

2 C++
3 a = 3 a = = 3
4
Java http://www.sun.com Java

1.3.2

Java

Java

1.
Java Java C++

2.
Windows
MacOSUNIX Java
Java

3.

30

Java

4.
Java C/C++ Java
Java Java

5.
Java
Java URL
Java Socket

CGI Java
AppletJava Java Server Page JSPServlet

6.
Java
Java
A Java Java

B Just-in-TimeJIT
JIT
7.
Java

Java
Java

8.

Java Java

9.
Java Java

Sun Java

JDK (Java Development Kit)1.0 Princeton


Java 1.0 Java
Java
Bugs Bugs
Sun Java

10.
Java
A Java
B
11.
Java Java

Java Java UCSD Pascal


UCSD Pascal
Niklaus Wirth Pascal

Java

1.4

Java (JVM)

Java (JVM) Java JVM


Java
1-1

1-1

Java

1-1 JAVA WINNT


LinuxUnix JVMJava JAVA SUN
Write Once, Run Anywhere

Java

J2EE (Java 2 Platform Enterprise Edition)

J2SE (Java 2 Platform Stand Edition)

J2ME (Java 2 Platform Micro Edition)

1.5

JDK

Java Java
JDK JDK
J2SDK1.4.2

1 JDK j2sdk-1_4_0_03-windows-i586 ;
2 path

1-2

JDK

10

1-3

c:\j2sdk

1-1 Java Javac Java


java windows

>>>>path

11

1-4

path c:\j2sdk\bin;
c:\j2sdk JDK 1-3

windows 2000 windows98


windows2000

12

1-5

javac java

1.6

Java

Java Java
JAVA Applet
Java Appliction Java
Java Application

13

Hello.java

01 public class Hello

02 {
03
//
04
public static void main(String args[])
05
{
06
// "Hello World !"
07
System.out.println("Hello World !");

08
}
09 }
HelloCareers.java javac Hello.java
java Hello

Hello World!

Java Application public static void main(String args[])

main

Java Application
Java Application

1.7

classpath

java set classpath java


classpath Hello.class c:\

14

D
set classpath=c:
D java Hello

1-6
D Hello.class
java Hello Hello.class D
set classpath C C

classpath classpath class

set classpath=.

15


1 Java
2 Byte-codes

3 classpath class

16

Java

Java

2.1

Java

TestJava2_1.java
01 // TestJava2_1.javajava
02 public class TestJava2_1
03 {
04
public static void main(String args[])
05
{
06
int num ;
// num
07
num = 3 ;
// 3
08
// "+"
09
System.out.println(" "+num);
10
System.out.println(" "+num+" ");
11
}
12 }

3
3

Java

17

System.out.println()
publicclassstaticvoid

1 1 Java / /

2 2 public class TestJava2_1 public class Java class


TestJava2_1public

public
2-1 TestJava2_1.java public
TestJava2_1 Java
public .java

2-1

public

3 4 public static void main(String args[]) 4~10


function Java method
C main() Java main() method

4 main() method body 5 { 11 }

18

Java main() method

5 6 int num; num

6 7 num=3; 2 num
7 8
System.out.println(" "+num);

num
8 System.out
println print line
8
System.out.println()
System.out.print()
9 10 main() method
10 11 class TestJava2_1

TestJava2_1 Java
TestJava2_1 Java
Java

2.2

Java

Java

19

2.2.1

class

Java class
Java

public class Test


{

// public Test

public Test
Test.java Test public Java

Java Java
Java
public
public non-public
Java public Java

2.2.2

{
};
{}
segmentblock
TestJava2_2

20


main() method for
for 3
13 public TestJava2_2

TestJava2_2.java

2.2.3

main() method

Java
main() main()

21

method
main() Java main()
main() method
public static void main(String args[])
{

// main() method

main() method public static void


public main() methodstatic main()

void main()Main
String args[]

2.2.4

Java

Java

//Java

int num ;

//

/*
*/

22


/*
int c = 10 ;
int x = 5 ;
*/
/**
*/ javadoc

2.2.5

Java

Java
_$ Java

yourname
your_name
_yourname
$yourname

class
67.9
Hello Careers

23

2.2.6

Java

Java publicstatic
Java

Java
abstract

boolean

break

byte

case

catch

char

class

continue

default

do

double

else

extend

false

final

finally

float

for

if

implement

import

instanceof

int

interface

long

native

new

null

package

private

protected

public

return

short

static

synchronized super

this

throw

throws

transient

true

void

volatile

while

try

gotoconst Java

2.2.7

Java

2.2.7.1

num

24


int num;

// num

int Java Integer

int num,num1,num2 ;

2.2.7.2

// num,num1,num2

Java Java
intlongshortfloatdouble
charString

2.2.7.3

Java
num a
bc

2.2.7.4

2-2-5

25

2.2.8

1
num 2

int num = 2 ;

//

num1num2 ch
int num1,num2 ; //
char c ;
num1 = 2 ;

//

num2 = 3 ;
ch = 'z' ;
3
num
int num ;

//

num = 2 ;

2.2.9

//

println()

1 System.out.println()

26

println()
System.out
println print line

20
! 20 num
TestJava2_3.java
01
02
03
04
05
06
07
08
09

//
public class TestJava2_3
{
public static void main(String args[])
{
int num = 2 ;
// 2
System.out.println(" "+num+" ! ");
}
}

20

TestJava2_3 println()

2.3

27

TestJava2_4.java
01
02
03
04
05
06
07
08
09
10
11
12

//
public class TestJava2_4
{
public static void main(String args[])
{
int num1 = 2 ;
// num1 2
int num2 = 3 ;
num2 3
System.out.println(" "+num1" ");
System.out.println(" "+num2+"")
)
}

2.3.1

TestJava2_4
4 main() method
11 main() method
Careers2_4
// 7 // 9
+ 10

28


2
3

2.3.2

TestJava2_5.java
01 //
//
02 public class TestJava2_5
03 {
04
public static void main(String args[])
05
{
06
int num1 = 4 ;
// num1
07
int num2 = 5 ;
// num2
08
09
System.out.println(" "+num1+" ! ");
10
System.out.println(" "+num2+" ! ");
11
// num1-num2 s
12
System.out.println(" "+(num1-num2)+ " ! ");
13
}
14 }

4 !
5 !
1 !

29


12 num1+num2
num1-num2

2.4

TestJava2_6.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14

//
public class Careers2_6
{
public static void main(String args[])
{
int x ;
for(x=1;x<=3;x++)
{
System.out.print("x = "+x+", ");
System.out.println("x * x = "+(x*x));
}
}
}

30


TestJava2_7.java
01 //
//
02 public class TestJava2_7{
03 public static void main(String args[]){
04 int x ; for(x=1;x<=3;x++){
05 System.out.print("x = "+x+", ");
06 System.out.println("x * x = "+(x*x));}}}
TestJava2_7
TestJava2_6

TestJava2_6 TestJava2_7
x=1,x*x=1
x=2,x*x=4
x=3,x*x=9

31


1 Java
1
//
2
/**/
3
2 public

3 main() Java method public


main() method void

4 System.out println print line

5 Java Java
6 Java _$
Java Java

8
1
2
3
4

32

3
3.1

Java

Java

booleanbytechar
shortintlongfloat double
C / C++

3.1.1

Java
Java num ch

TestJava3_1.java
01 //
02 public class TestJava 3_1
03 {
04
public static void main(String args[])
05
{
06
int num = 3 ;
// num 3
07
char ch = 'z';
// ch z

33

08
09
10
11 }

System.out.println(num+ "");
System.out.println(ch + "");

// num
// ch

3
z
TestJava 3_1 num ch 3
z

TestJava 3_1 6 num


3 num 3
7 ch'z'

3.1.2

Java

Java
3-1

34

3-1

Java

3.1.3

Java

Java 3-1
3-1

Java

long

-9223372036854775808 ~ 9223372036854775807

int

-2147483648 ~ 2147483647

short

-32768 ~ 32767

byte

-128 ~ 127

char

0 ~ 255

boolean

true false

float

-3.4E38-3.41038 ~ 3.4E383.41038

double

-1.7E308-1.710308~ 1.7E3081.710308

35

3.1.3.1

3-147
Java longintshort byte long 64
8 bytes-9223372036854775808 9223372036854775807int
32 4 -2147483648 2147483647
-32768 32767 short
-128 127 byte
sum
short sum ;

// snum

Java 2
sum -32768 32767

3.1.3.1.1

Java int
2147483647

TestJava3_2.java
01
02
03
04
05
06
07
08
09

//
public class TestJava3_2
{
public static void main(String args[])
{
long num = 329852547553;
//
System.out.println(num = +num);
}
}

36


TestJava3_2.java:5: integer number too large: 329852547553
long num = 329852547553;
int 329852547553 int
num long
L
long 6
06

long num = 329852547553L ;

3.1.3.1.2

Java longintshort byte


MAX_VALUE MIN_VALUE

3-2

3-2

java.lang Java

37

Java 3-2

3-2
Long

int

java.lang.Long

java.lang.Integer

MAX_VALUE

MAX_VALUE

9223372036854775807

2147483647

MIN_VALUE

MIN_VALUE

-9223372036854775808

-2147483648

short

byte

java.lang.Short

java.lang.Byte

MAX_VALUE

MAX_VALUE

32767

127

MIN_VALUE

MIN_VALUE

-32768

-128

Java

TestJava3_3.java
01 // 3-2
02 public class TestJava3_3
03 {
04
public static void main(String args[])
05
{
06
long long_max = java.lang.Long.MAX_VALUE ;//
07
int int_max = java.lang.Integer.MAX_VALUE ; //
08
short short_max = Short.MAX_VALUE ;
//
09
byte byte_max = Byte.MAX_VALUE ;
// Byte
10
11
System.out.println("LONG "+long_max);

38

12
13
14
15
16 }

System.out.println("INT "+int_max);
System.out.println("SHORT "+short_max);
System.out.println("BYTE "+byte_max);
}

LONG 9223372036854775807
INT 2147483647
SHORT 32767
BYTE 127

TestJava3_3
Java

3.1.3.1.3

1 2
TestJava3_4.java
01 //
02 public class TestJava3_4
03 {
04
public static void main(String args[])
05
{
06
int x = java.lang.Integer.MAX_VALUE ;
//
07
08
System.out.println("x = "+x);

39

09
10
11
12 }

System.out.println("x+1 = "+(x+1));
System.out.println("x+2 = "+(x+2));
}

x = 2147483647
x+1 = -2147483648
x+2 = -2147483647

1 2

i-2147483648 ~ 2147483647 i
2147483647 x 1 2 x
-2147483648 -2147483647

-2147483648 x 1 -2147483648
3-3

3-3

int L
long TestJava3_5

40

TestJava3_5.java
01
02
03
04
05
06
06
08
09
10
11
12
13

//
public class TestJava3_5
{
public static void main(String args[])
{
int x = java.lang.Integer.MAX_VALUE ;
System.out.println("x = "+x);
System.out.println("x + 1 = "+(x+1));
System.out.println("x + 2 = "+(x+2L));
System.out.println("x + 3 = "+((long)x+3));
}
}

x = 2147483647
x + 1 = -2147483648
x + 2 = 2147483649
x + 3 = 2147483650

1 6 int x 2147483647
2 8 x 2147483647
3 9 x+1 -2147483648
4 10 x+2 2 L
2147483649
5 11 x+3 x long
2147483650

int
long

41

3.1.3.2

0 1 0 1

ASCII

Unicode
Java
Unicode
Unicode a 97
ch1ch2 ch1 97ch2 a
ch1 ch2
TestJava3_6.java
01 //
02 public class TestJava3_6
03 {
04
public static void main(String args[])
05
{
06
char ch1 = 97 ;
07
char ch2 = 'a' ;
08
09
System.out.println("ch1 = "+ch1);

42

10
11
12 }

System.out.println("ch2 = "+ch2);
}

ch1 = a
ch2 = a

' '

ch ch
\"
3-3
3-3

\f

\\

\b

\'

\r

\"

\t

\n

ch \"'
ch

TestJava3_7.java
01 //
02 public class TestJava3_7
03 {
04
public static void main(String args[])
05
{
06
char ch =' \" ';

43

07
08
09
10
11 }

System.out.println(ch+""+ch);
System.out.println("\"hello world\"");
}

""
"hello world"

3.1.3.3

Javafloat 4
-3.41038 3.41038double
8 -1.710308
1.710308

double num float sum


sum 3.0
double num ;

// sum

float sum = 3.0f ;

// sum 3.0

Java 8 num

44

-1.710308 1.710308 4 sum


-3.41038 3.41038sum
3.0

float double
double num1 = -6.3e64 ;

// num1 double-6.31064

double num2 = -5.34E16 ;

// e E

float num3 = 7.32f ;

// num3 float 7.32f

float num4 = 2.456E67 ;

// 2.4561067 float

double D
d double Java D d
F f float Java double

float num
3.0 num*num
TestJava3_8.java
01
02
03
04
05
06
07
08
09

//
public class TestJava3_8
{
public static void main(String args[])
{
float num = 3.0f ;
System.out.println(num+" *"+num+" = "+(num*num));
}
}

3.0 * 3.0 = 9.0

45

Java
3-4
3-4

float

double

java.lang.Float

java.lang.Double

MAX_VALUE

MAX_VALUE

3.4028235E38

107976931348623157E308

MIN_VALUE

MIN_VALUE

1.4E-45

4.9E-324

java.lang
float double

TestJava3_9.java
01
02
03
04
05
06
07
08
09
10
11

//
public class TestJava3_9
{
public static void main(String args[])
{
System.out.println("float_max = "+java.lang.Float.MAX_VALUE);
System.out.println("float_min = "+java.lang.Float.MIN_VALUE);
System.out.println("double_max = "+java.lang.Double.MAX_VALUE);
System.out.println("double_min = "+java.lang.Double.MIN_VALUE);
}
}

float_max = 3.4028235E38
float_min = 1.4E-45
double_max = 1.7976931348623157E308
double_min = 4.9E-324

46

3.1.3.4

boolean true false


true false
status
true
boolean status = true ;

// status true

true status
TestJava3_10

TestJava3_10.java
01
02
03
04
05
06
08
09
10
11

//
public class TestJava3_10
{
public static void main(String args[])
{
// status true false
boolean status = true ;
System.out.println("status = "+status);
}
}

status = true

47

3.1.3.5

Java
3-5
3-5

byte

byte0

short

short0

int

long

0L

float

0.0f

double

0.0d

char

\u0000

boolean

false

Java

3.1.4

Java
Java

48

3.1.4.1

Java

1
2

short a int short int


1 int short 2 Java
short a int

short byteJava
short byte int
Java

boolean true flase

TestJava3_11.java
01 //
02 public class TestJava3_11
03 {
04
public static void main(String args[])
05
{
06
int a = 156 ;
07
float b = 24.1f ;
// f
08
09
System.out.println("a = "+a+" , b = "+b);

49

10
11
12 }

System.out.println("a / b = "+(a/b));

//

a = 156 , b = 24.0
a / b = 6.5

Java

Java

3.1.4.2

8/3
2 2.6666 Java

3-1
;

Java
TestJava3_12
01 //
02 public class TestJava3_12
03 {
04
public static void main(String args[])
05
{

50

06
07
08
09
10
11
12
13
14
15
16
17 }

int a = 55 ;
int b= 9 ;
float g,h ;
System.out.println("a = "+a+" , b = "+b);
g = a/b ;
System.out.println("a / b ="+g+"\n");
System.out.println("a = "+a+" , b = "+b);
h = (float)a/b ;
//
System.out.println("a /b = "+h);
}

a = 55 , b = 9
a / b = 6.0
a = 55 , b = 9
a /b = 6.111111

(float)a/b

// a b

a/(float)b

// b a

(float)a/(/float)b

// a b

Java

51

3.2

Java

Java

3.2.1

Java

-
*
/
%z+100
z100
+

3-4

Java

3.2.1.1

= 3-6
Java

52

3-6

= Java

3-5

22 num

num = num 3

// num-3 num

C C++=

num-3 num num


22Java num-3 19

num num 19

TestJava3_13.java
01 // =
02 public class TestJava4_1
03 {
04
public static void main(String args[])
05
{
06
int num = 22 ;
// num 22

53

07
08
09
10
11
12
13 }

System.out.println("num = "+num);

// num

num = num 3 ;
// num num
System.out.println("num = "+num);// num
}

num = 22
num = 19

in sum = num1+num2 ;

// num1 num2 sum

num1 num2 sum

3.2.1.2

+3 ;

// 3

~a ;

// a

b = -a ; // a b
!a ;

// a NOT a !a 1 a !a

3-7

54

3-7

NOT

byte a boolean b
~

TestJava3_14.java
01
02
03
04
05
06
07
08
09
10
11
12

//
public class TestJava3_14
{
public static void main(String args[])
{
byte a = java.lang.Byte.MAX_VALUE ; // a
boolean b = false ;
System.out.println("a = "+a+" , ~a = "+(~a));
System.out.println("b = "+b+" , !b = "+(!b));
}
}

a = 127 , ~a = 128
b = false , !b = true

1 6 byte a a 127 7
boolean b false
2 9 a ~a

55

3 10 b b b flaseb
true

3.2.1.3

3-8
3-8

3.2.1.3.1

+
System.out.println("3 + 8 = "+(3+8));

3.2.1.3.2

//

num = num 3 ;

// num-3 num

a=bc;

// bc a

120 - 10 ;

// 120 10

56

3.2.1.3.3

*
b=b*5;

// b*5 b

a = a *a ;

// a * a a

19 * 2 ;

// 19 * 2

3.2.1.3.4

/
a=b/5;

// b / 5 a

c=c/d;

// c / d c

15 / 5 ;

// 14 / 7

abcd

ab
a / b
TestJava3_15.java
01 //
02 public class TestJava3_15
03 {
04
public static void main(String[] args)
05
{
06
int a = 13 ;
07
int b = 4 ;
08
09
System.out.println("a = "+a+" , b = "+b);
10
System.out.println("a / b = "+(a/b));
11
System.out.println("a / b = "+((float)a/b));

57

//

12
13 }

a = 13 , b = 4
a/b=3
a / b = 3.25

1 10 11 10 ab

2 11
intfloat

3.2.1.3.5

num = num % 3 ;

// num%3 num

a=b%c;

// b%c a

100 % 7 ;

// 100%7

ab 5 3 a%b

TestJava3_16.java
01 // JAVA %
02 public class TestJava3_16
03 {

58

04
05
06
07
08
09
10
11
12 }

public static void main(String[] args)


{
int a = 5 ;
int b = 3 ;
System.out.println(a+" % "+b+" = "+(a%b));
System.out.println(b+" % "+a+" = "+(b%a));
}

5%3=2
3%5=3

3.2.1.4

if

if if
if
3-2 if
if ()

if (x>0)
System.out.println("I like Java ");

x 0I like Java
x 0 0 if

59

3-9

3-9

>

<

>=

<=

==

!=

Java
=
== 2
=
=

true false if
if

TestJava3_17.java
01 //
02 public class TestJava3_17
03 {
04
public static void main(String[] args)
05
{
06
if(5>2)
07
System.out.println(""+(5>2));
08
09
if(true)
10
System.out.println("Hello Java !");

60

11
12
13
14
15 }

if((3+6)==(3-6))
System.out.println("I like Java !");
}

true
Hello Java !

1 6 5>2 7 true
2 9 if true 10
Hello TestJava!
3 12 3+6 3-6if 13

3.2.1.5

C / C++Java
3-10
3-10

++

--

int a
1
a = a+1 ;

// a 1 a

a 1 a ++

61


a++ ;

// a 1 a a++

++++
++a a++a++
a 1++b b 1
a b 3 a++++b
TestJava3_18.java
01
02
03
04
05
06
07
08
09
10
11
12
13

// ++
public class TestJava3_18
{
public static void main(String args[])
{
int a = 3 , b = 3 ;
System.out.print("a = "+a);
System.out.println(" , a++ = "+(a++)+" , a= "+a);
System.out.print("b = "+b);
System.out.println(" , ++b = "+(++b)+" , b= "+b);

//
//
//
//

a
a++ a
b
++b b

}
}

a = 3 , a++ = 3 , a= 4
b = 3 , ++b = 4 , b= 4

1 9 a++ a a++a 1
4
2 11 ++b b ++b b 1
4
--++

62

++ 1-- 1
1 1 1
a = a+2

3.2.1.6

if 3-11
3-11

&&

AND

||

OR

&&
||

a>0 && b> 0

//

a>0 || b>0

//

1 a>0 b>0 true


2 a>0 b>0 true
3-12
3-12 AND OR

true

&&

||

true

true

true

true

false

false

true

false

true

false

true

false

false

false

false

63

3-12 false
falsetrue
true
a 0~100
a 50~60

TestJava3_19.java
01
02
03
04
05
06
07
08
09
10
11
12
13

//
public class TestJava3_19
{
public static void main(String[] args)
{
int a = 56 ;
if((a<0)||(a>100))
System.out.println("");
if((a<60)&&(a>49))
System.out.println("");
}
}

1 8 if a a<0 a>100
9
0~100 a

2 9 10 if a
a<60 a>49
11

64

3.2.1.7

Java 3-13

3-13

3+5+4*6-7

//

*/+- 25
3+5+4 6-7 3+5+4 6-7

(3+5+4)*(6-7)

//

-12

3.2.2

3-14

65

3-14

()

[]

!+
-
~

++-*/%

+<<>>

>>=<<=

==!=

& AND

^ XOR

10

| OR

11

&&

12

||

13

?:

14

2
2
3
4

3-14

a = b +d

/5*4;

/*+

+=/* d
5 4 5 4 d

/
* d 5 4 b
a

66

3.2.3

-49

// - 49

sum + 2

// sum 2

a + b c / ( d * 3 9 ) //

Java
3-15
3-15

+=

a += b

a + b a

a=a+b

-=

a -= b

a - b a

a=a-b

*=

a *= b

a * b a

a=a*b

/=

a /= b

a / b a

a=a/b

%=

a %= b

a % b a

a=a%b

a++

// a = a + 1

a -= 5

// a = a 5

b %= c

// b = b % c

a /= b--

// a = a / b b--

67

TestJava3_20.java
01
02
03
04
05
06
07
08
09
10
11
12

//
public class TestJava3_20
{
public static void main(String[] args)
{
int a = 5 , b = 8 ;
System.out.println(" a = "+a+" , b = "+b);
a +=b ;
System.out.println(" a = "+a+" , b = "+b);
}
}

a = 5 , b = 8
a = 13 , b = 8

1 6 ab 5 8
2 8 ab a 5b 8
3 9 a+=b a = a +b a+b a
5+8 a
4 10 ab a 13 b 8

3-16

68

3-16

+=

a += b

12

-=

a -= b

12

*=

a *= b

/=

a + b a a = a + b

16

a - b a a = a b

12

a * b a a = a * b

48

a /= b

12

a / b a a = a / b

%=

a %= b

12

a % b a a = a % b

B++

a *= b++

12

48

++b

a *= ++b

12

b 1 a*b a
b++a=a*b

60

b--

a *= b--

12

a * b a b 1
a=a*bb--

48

--b

a *= --b

12

b 1 a*b a
b--a=a*b

36

a * b a b 1
a = a * bb++

TestJava3_21

TestJava3_21.java
01
02
03
04
05
06
07
08
09
10
11
12

//
public class TestJava3_21
{
public static void main(String[] args)
{
int a = 10 , b = 6 ;
System.out.println(" a = "+a+" , b = "+b);
a -= b++ ;
// a-b a b 1
System.out.println(" a = "+a+" , b = "+b);
}
}

69


a = 10 , b = 6
a = 4 , b = 7

1 8 ab ab 106
a 10b 6
2 9 a -= b++
a = a- b ;

//a = 10 - 6 = 4 a = 4

b++ ;

//b = b+1 = 6+1 = 7 b = 7

3 10 a 4b 7

3.2.4

int float

Java

Java

1
2 int
3 int float
4 double double

70

TestJava3_22.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15

//
public class TestJava3_22
{
public static void main(String[] args)
{
char ch = 'a' ;
short a = -2 ;
int b = 3 ;
float f = 5.3f ;
double d = 6.28 ;
System.out.print("(ch / a) - (d / f) - (a + b) = ");
System.out.println((ch / a) - (d / f) - (a + b));
}
}

(ch / a) - (d / f) - (a + b) = -50.18490561773532
ch / a- (d
/ f) (b + a)
3-6

3-6

71

3.3

3.3.1

1
2
3

3.3.1.1

3-7

72

3-7

3.3.1.2

3-8

3-8

73


1 2
3
a b a b a-b a
b a*b

TestJava3_23.java
01
02
03
04
05
06
07
08
09
10
11
12
13

// if
public class TestJava3_23
{
public static void main(String[] args)
{
int a = 6 , b = 5 ;
System.out.println("a = "+a+" , b = "+b);
if(a>b)
System.out.println("a - b = "+(a-b));
System.out.println("a * b = "+(a*b));
}
}

a=6,b=5
a-b=1
a * b = 30

6 ab a b
a b 11

74

3.3.1.3

3-9

3-9

3.3.2

ifif..else switch
if

3.3.2.1

if

if if

75

if
3-3 if
if ()
{
1
2

3
}
if 1
if 3-10

3-10 if
if ifelse if

ifelse

76

3.3.2.2

ifelse

if...else
if else ifelse

3-4 ifelse
if ()
{
1
}
else
{
2
}
if else
ifelse 3-17

3-17 if..else

77

a 5 a

TestJava3_24.java
01
02
03
04
05
06
07
08
09
10
11
12
13

// if...else
public class TestJava3_24
{
public static void main(String[] args)
{
int a = 5 ;
if(a%2 = = 1)
System.out.println(a+" ");
else
System.out.println(a+" ");
}
}

1 8~11 if..else 8 if a%2 = = 1 a 2


1 a a 2 0
a
2 a 2 1 9 a
11 a
3 a

78

3.3.2.3

ifelse 3-17
3-17

?:

3
3-5 ifelse
1 2
if 1
2
if..else
3-6 ifelse
if ()
x = 1
else
x = 2
ab

TestJava3_25.java
01 //
02 public class TestJava3_25
03 {
04
public static void main(String[] args)

79

05
06
07
08
09
10
11
12
13 }

{
int a = 5 , b = 13 , max ;
max = (a>b)?a:b ;
System.out.println("a = "+a+" , b = "+b);
System.out.println(" "+max);
}

a = 5 , b = 13
13

1 6 ab max

2 8 max = (a>b)?a:b a>b max = a max = b


3 10 ab 11
4 ab

if..else

3.3.2.4

if..else if..else

if..else if..else if else

80

3-7 ifelse if else

if ( 1)
{
1
}
else if ( 2)
{
2
}
.
// else if()
else
{
3
}

TestJava3_26.java
01 // if..else if ...else
02 public class TestJava3_26
03 {
04
public static void main(String[] args)
05
{
06
07
08
09
10
11
12
13
14
15
16

int x = 1 ;
if(x= =1)
System.out.println("x = = 1");
else if(x= =2)
System.out.println("x = = 2");
else if(x= =3)
System.out.println("x = = 3");
else
System.out.println("x > 3");
}

81

17 }

x==1
if else if ..else if..else

3.3.3

switch

switch
switch break switch
break switch

if..else switch
if..else if else
swtich

switch
3-8

switch

switch ()
{
case 1 1
break
case 2 2
break
.
case n n
break
default
}

82

switch
switch
1 switch
2 case case
default switch
3 case case
break switch
4 case break switch
switch break break

5 default switch
3-18 switch

3-18 switch

83

switch

TestJava3_27.java
01 //
02 public class TestJava3_27
03 {
04
public static void main(String[] args)
05
{
06
int a = 100 , b = 7 ;
07
char oper ='/' ;
08
09
switch(oper)
// switch
10
{
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 }

case '+':
System.out.println(a+" + "+b+" = "+(a+b));
break ;
case '-':
System.out.println(a+" - "+b+" = "+(a-b));
break ;
case '*':
System.out.println(a+" * "+b+" = "+(a*b));
break ;
case '/':
System.out.println(a+" / "+b+" = "+((float)a/b));
break ;
default:
System.out.println("");
}
}

100 / 7 = 14.285714

84


1 7 3+25*7
2 9~25 switch oper +-*/%
switch default :

switch
3

break
switch break

3.3.4

while

while
while while
3-9

while

while ()
{
1
2

n
}
while while

while
while

1 while
2 True

85

False
3
while
while
2

3-19 while

3-19 while
1 10

TestJava3_28.java
01 // while
02 public class TestJava3_28
03 {
04
public static void main(String[] args)
05
{
06
int i = 1 ,sum = 0 ;
07
08
while(i<=10)

86

09
10
11
12
13
14
15 }

{
sum += i ;
i++ ;

//

}
System.out.println("1 + 2 + ...+ 10 = "+sum);

//

1 + 2 + ...+ 10 = 55

1 6 i 1
2 8 while i<=10 i 1

3 9~12 sum+i sum i 1


i i 10
sum

3.3.5

dowhile

dowhile while dowhile


while while
dowhile
dowhile
dowhile

87

3-10 dowhile
Do
{
1
2
.
n
}while ();
do..while

dowhile dowhile
1 do...whle
2
True
False
3
dowhile while
dowhile
2

3-20 do..while

88

3-20 dowhle
TestJava3_28.java1+2++10 dowhile
n n n 0
TestJava3_29.java

TestJava3_29.java
01 // do...while
02 public class TestJava3_29
03 {
04
public static void main(String[] args)
05
{
06
int i = 1 ,sum = 0 ;
07
// do.while
08
do
09
{
10
sum += i ;
//

89

11
12
13
14
15 }

i++ ;
}while(i<=10);
System.out.println("1 + 2 + ...+ 10 = "+sum);

//

1 + 2 + ...+ 10 = 55


i sum
sum 0 1+2++10 i
1 i 10 i 10 sum+i
sum i i
sum

1 08~12 dowhile 1~10


2 13 1~10 1 + 2 + ...+ 10 = 55

do..while
dowhile

dowhile

3.3.6

for

for

90

3-11 for
for ()
{
1
.
n
}

1 for

1 for
2 true
false

3
2

3-21 for

91

3-21 for
TestJava3_30 for for
1 10

TestJava3_30.java
01
02
03
04
05
06
07
08
09
10
11
12

// for
public class TestJava3_30
{
public static void main(String[] args)
{
int i , sum = 0 ;
// for
for(i=1;i<=10;i++)
sum += i ;
// sum = sum+i
System.out.println("1 + 2 + ... + 10 = "+sum);
}
}

92


1 + 2 + ... + 10 = 55

1 06 sum iI
2 08~09 1~10 TestJava3_28
TestJava3_28 for

3.3.7

for while

TestJava3_31.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15

// for
public class TestJava3_31
{
public static void main(String[] args)
{
int i , j ;
// for
for(i=1;i<=9;i++)
{
for(j=1;j<=9;j++)
System.out.print(i+"*"+j+"="+(i*j)+"\t");
System.out.print("\n");
}
}
}

93


1*1=1

1*2=2

1*3=3

1*4=4

1*5=5

1*6=6

1*7=7

1*8=8

1*9=9

2*1=2

2*2=4

2*3=6

2*4=8

2*5=10 2*6=12 2*7=14

2*8=16 2*9=18

3*1=3

3*2=6

3*3=9

3*4=12

3*5=15 3*6=18 3*7=21

3*8=24 3*9=27

4*1=4

4*2=8

4*3=12 4*4=16

4*5=20 4*6=24 4*7=28

4*8=32 4*9=36

5*1=5

5*2=10 5*3=15 5*4=20

5*5=25 5*6=30 5*7=35

5*8=40 5*9=45

6*1=6

6*2=12 6*3=18 6*4=24

6*5=30 6*6=36 6*7=42

6*8=48 6*9=54

7*1=7

7*2=14 7*3=21 7*4=28

7*5=35 7*6=42 7*7=49

7*8=56 7*9=63

8*1=8

8*2=16 8*3=24 8*4=32

8*5=40 8*6=48 8*7=56

8*8=64 8*9=72

9*1=9

9*2=18 9*3=27 9*4=36

9*5=45 9*6=54 9*7=63

9*8=72 9*9=81

1 i j
2 i 1 for i<=9 for
j 1 for
j<=9
i*j 1*1=1j 1 2
for j<=9 j 9
for i 1 2 for
for i 9
3 i 1 9
j 1~9, i 2 9 j 1~9
81 81

3.3.8

Java breakcontinue

break continue

94

3.3.8.1

break

break break
break break
for break
break
3-12 break
for ()
{
1
2

break

// break
n
}

for i i 3
0 break I

TestJava3_32.java
01 // break
02 public class TestJava3_32
03 {
04
public static void main(String[] args)
05
{
06
int i ;
07
08
for(i=1;i<=10;i++)
09
{
10
if(i%3 == 0)

95

11
12
13
14
15
16 }

break ;
//
System.out.println("i = "+i);
}
System.out.println("i = "+i);
}

i=1
i=2
i = 3

1 9~13 i
2 i%3 0 if 11 break for
i 3 3%3 0 if for
14 i 3

break if
switch break

3.3.8.2

continue

continue continue
for
continue continue

96

3-13 continue
for ()
{
1
2

continue
// continue
n
}
.
TestJava3_32 break continue
TestJava3_33.javabreak
continue

TestJava3_33.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16

// continue
public class TestJava3_33
{
public static void main(String[] args)
{
int i ;
for(i=1;i<=10;i++)
{
if(i%3==0)
continue ;
//
System.out.println("i = "+i);
}
System.out.println("i = "+i);
}
}

97


i=1
i=2
i=4
i=5
i=7
i=8
i = 10
i = 11

1 9~13 i
2 i%3 0 if 11 continue
for
i 369 0 if
for
3 i 11 14
i 11

break continue Break


continue

3.3.9

Java

98

TestJava3_34.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14

// for
public class TestJava3_34
{
public static void main(String[] args)
{
int sum = 0 ;
// for 1~5
for(int i=1;i<=5;i++)
{
sum = sum + i ;
System.out.println("i = "+i+", sum = "+sum);
}
}
}

i = 1, sum = 1
i = 2, sum = 3
i = 3, sum = 6
i = 4, sum = 10
i = 5, sum = 15

TestJava3_34 i for i
for 8~12 i
sum main() 6
12 for sum

99


1 Java
2 Java longintshort byte
MAX_VALUE MIN_VALUE

3 Unicode

4 boolean true false


5

6
7 +3~a-a!a

9 if
10
4-5
11 Java
12
1

2 short int int


3
short
4int float
5
double double
6

13123
14
Java forwhile dowhile
15break break
break
break
16continue continue

100


17 ifif-else switch

18

101

4.1

4.1.1

Java
1
2

4-1

[ ]
new [] ;

//
//

new

102

int score[] ;

// score

score = new int[3];

// score 4

score score

4-1

4-1

3 score
4-2

4-2

103

Ox1000 3
score

4-1

4-2
[] = new []

score 11 score
int score[] = new int[11] ;
// 10 score

Java 4 bytes score


11 4 * 11 = 44 4-3 score

4-3

4.1.2

Java 0
score score[0] 1 score[1] 2 score[9]
10 4-4 score

104

4-4

3
for

TestJava4_1.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15

//
public class TestJava4_1
{
public static void main(String args[])
{
int i;
int a[];
// a
a=new int[3];
// a 3
for(i=0;i<3;i++)
//
System.out.print("a["+i+"] = "+a[i]+",\t");
System.out.println("\n "+a.length);
}
}

a[0] = 0, a[1] = 0, a[2] = 0,


3

105

//


1 7 a 8 a
3
2 10~11 for
0
3 13 3 3

Java
.length

4-3

.length
TestJava4_1 a a
.length
a.length ;

4.1.3

//

4-4
[] = { 0 1 n}
1n+1

106


int day[] = {32,23,45,22,13,45,78,96,43,32};

//

day
10 day[0] 32
day[1] 23day[9] 32
TestJava4_2.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14

//
public class TestJava4_2
{
public static void main(String args[])
{
int i;
int a[]={5,6,8};
// a
for(i=0;i<a.length;i++)
//
System.out.print("a["+i+"]="+a[i]+",\t");
System.out.println("\n "+a.length);
}
}

a[0]=5,

a[1]=6,

a[2]=8,

TestJava4_2 7
int a [] = new int[] ;
a[0] = 5 ;
a[1] = 6 ;
a[2] = 8 ;

107

4.1.4

TestJava4_3.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22

//
public class TestJava4_3
{
public static void main(String args[])
{
int i,min,max;
int A[]={74,48,30,17,62};
// A,
min=max=A[0];
System.out.print(" A ");
for(i=0;i<A.length;i++)
{
System.out.print(A[i]+" ");
if(A[i]>max)
//
max=A[i];
if(A[i]<min)
//
min=A[i];
}
System.out.println("\n "+max);
//
System.out.println(""+min);
//
}
}

108


A 74 48 30 17

62

74
17

1 6 i
min max
2 7 A 5 7448301762
3 9 min max
4 10~18
5 19~20

min max
min min min
max max max for
min max

4.1.5

API

Java API

JDK
TestJava4_4.java
01 //
02 public class TestJava4_4
03 {
04
public static void main(String[] args)

109

05
06
07
08
09
10
11
12
13
14
15
16
17
18
19 }

{
int a1[] = {1,2,3,4,5} ; // a1a2
int a2[] = {9,8,7,6,5,4,3} ;
System.arraycopy(a1,0,a2,0,3);
//
System.out.print("a1 ");
for(int i=0;i<a1.length;i++)
// a1
System.out.print(a1[i]+" ");
System.out.println();
System.out.print("a2 ");
for(int i=0;i<a2.length;i++)
// a2
System.out.print(a2[i] +" ");
System.out.println("\n ");
}

a1 1

2 3 4

a2 1

2 3 6

5 4 3

System.arrayCopy(source,0,dest,0,x) 0
x 0

TestJava4_5.java
01
02
03
04
05
06
07
08
09
10

// sort
import java.util.*;
public class TestJava4_5
{
public static void main(String[] args)
{
int a[] = {4,32,45,32,65,32,2} ;
System.out.print("");
for(int i=0;i<a.length;i++)

110

11
12
13
14
15
16
17 }

System.out.print(a[i]+" ");
Arrays.sort(a);
//
System.out.print("\n ");
for(int i=0;i<a.length;i++)
System.out.print(a[i]+" ");
}

4 32 45 32 65
2 4

32

32

32 32 45 65

12 Arrays.sort() java.util

4.2

Java

4.2.1

new

4-5
[][]
= new [][]

111


4-5

// score

int score[][] ;

score = new int[4][3] ; // 4 3 score

4-6
[][] = new [][]

int score[][] = new int[4][3] ; // score

score 4*3 = 12 Java int


4 4*12 = 48

4-7

[][] = {

{ 0 },
{ 1 }

{ n },

};

01n num

112

int num[][] = {
//

{23,45,21,45},
{45,23,46,23}
};

num 2 4 8
num[0][0] 23num[0][1]
45num[1][3] 23

4.2.1.1

Java
num
num 4 3 5

int num[][] = {
{42,54,34,67},
{33,34,56},
{12,34,56,78,90}
};

4.2.1.2

.length

113

4-8
.length
[].length

//
//

.length

.length
num.length;
num[0].length
num[2].length

4.2.2

// num 3
// num 1 4
// num 3 5

TestJava4_6.java
01 //
02 public class TestJava4_6
03 {
04
public static void main(String args[])
05
{
06
int i,j,sum=0;
07
int num[][]={{30,35,26,32},{33,34,30,29}};
//
08
09
for(i=0;i<num.length;i++)
//
10
{
11
System.out.print(" "+(i+1)+" ");
12
for(j=0;j<num[i].length;j++)
13
{
14
System.out.print(num[i][j]+" ");
15
sum+=num[i][j];
16
}
17
System.out.println();

114

18
19
20
21 }

}
System.out.println("\n "+sum+" ");
}

1 30 35 26 32
2 33 34 30 29
249

1 6 ij i
j sum

2 7 num 8
3 9~18
4 19 sum

4.3

int A[][][]
int A[][][][]

TestJava4_7.java
01 //
02 public class TestJava4_7

115

03 {
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19 }

public static void main(String args[])


{
int i,j,k,sum=0;
int A[][][]={{{5,1},{6,7}},{{9,4},{8,3}}};
//
// for
for(i=0;i<A.length;i++)
//
for(j=0;j<A[i].length;j++)
for(k=0;k<A[j].length;k++)
{
System.out.print("A["+i+"]["+j+"]["+k+"]=");
System.out.println(A[i][j][k]);
sum+=A[i][j][k];
}
System.out.println("sum="+sum);
}

A[0][0][0]=5
A[0][0][1]=1
A[0][1][0]=6
A[0][1][1]=7
A[1][0][0]=9
A[1][0][1]=4
A[1][1][0]=8
A[1][1][1]=3
sum=43

4.4

main()

116

4-9
1 2
{

return
}

return

4.4.1

TestJava4_8 19 *
I Like Java 19

TestJava4_8.java
01 //
02 public class TestJava4_8
03 {
04
public static void main(String args[])
05
{
06
star();
// star()
07
System.out.println("I Like Java !");
08
star();
// star()
09
}
10
11
public static void star()
// star()
12
{
13
for(int i=0;i<19;i++)

117

14
15
16
17 }

// 19
//

System.out.print("*");
System.out.print("\n");
}

*******************
I Like Java !
*******************
TestJava4_8 main() star() main()
star() main() main() 6
start() 11~16 star()
main() 7 I Like Java
8 sart() 11~16 star()
main() main()
TestJava4_8

TestJava4_8 star()
4-5

4-5

star()

118

TestJava4_8 star()
star() void star()
star()
star() static main()
static static static
star() main() star() static
static static

4.4.2

TestJava4_9
n 2*n
2*n

TestJava4_9
01 //
02 public class TestJava4_9
03 {
04
public static void main(String args[])
05
{
06
int num;
07
num=star(7);
// 7 star() num
08
System.out.println(num+" stars printed");
09
}
10
11
public static int star(int n)
// star() method
12
{
13
for(int i=1;i<=2*n;i++)
14
System.out.print("*");
// 2*n
15
System.out.print("\n");
//
16
return 2*n;
// 2*n
17
}

119

18 }

**************
14 stars printed
TestJava4_9 star() 11 star()
int star() star()

TestJava4_10 show_length()

TestJava4_10.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15

//
public class TestJava4_10
{
public static void main(String args[])
{
double num;
num=show_length(22,19); // 22 19 show_length()
System.out.println(" = "+num);
}
public static double show_length(int m, int n)
{
return Math.sqrt(m*m+n*n);
//
}
}

= 29.068883707497267

TestJava4_10 7 show_length(22,19) 22 19 show_length()

120

13 Math sqrt() sqrt(n)


n sqrt() double show_length() double

4.4.3

TestJava4_11.java
01 //
02 public class TestJava4_11
03 {
04
public static void main(String[] args)
05
{
06
int int_sum ;
07
double double_sum ;
08
int_sum = add(3,5) ;
// add
09
System.out.println("int_sum = add(3,5)"+int_sum);
10
int_sum = add(3,5,6) ;
// add
11
System.out.println("int_sum = add(3,5,6)"+int_sum);
12
double_sum = add(3.2,6.5); // doule
13
System.out.println("double_sum = add(3.2,6.5)"+double_sum);
14
}
15
public static int add(int x,int y)
16
{
17
return x+y ;
18
}
19
public static int add(int x,int y,int z)
20
{
21
return x+y+z ;
22
}
23
public static double add(double x,double y)

121

24
25
26
27 }

{
return x+y ;
}

int_sum = add(3,5)8
int_sum = add(3,5,6)14
double_sum = add(3.2,6.5)9.7
add

4.4.4

Java

4.4.4.1

TestJava4_12
largest() largest()

TestJava4_12.java
01 //
02 public class TestJava4_12
03 {
04
public static void main(String args[])
05
{
06
int score[]={7,3,8,19,6,22};
// score
07
largest(score);
// score largest()

122

08
09
10
11
12
13
14
15
16
17
18
19 }

public static void largest(int arr[])


{
int tmp=arr[0];
for(int i=0;i<arr.length;i++)
if(tmp<arr[i])
tmp=arr[i];
System.out.println(" = "+tmp);
}

= 22

TestJava4_12 11~18 largest()


13~17
7

4.4.4.2

TestJava4_13 A
print_mat() print_mat()

TestJava4_13.java
01 //
02 public class TestJava4_13
03 {
04
public static void main(String args[])
05
{

123

06
07
08
09
10
11
12
13
14
15
16
17
18
19
20 }

int A[][]={{51,38,22,12,34},{72,64,19,31}};
print_mat(A);

// A

}
public static void print_mat(int arr[][]) //
{
for(int i=0;i<arr.length;i++)
{
for(int j=0;j<arr[i].length;j++)
System.out.print(arr[i][j]+" ");
//
System.out.print("\n"); //
}
}

51 38 22 12 34
72 64 19 31

TestJava4_13 11~18 print_mat()


for .length
13 15

4.4.4.3

int
int[]
int[][]
TestJava4_14.java add10()
add10() 10 main()

124

TestJava4_14.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

//
public class TestJava4_14
{
public static void main(String args[])
{
int A[][]={{51,38,82,12,34},{72,64,19,31}}; //
int B[][]=new int[2][5];
B=add10(A);
// add10() B
for(int i=0;i<B.length;i++)
//
{
for(int j=0;j<B[i].length;j++)
System.out.print(B[i][j]+" ");
System.out.print("\n");
}
}
public static int[][] add10(int arr[][])
{
for(int i=0;i<arr.length;i++)
for(int j=0;j<arr[i].length;j++)
arr[i][j]+=10;
// 10
return arr;
//
}
}

61 48 92 22 44
82 74 29 41

TestJava4_14 17 add10()
21
10 22 return

125

2 Java
1
2
3 Java .length
4

5 Java
6
.length
7

126

Java

Java

127

Java Java

class Java
Java

5.1

20 70
5-1

128

5-1

5.1.1

129

Java
Java

5.1.3

Java

Java

130

5.1.2

5.1.4

Java Java

131

Java interface
Java

5.1.5

Java

5.2

classobject

Instance 5-2

132

5-2

5.2.2

133

5-1
class
{

1 2
{

return
}

}
Person
Person.java
01 class Person
02 {
03
String name ;
04
int age ;
05
void talk()
06
{
07
System.out.println(""+name+""+age+"");
08
}
09 }

1 class Person Person


2 34 name agename String
age int
3 5~8 talk()

5-3

134

Person
+ name : String
+ age : int
+ talk () : void
5-3

Person

Person

5.2.3

Person

5-2
= new () ;

1 ""
2 new
Person
Person p

p = new Person() ;

// Person p
// new Person p

135


Person p = new Person() ;

// Person p

new

5-4

5-4

Person

Person p
Person p p p
new
p p

136

5-3

.
.()
Person name age
p.name ;

// Person name

p.age ;

// Person age

Person p name "" 25

p.name = "" ;
p.age = 25 ;
Person talk()
p.talk() ;

// Person talk()

Person.java
01 class Person
02 {
03
String name ;
04
int age ;
05
void talk()
06
{
07
System.out.println(""+name+""+age+"");
08
}
09 }

137

TestPersonDemo.java
01
02
03
04
05
06
07
08
09
10
11

// Person
class TestPersonDemo
{
public static void main(String[] args)
{
Person p = new Person() ;
p.name = "" ;
p.age = 25 ;
p.talk();
}
}

25

1 6 Person p
2 78 p
3 9 talk()
5-5 Java

5-5

Person p

138

5.2.4

TestPerson.java Person p
5-2
TestPersonDemo1.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

class Person
{
String name ;
int age ;
void talk()
{
System.out.println(""+name+""+age+"");
}
}
public class TestPersonDemo1
{
public static void main(String[] args)
{
// Person p1
Person p1 = new Person() ;
// Person p2
Person p2 = new Person() ;
// p1
p1.name = "" ;
p1.age = 25 ;
// p2
p2.name = "" ;
p2.age = 30 ;
// p1p2 talk()
p1.talk() ;
p2.talk() ;

139

30
31 }

25
30

1 1~9 Person nameage talk()

2 15~18 Person p1p2


3 2122 p1
4 2425 p2
5 2829 p1p2 Person talk()
5 p1 p2 p1 p2 p1
p2 5-6

5-6

Person p1 p2

p1 p2 p1p2
p1p2

140

5.3

TestPersonDemo2.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

class Person
{
String name ;
int age ;
void talk()
{
System.out.println(""+name+""+age+"");
}
}
public class TestPersonDemo2
{
public static void main(String[] args)
{
// Person p
Person p = new Person() ;
// p
p.name = "" ;
// p -25
p.age = -25 ;
// Person talk()
p.talk() ;
}
}

-25

141


1 1~9 Person nameage talk()

2 16 Person p
3 18~22 p talk()

20 age-25
talk()

private
TestPersonDemo2.java
TestPersonDemo3-1.java
TestPersonDemo3-1.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15

class Person
{
private String name ;
private int age ;
void talk()
{
System.out.println(""+name+""+age+"");
}
}
public class TestPersonDemo3-1
{
public static void main(String[] args)
{
// Person p

142

16
17
18
19
20
21
22
23
24 }

Person p = new Person() ;


// p
p.name = "" ;
// p -25
p.age = -25 ;
// Person talk()
p.talk() ;
}

TestPersonDemo3.java:18: name has private access in Person


p.name = "" ;
^
TestPersonDemo3.java:20: age has private access in Person
p.age = -25 ;
^
2 errors

1 1~9 Person nameage talk()


private

2 16 Person p
3 18~22 p talk()

nameage

setXxx()
getXxx()

143

TestPersonDemo3-2.java
01 class Person
02 {
03
private String name ;
04
private int age ;
05
void talk()
06
{
07
System.out.println(""+name+""+age+"");
08
}
09
public void setName(String str)
10
{
11
name = str ;
12
}
13
public void setAge(int a)
14
{
15
if(a>0)
16
age = a ;
17
}
18
public String getName()
19
{
20
return name ;
21
}
22
public int getAge()
23
{
24
return age ;
25
}
26 }
27
28 public class TestPersonDemo3-2
29 {
30
public static void main(String[] args)
31
{
32
// Person p
33
Person p = new Person() ;
34
// p
35
p.setName("") ;

144

36
37
38
39
40
41 }

// p -25
p.setAge(-25) ;
// Person talk()
p.talk() ;
}

1 9~25 setXxx()getXxx()

2 35 Person setName() 37
setAge()-25
3 13~17 0
age

-25 Person
age
0

private private
5-4
5-4

private
private

145


private
private

TestPersonDemo3-2.java talk()

TestPersonDemo4.java
01 class Person
02 {
03
private String name ;
04
private int age ;
05
private void talk()
06
{
07
System.out.println(""+name+""+age+"");
08
}
09
public void setName(String str)
10
{
11
name = str ;
12
}
13
public void setAge(int a)
14
{
15
if(a>0)
16
age = a ;
17
}
18
public String getName()
19
{
20
return name ;
21
}
22
public int getAge()
23
{
24
return age ;
25
}
26 }

146

27
28 public class TestPersonDemo4
29 {
30
public static void main(String[] args)
31
{
32
// Person p
33
Person p = new Person() ;
34
// p
35
p.setName("") ;
36
// p -25
37
p.setAge(-25) ;
38
// Person talk()
39
p.talk() ;
40
}
41 }

TestPersonDemo4.java:39: talk() has private access in Person


p.talk() ;
^
1 error

1 9~25 setXxx()getXxx()

2 35 Person setName()"" 37
setAge()-25
3 13~17 0
age
4 5 talk() private
private

147

setXxx()getXxx()

5.4

java

say()
talk()

TestPersonDemo5.java
01 class Person
02 {
03
private String name ;
04
private int age ;
05
private void talk()
06
{
07
System.out.println(""+name+""+age+"");
08
}
09
public void say()
10
{
11
talk();
12
}
13
public void setName(String str)
14
{
15
name = str ;
16
}
17
public void setAge(int a)
18
{

148

19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

if(a>0)
age = a ;
}
public String getName()
{
return name ;
}
public int getAge()
{
return age ;
}
}
public class TestPersonDemo5
{
public static void main(String[] args)
{
// Person p
Person p = new Person() ;
// p
p.setName("") ;
// p -25
p.setAge(30) ;
// Person say()
p.say() ;
}
}

30

1 9~12 say() talk()


2 43 Person say() Person talk()

149


say() talk()

this.talk() ;

this

5.5

java C++
java C++

TestRefDemo1.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16

class Person
{
String name ;
int age ;
}
public class TestRefDemo1
{
public static void main(String[] args)
{
// p1 null
Person p1 = null ;
// p2 null
Person p2 = null ;
// p1
p1 = new Person() ;
// p1

150

17
18
19
20
21
22
23
24
25
26 }

p1.name = "" ;
p1.age = 25 ;
// p1 p2
p2 = p1 ;
// p2
System.out.println(""+p2.name);
System.out.println(""+p2.age);
p1 = null ;
}

25

1 1~5 Person name age


2 1113 Person p1 p2
null
3 15 p1
4 1718 p1
5 20 p1 p2 p1 p2
6 2223 p2.name p2.age p2
7 24 p1 null
8 24 p1 p2
p1

new p2
p2.name p2.age p1
p2 p1 p1
p2 5-7

151

5-7

p2=null p1
5-8

5-8

152

TestRefDemo2.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19

class Change
{
int x = 0 ;
}
public class TestRefDemo2
{
public static void main(String[] args)
{
Change c = new Change() ;
c.x = 20 ;
fun(c) ;
System.out.println("x = "+c.x);
}
public static void fun(Change c1)
{
c1.x = 25 ;
}
}

x = 25

1 1~4 Change x
2 10 Change c
3 11 c x 20
4 12 fun() c
5 15~18 fun Change
6 17 c1 x 25

153

x = 25 fun() x
25
15 fun() Change c1 fun()
fun 5-9

5-9

c x 20 A

fun() c1c1 x c1 c
c1 x c x fun()x
25

5.6

154


TestNoName.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17

class Person
{
private String name = "" ;
private int age = 25 ;
public String talk()
{
return ""+name+""+age+"" ;
}
}
public class TestNoName
{
public static void main(String[] args)
{
System.out.println(new Person().talk());
}
}

25

1 1~9 Person name age

2 15 Person Person talk()

new Person() Person


Java

155

5.7

Java

5-5
class
{
1 1 2 2
{

//
}
}

1
2

TestConstruct.java

TestConstruct.java
01 class Person
02 {
03
public Person()

// Person

156

04
05
06
07
08
09
10
11
12
13
14
15

{
System.out.println("public Person()") ;
}
}
public class TestConstruct
{
public static void main(String[] args)
{
Person p = new Person() ;
}
}

public Person()

1 1~7 Person Person


2 3~6 Person
3 13 Person p Person

javac java

public Person()
{}

157

5.7.1

Java
java

TestConstruct1.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

class Person
{
private String name ;
private int age ;
public Person(String n,int a)
{
name = n ;
age = a ;
System.out.println("public Person(String n,int a)") ;
}
public String talk()
{
return ""+name+""+age+"" ;
}
}
public class TestConstruct1
{
public static void main(String[] args)
{
Person p = new Person("",25) ;
System.out.println(p.talk()) ;
}
}

158


public Person(String n,int a)
25

1 1~15 Person name age


talk()
2 5~10 Person
Person
3 21 Person new Person("
",25)

4 22 Person talk()

TestConstruct2.java
01 class Person
02 {
03
private String name ;
04
private int age ;
05
public Person(String n,int a)
06
{
07
name = n ;
08
age = a ;
09
System.out.println("public Person(String n,int a)") ;
10
}
11
public String talk()
12
{
13
return ""+name+""+age+"" ;
14
}

159

15
16
17
18
19
20
21
22
23
24

}
public class TestConstruct2
{
public static void main(String[] args)
{
Person p = new Person() ;
System.out.println(p.talk()) ;
}
}

TestConstruct2.java:21: Person(java.lang.String,int) in Person cannot be applied to ()


Person p = new Person() ;
^
1 error
21 Person p = new Person()
Person

5~10
java
Person
Person
TestConstruct2.java
01 class Person
02 {
03
private String name ;
04
private int age ;
05
public Person()
06
{}
07
public Person(String n,int a)
08
{
09
name = n ;

160

10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

age = a ;
System.out.println("public Person(String n,int a)") ;
}
public String talk()
{
return ""+name+""+age+"" ;
}
}
public class TestConstruct2
{
public static void main(String[] args)
{
Person p = new Person() ;
System.out.println(p.talk()) ;
}
}
56

5.8

= = equals()
= =
equals()

TestEquals.java
01 public class TestEquals
02 {
03
public static void main(String[] args)
04
{
05
String str1 = new String("java") ;
06
String str2 = new String("java") ;
07
String str3 = str2 ;

161

08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 }

if(str1==str2)
{
System.out.println("str1 == str2");
}
else
{
System.out.println("str1 != str2") ;
}
if(str2==str3)
{
System.out.println("str2 == str3");
}
else
{
System.out.println("str2 != str3") ;
}
}

str1 != str2
str2 == str3

str1 str2str1 str2


5 6
String
==
str1!=str2 7 str2 str3 str3 str2
str2==str3

equals TestEquals1.java TestEquals.java

162

TestEquals1.java
01 public class TestEquals1
02 {
03
public static void main(String[] args)
04
{
05
String str1 = new String("java") ;
06
String str2 = new String("java") ;
07
String str3 = str2 ;
08
if(str1.equals(str2))
09
{
10
System.out.println("str1 equals str2");
11
}
12
else
13
{
14
System.out.println("str1 not equals str2") ;
15
}
16
if(str2.equals(str3))
17
{
18
System.out.println("str2 equals str3");
19
}
20
else
21
{
22
System.out.println("str2 note equals str3") ;
23
}
24
}
25 }

str1 equals str2


str2 equals str3

equals equals()
String equals String
==
equals

163


String
String str1 = new String("java");
String str2 = "java";

01 public class StringDemo


02 {
03
public static void main(String[] args)
04
{
05
String str1 = "java" ;
06
String str2 = new String("java") ;
07
String str3 = "java" ;
08
System.out.println("str1 == str2 ? --- > "+(str1==str2)) ;
09
System.out.println("str1 == str3 ? --- > "+(str1==str3)) ;
10
System.out.println("str3 == str2 ? --- > "+(str3==str2)) ;
11
}
12 }

str1 == str2 ? --- > false


str1 == str3 ? --- > true
str3 == str2 ? --- > false

str1 str3
== str1 str3 str1
str3 5-10

164

5-10 String
java str1
str3 str1 str3
str2 new

String
String String
new String
5-11

165

5-11 String
5-11AString

5-11B String
new String(java) String
String str1 = "java"

5.9

this

java this
5-4 this
this

166


Person.java
01 class Person
02 {
03
private String name ;
04
private int age ;
05
public Person(String name,int age)
06
{
07
name = name ;
08
age = age ;
09
}
10 }
name age
name age
7 name name
name name this

Person-1.java
01 class Person-1
02 {
03
private String name ;
04
private int age ;
05
public Person(String name,int age)
06
{
07
this.name = name ;
08
this.age = age ;
09
}
10 }
Person-1.java Person.java 7
8 this
this this.name this.age

167

name age

TestJavaThis.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22

class Person
{
private String name ;
private int age ;
public Person(String name,int age)
{
this.name = name ;
this.age = age ;
}
public String talk()
{
return ""+name+""+age+"" ;
}
}
public class TestJavaThis
{
public static void main(String[] args)
{
Person p = new Person("",25) ;
System.out.println(p.talk()) ;
}
}

25

1 1~14 Person
2 5~9 Person

168

this

TestCompare.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

class Person
{
String name ;
int age ;
Person(String name,int age)
{
this.name = name ;
this.age = age ;
}
boolean compare(Person p)
{
if(this.name.equals(p.name)&&this.age==p.age)
{
return true ;
}
else
{
return false ;
}
}
}
public class TestCompare
{
public static void main(String[] args)
{
Person p1 = new Person("",30);
Person p2 = new Person("",30);
System.out.println(p1.compare(p2)?",!":",!");
}
}

169


,!

1 1~21 Person
2 10~20 Person compare Person

3 12
4 29 p1 compare() p2 compare
12 this.name p1.namethis.age p1.age
p2 compare() p

this

5.9.1

this

this

this() ;

TestJavaThis1.java
01 class Person
02 {
03
String name ;
04
int age ;
05
public Person()
06
{
07
System.out.println("1. public Person()");
08
}

170

09
10
11
12
13
14
15
16
17
18
19
20
22
23
24
25

public Person(String name,int age)


{
//
this() ;
this.name = name ;
this.age = age ;
System.out.println("2. public Person(String name,int age)");
}
}
public class TestJavaThis1
{
public static void main(String[] args)
{
new Person("",25) ;
}
}

1. public Person()
2. public Person(String name,int age)

1 1~17 Person

2 12 this()
3 23 Person

TestJavaThis1.java 23 Person
12 this()
Person

171


this()

this

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

class Person
{
String name ;
int age ;
public Person()
{
System.out.println("1. public Person()");
}
public Person(String name,int age)
{
this.name = name ;
this.age = age ;
// this
this() ;
System.out.println("2. public Person(String name,int age)");
}
public String talk()
{
// this
this() ;
System.out.println(""+name+""+age+"");
}
}
public class TestJavaThis1
{
public static void main(String[] args)
{
new Person("",25) ;

172

29
}

this

TestJavaThis1.java:14: call to this must be first statement in constructor


this() ;
1 error
this()

5.10
5.10.1

static

static

TestStaticDemo1.java
01 class Person
02 {
03
String name ;
04
String city ;
05
int age ;
06
public Person(String name, String city, int age)
07
{
08
this.name = name ;
09
this.city = city ;
10
this.age = age ;
11
}
12
public String talk()
13
{
14
return ""+this.name+""+this.age+""+this.city;

173

15
16
17
18
19
20
21
22
23
24
25
26
27
28

}
}
public class TestStaticDemo1
{
public static void main(String[] args)
{
Person p1 = new Person("",25,"") ;
Person p2 = new Person("",30,"") ;
Person p3 = new Person("",35,"") ;
System.out.println(p1.talk()) ;
System.out.println(p2.talk()) ;
System.out.println(p3.talk()) ;
}
}

25
30
35

1 1~16 Person nameagecity


2 6~11 Person
3 12~15 talk()
4 21~23 Person
5 24~26 talk()

Person city
5-11

174

5-12
50 Person
city 50 city
java static
TestStaticDemo1.java TestStaticDemo2.java

TestStaticDemo2.java
01 class Person
02 {
03
String name ;
04
static String city = "";
05
int age ;
06
public Person(String name,int age)
07
{
08
this.name = name ;
09
this.age = age ;
10
}
11
public String talk()
12
{
13
return ""+this.name+""+this.age+""+city;

175

14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

}
}
public class TestStaticDemo2
{
public static void main(String[] args)
{
Person p1 = new Person("",25) ;
Person p2 = new Person("",30) ;
Person p3 = new Person("",35) ;
System.out.println(""+p1.talk()) ;
System.out.println(""+p2.talk()) ;
System.out.println(""+p3.talk()) ;
System.out.println(" ************* **************");
//
p1.city = "" ;
System.out.println(""+p1.talk()) ;
System.out.println(""+p2.talk()) ;
System.out.println(""+p3.talk()) ;
}
}

:25
:30
:35
************* **************
:25
:30
:35

1 1~15 Person nameagecity


city static

176

2 6~10 Person nameage

3 11~14 talk()
4 20~22 Person
5 23~25 talk()
6 28 p1 city

28 city
city city
static
5-13

177

5-13 static
city
city
static
city
Person.city = ;

static

178


static
static

class Person
{
static int count = 0 ;
public Person()
{

// static

count++ ;
//
System.out.println(""+count+"");
}
}
public class TestStaticDemo3
{
public static void main(String[] args)
{
new Person() ;
new Person() ;
}
}

5.10.2

static

179

TestStaticDemo4.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

class Person
{
String name ;
private static String city = "";
int age ;
public Person(String name,int age)
{
this.name = name ;
this.age = age ;
}
public String talk()
{
return ""+this.name+""+this.age+""+city;
}
public static void setCity(String c)
{
city = c ;
}
}
public class TestStaticDemo4
{
public static void main(String[] args)
{
Person p1 = new Person("",25) ;
Person p2 = new Person("",30) ;
Person p3 = new Person("",35) ;
System.out.println(""+p1.talk()) ;
System.out.println(""+p2.talk()) ;
System.out.println(""+p3.talk()) ;
System.out.println("
****************************");
//
Person.setCity("") ;
System.out.println(""+p1.talk()) ;
System.out.println(""+p2.talk()) ;
System.out.println(""+p3.talk()) ;
}

180

37 }

25
30
35
****************************
25
30
35

1 1~19 Person static city

2 15~18 static
city
3 32 Person setCity() city

static static
static static
static static

public class PersonStatic


{
String name = "" ;
static String city = "";
int age ;
public PersonStatic(String name,int age)
{
this.name = name ;
this.age = age ;

181

}
public static void print()
{
System.out.println(name);
}
public String talk()
{
return ""+this.name+""+this.age+""+city;
}
}

PersonStatic.java:13: non-static variable name cannot be referenced


from a static context
System.out.println(name);
^
1 error
print() static name
static print static name

5.10.3

main()

Java
main() main()

Java main() public


Java main() static
String Java

182

java
java 1 2 3

TestMain.java

TestMain.java
01 public class TestMain
02 {
03
/*
04
public
05
static
06
void
07
main
08
String args[]
09
*/
10
public static void main(String[] args)
11
{
12
//
13
int j = args.length ;
14
if(j!=2)
15
{
16
System.out.println("") ;
17
//
18
System.exit(1) ;
19
}
20
for (int i=0;i<args.length ;i++ )
21
{
22
System.out.println(args[i]) ;
23
}
24
}
25 }

java TestMain first second

183


first
second

1 14
2 args[] for

5.10.4

TestStaticDemo5.java
01 class Person
02 {
03
public Person()
04
{
05
System.out.println("1.public Person()");
06
}
07
//
08
static
09
{
10
System.out.println("2.Person ");
11
}
12 }
13 public class TestStaticDemo5 {
14
//
15
static
16
{
17
System.out.println("3.TestStaticDemo5 ");
18
}
19
public static void main(String[] args) {

184

20
21
22
23
24
25 }

System.out.println("4.");
//
new Person() ;
new Person() ;
}

3.TestStaticDemo5
4.
2.Person
1.public Person()
1.public Person()

1 1~12 Person
2 8~11 Person
3 15~18 TestStaticDemo5
4 2223 Person

TestStaticDemo5
TestStaticDemo5
2223 Person

5.11

public private public private


public

185

private

TestSingleDemo1.java
01 public class TestSingleDemo1
02 {
03
private TestSingleDemo1()
04
{
05
System.out.println("private TestSingleDemo1 .") ;
06
}
07
public static void main(String[] args)
08
{
09
new TestSingleDemo1() ;
10
}
11 }

private TestSingleDemo1 .

3 private
main
TestSingleDemo1

main()

TestSingleDemo2
01 class Person
02 {
03
String name ;
04 // Person p final

186

05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

private static final Person p = new Person() ;


private Person()
{
name = "" ;
}
public static Person getP()
{
return p ;
}
}
public class TestSingleDemo2
{
public static void main(String[] args)
{
// Person
Person p = null ;
p = Person.getP() ;
System.out.println(p.name) ;
}
}

1 6~9 Person

2 5 Person Person
static
Person final
Person p
final

187

3 21 Person p
4 22 Person getP() Person

Person

5.12

1 new
2 new
Person
Person p[] ;

// Person

p = new Person[3] ;

// new

Person
p[0] = new Person () ;
p[1] = new Person () ;

new

p[2] = new Person () ;

p[0]p[1]p[2] Person

Person p[] = new Person[3];

//

for

188

for(int i=0;i<p.length;i++)
{
p[i] = new Person() ;
}

Person p[] = {new Person(),new Person(),new Person()} ;

TestObjectArray.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

class Person
{
String name ;
int age ;
public Person()
{
}
public Person(String name,int age)
{
this.name = name ;
this.age = age ;
}
public String talk()
{
return ""+this.name+""+this.age+"" ;
}
}
public class TestObjectArray
{
public static void main(String[] args)
{
Person p[] = {
new Person("",25),new Person("",30),new Person("",35)
};
for(int i=0;i<p.length;i++)
{
System.out.println(p[i].talk()) ;

189

28
29
30 }

}
}

25
30
35

1 22~24 Person
2 25~28 for talk()

5.13

Outer Inner Inner


Outer
public private public private

5-6

class
{
//
class
{
//
}
}

190

InnerClassDemo.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

class Outer
{
int score = 95;
void inst()
{
Inner in = new Inner();
in.display();
}
class Inner
{
void display()
{
System.out.println(": score = " + score);
}
}
}
public class InnerClassDemo
{
public static void main(String[] args)
{
Outer outer = new Outer();
outer.inst();
}
}

: score = 95

1 9~15 Outer Inner display()


score
2 4~8 inst() in

Inner Outer score

191

score
Outer Outer score
score

InnerClassDemo1.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

class Outer
{
int score = 95;
void inst()
{
Inner in = new Inner();
in.display();
}
public class Inner
{
void display()
{
// name
String name = "" ;
System.out.println(": score = " + score);
}
}
public void print()
{
// name
System.out.println(""+name) ;
}
}
public class InnerClassDemo1
{
public static void main(String[] args)

192

27
28
29
30
31 }

{
Outer outer = new Outer();
outer.inst();
}

InnerClassDemo1.java:21: cannot resolve symbol


symbol : variable name
location: class Outer
System.out.println(""+name) ;
^
1 error

static static static


static static
static

InnerClassDemo2.java
01 class Outer
02 {
03
int score = 95;
04
void inst()
05
{
06
Inner in = new Inner();
07
in.display();
08
}
09
// static
10
static class Inner
11
{
12
void display()

193

13
14
15
16
17
18
19
20
21
22
23
24
25

{
System.out.println(": score = " + score);
}
}
}
public class InnerClassDemo2
{
public static void main(String[] args)
{
Outer outer = new Outer();
outer.inst();
}
}

InnerClassDemo2.java:14: non-static variable score cannot be referenced from a static


context
System.out.println(": score = " + score);
^
1 error
Inner static
static score

5.13.1

public

InnerClassDemo3.java
01 class Outer
02 {
03
int score = 95;
04
void inst()

194

05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

{
Inner in = new Inner();
in.display();
}
public class Inner
{
void display()
{
System.out.println(": score = " + score);
}
}
}
public class InnerClassDemo3
{
public static void main(String[] args)
{
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
inner.display() ;
}
}

: score = 95

1 9~15 public
2 22

5.13.2

195

InnerClassDemo4.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

class Outer
{
int score = 95;
void inst()
{
class Inner
{
void display()
{
System.out.println(": score = " + score);
}
}
Inner in = new Inner();
in.display();
}
}
public class InnerClassDemo4
{
public static void main(String[] args)
{
Outer outer = new Outer();
outer.inst() ;
}
}

: score = 95

1 4~15 Outer inst() Inner


Inner
2 21 Outer 22 Outer inst()

196

final final

InnerClassDemo5
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

class Outer
{
int score = 95;
void inst(final int s)
{
int temp = 20 ;
class Inner
{
void display()
{
System.out.println(": score = " + (score+s+temp));
}
}
Inner in = new Inner();
in.display();
}
}
public class InnerClassDemo5
{
public static void main(String[] args)
{
Outer outer = new Outer();
outer.inst(5) ;
}
}

InnerClassDemo5.java:11: local variable temp is accessed from within inner class;


needs to be declared final
System.out.println(" : score = " +
(score+s+temp));

197

^
1 error
final s
temp 6 final
final int temp = 20 ;

InnerClassDemo5.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

class Outer
{
int score = 95;
void inst(final int s)
{
final int temp = 20 ;
class Inner
{
void display()
{
System.out.println(": score = " + (score+s+temp));
}
}
Inner in = new Inner();
in.display();
}
}
public class InnerClassDemo5
{
public static void main(String[] args)
{
Outer outer = new Outer();
outer.inst(5) ;
}
}

198


: score = 120

1 4~16 inst() final


2 6 final temp final
Inner
3 22 Outer outer
4 outer inst()

5.14

Java

Java // /* */
/***/
javadoc
HTML

5.14.1

javadoc

javadoc

199

Tag
@author

@deprecated

{@docRoot}

(Java21.3)

@exception

{@link}

@param

@return

@see

@serial

@serialData

writeObject()writeExternal()

@serialField

ObjectStreamField

@since

@throws

@exception

@version

(@)
HTML
javadocHTML

@see, @since,
@serial,@serialField, @deprecated@see, @author,
@since,@deprecated, @version @see, @return,
@param, @since,@deprecated, @throws, @serialData, @exception
{@link} {@docRoot}

@ author
@author
@author description

description @author
javadoc-author @author HTML

200

@deprecated
@deprecated @see

@deprecated description

description @deprecated
.classJava

@deprecated

{@docRoot}
{@docRoot}

@exception
@exception
@exception exception-name explanation

exception-nameexplanation
@exception

{@link}
{@link}
{@link name text}

name text

@param
@param
@param parameter-name explanation

parameter-nameexplanation

201

@param

@return
@return
@return explanation

explanation @return

@see
@see
@see anchor
@see pkg.class#member text

anchor URL
pkg.class#member text
pkg.class#membe

@serial
@serial
@serial description

description

@serialData
@serialData writeObject( )writeExternal( )

@serialData description

description

@serialField

202

@serialField ObjectStreamField
@serialField name type description

nametypedescription

@since
@since
@since release

release@since

@throws
@throws @exception

@version
@version
@version info

info 2.2@version
javadoc-version @version
HTML

5.14.2

/**
@@
(*)@see

203

/**
* This class draws a bar chart.
* @author Herbert Schildt
* @version 3.2
*/

5.14.3

javadoc

javadocJavaHTML
HTMLjavadoc

JavadocHTMLjavadoc
Java
JavaDoc

PersonJavaDoc.java
/**
*Title: PersonJavaDoc<br>
*Description: PersonJavaDoc Java <br>
*Copyright:(c) 2004 www.sun.com.cn<br>
*Company : sun java </br>
*@author lixinghua
*@version 1.00
*/
public class PersonJavaDoc
{
private String name = "Careers";
private String sex = "male";
private int age = 30;
/**
* PersonJavaDoc

204

*/
public PersonJavaDoc()
{ }
/**
* PersonJavaDoc
*@param name PersonJavaDoc
*@param sex PersonJavaDoc
*@param age PersonJavaDoc
*/
public PersonJavaDoc(String name,String sex,int age)
{
this.name = name ;
this.sex = sex;
this.age = age;
}
/**
* name name this.name
*@param name PersonJavaDoc
*/
public void setName(String name)
{
this.name = name;
}
/**
* name
*@ name
*/
public String getName()
{
return name;
}
/**
* age
*@ age
*/
public int getAge()
{

205

return age;
}
/**
* sex sex this.sex
*@param sex PersonJavaDoc
*/
public void setSex(String sex)
{
this.sex = sex ;
}
/**
* sex
*@ sex
*/
public String getSex()
{
return sex;
}
/**
* age
*@param age PersonJavaDoc
*/
public void setAge(int age)
{
if(age<0)
this.age = 0;
else
this.age = age;
}
public void shout()
{
System.out.println(" "+name+" "+sex+" "+age+"
");
}
}
javadoc

206

javadoc -d PersonJavaDoc -version -author PersonJavaDoc.java


-d PersonJavaDoc
-version javadoc
-author javadoc

PersonJavaDoc 5-14

5-14 PersonJavaDoc
index.html

207

5-15 index.html

208

2 Java field method


3 instance
4 1
2
new

5 field.
.method
6
void
7 private member

8 public member
9 encapsulation

10
11
12 this()
13 public private public
private

14Java

15 intdouble

161
new
2 new

209


17 Outer Inner Inner inner class

Outer outer class

210

6.1

Person name age Student nameage


school 6-1 Person name age
Student
Person Student

6-1

Student Person

Student Person 6-2

211

6-2

Person Student

Java
6-1
class
{
}
class extends
{
}

//

// extends

TestPersonStudentDemo.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16

class Person
{
String name ;
int age ;
}
class Student extends Person
{
String school ;
}
public class TestPersonStudentDemo
{
public static void main(String[] args)
{
Student s = new Student() ;
// Person name

212

17
18
19
20
21
22
23
24 }

s.name = "" ;
// Person age
s.age = 25 ;
// Student school
s.school = "" ;
System.out.println(""+s.name+""+s.age+""+s.school) ;
}

25

1 1~5 Person name age


2 6~9 Student Person
3 15 Student
4 171921 Student nameageschool

Student name age


name age Student Person
Student Person Student
6-3

6-3

Person Student

213


java
java

6-4

class A
{}
class B
{}
class C extends A,B
{}
C A B C
JAVA

6-5

class A
{}

214

class B extends A
{}
class C extends B
{}
B A C B
B A C A

6.1.1

TestPersonStudentDemo1.java
01 class Person
02 {
03
String name ;
04
int age ;
05
//
06
public Person()
07
{
08
System.out.println("1.public Person(){}") ;
09
}
10 }
11 class Student extends Person
12 {
13
String school ;
14
//
15
public Student()
16
{
17
System.out.println("2.public Student(){}");
18
}
19 }
20
21 public class TestPersonStudentDemo1
22 {

215

23
24
25
26
27 }

public static void main(String[] args)


{
Student s = new Student() ;
}

1.public Person(){}
2.public Student(){}

1 1~10 Person
2 11~19 Student Person

3 25 Student s

25

super()

class Student extends Person


{
String school ;
//
public Student()
{
super() ;

System.out.println("2.public Student(){}");

}
}

216

TestPersonStudentDemo2.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

class Person
{
String name ;
int age ;
//
public Person(String name,int age)
{
this.name = name ;
this.age = age ;
}
}
class Student extends Person
{
String school ;
//
public Student()
{
}
}
public class TestPersonStudentDemo2
{
public static void main(String[] args)
{
Student s = new Student() ;
}
}

TestPersonStudentDemo2.java:17:

217

Person(java.lang.String,int)

in

Person cannot
be applied to ()
{}
^
1 error
Person
Person

25
Person
TestPersonStudentDemo2.java
TestPersonStudentDemo3.java
TestPersonStudentDemo3.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18

class Person
{
String name ;
int age ;
//
public Person(){}
//
public Person(String name,int age)
{
this.name = name ;
this.age = age ;
}
}
class Student extends Person
{
String school ;
//
public Student()

218

19
{}
20 }
21
22 public class TestPersonStudentDemo3
23 {
24
public static void main(String[] args)
25
{
26
Student s = new Student() ;
27
}
28 }
6 Person

6.1.2

super

super super
TestPersonStudentDemo1 super
super
TestPersonStudentDemo3.java
TestPersonStudentDemo4.java

TestPersonStudentDemo4.java
01 class Person
02 {
03
String name ;
04
int age ;
05
//
06
public Person(String name,int age)
07
{
08
this.name = name ;
09
this.age = age ;
10
}
11 }
12 class Student extends Person

219

13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

{
String school ;
//
public Student()
{
// super
super("",25);
}
}
public class TestPersonStudentDemo4
{
public static void main(String[] args)
{
Student s = new Student() ;
// Student school
s.school = "" ;
System.out.println(""+s.name+""+s.age+""+s.school) ;
}
}

25

1 1~11 Person name age

2 12~21 Student Person 16~20


super("",25)

3 27 Student s29 Student s

school

220

TestPersonStudentDemo3.java

super

super
6-2

6-2 super
super. ;
super.() ;
TestPersonStudentDemo5.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18

class Person
{
String name ;
int age ;
//
public Person()
{
}
public String talk()
{
return ""+this.name+""+this.age+"" ;
}
}
class Student extends Person
{
String school ;
//
public Student(String name,int age,String school)

221

19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

{
// super
super.name = name ;
super.age = age ;
// talk()
System.out.print(super.talk());
// school
this.school = school ;
}
}
public class TestPersonStudentDemo5
{
public static void main(String[] args)
{
Student s = new Student("",25,"") ;
System.out.println(""+s.school) ;
}
}

25

1 1~13 Person name age


String talk()
2 14~30 Student Person
3 2122 super. name age

4 25 talk()

Student super
212225 this

222

super

6.1.3

private

TestPersonStudentDemo6.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21

class Person
{
//
private String name ;
private int age ;
}
class Student extends Person
{
//
public void setVar()
{
name = "" ;
age = 25 ;
}
}
class TestPersonStudentDemo6
{
public static void main(String[] args)
{
new Student().setVar() ;

22
23 }

223


TestPersonStudentDemo6.java:12: name has private access in Person
name = "" ;
^
TestPersonStudentDemo6.java:13: age has private access in Person
age = 25 ;
^
2 errors

name age

private

private

TestPersonStudentDemo6.java
TestPersonStudentDemo7.java
class Person
{
//
private String name ;
private int age ;
// setXxx()
public void setName(String name)
{
this.name = name ;
}
public void setAge(int age)
{
this.age = age ;
}
public String talk()

224

{
return ""+this.name+""+this.age+"" ;
}
}
class Student extends Person
{
//
public void setVar()
{
super.setName("") ;
super.setAge(25) ;
}
}
class TestPersonStudentDemo7
{
public static void main(String[] args)
{
Student s = new Student() ;
s.setVar() ;
System.out.println(s.talk()) ;
}
}

25

name age

225

6.1.4

Java

6-3
class Super
{
1 1
{}
}
class Sub extends Super
{
1 1
{}
}

TestOverDemo1.java
01
02
03
04
05
06
07
08
09
10
11
12

class Person
{
String name ;
int age ;
public String talk()
{
return ""+this.name+""+this.age+"";
}
}
class Student extends Person
{

226

13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

String school ;
public Student(String name,int age,String school)
{
//
this.name = name ;
this.age = age ;
this.school = school ;
}
// Person talk()
public String talk()
{
return ""+this.school+"" ;
}
}
class TestOverDemo1
{
public static void main(String[] args)
{
Student s = new Student("",25,"") ;
// talk()
System.out.println(s.talk()) ;
}
}

1 1~9 Person name age


talk()
2 11~26 Student Person name
age talk() Student
talk() Person talk()
3 32

227

4 34 talk() talk()

talk()
talk() talk()
talk() public

class Person
{
public String talk ()
{}
}
class Student extends Person
{
//
String talk ()
{}
}
talk() default
talk public public default

TestOverDemo1.java 34 talk()

TestOverDemo1.java

228

TestOverDemo2.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

class Person
{
String name ;
int age ;
public String talk()
{
return ""+this.name+""+this.age+"";
}
}
class Student extends Person
{
String school ;
public Student(String name,int age,String school)
{
//
this.name = name ;
this.age = age ;
this.school = school ;
}
// Person talk()
public String talk()
{
return super.talk()+""+this.school+"" ;
}
}
class TestOverDemo2
{
public static void main(String[] args)
{
Student s = new Student("",25,"") ;
// talk()
System.out.println(s.talk()) ;
}
}

229


25

1 1~9 Person name age talk()

2 11~26 Student Person name age


talk() Student talk()
Person talk() 24 super.talk()
talk()
3 32
4 34 talk() talk()

super.()

this super 6-1


this super
6-1

this super

this

2
3

super

1
2

super this
super this

230

6.2

Java

abstract
new

6-4
abstract class //
{


{

}
abstract

//
}

231

abstract

TestAbstractDemo1.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

abstract class Person


{
String name ;
int age ;
String occupation ;
// talk()
public abstract String talk() ;
}
// Student Person
class Student extends Person
{
public Student(String name,int age,String occupation)
{
this.name = name ;
this.age = age ;
this.occupation = occupation ;
}
// talk()
public String talk()
{
return ">"+this.name+""+this.age+"
"+this.occupation+"" ;
}
}
// Worker Person
class Worker extends Person
{
public Worker(String name,int age,String occupation)

232

29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

{
this.name = name ;
this.age = age ;
this.occupation = occupation ;
}
// talk()
public String talk()
{
return ">"+this.name+""+this.age+"
"+this.occupation+"" ;
}
}
class TestAbstractDemo1
{
public static void main(String[] args)
{
Student s = new Student("",20,"") ;
Worker w = new Worker("",30,"") ;
System.out.println(s.talk()) ;
System.out.println(w.talk()) ;
}
}

>20
>30

1 1~8 Person Person


talk()
2 9~24 Student Person
Person talk()
3 25~40 Worker Person
Person talk()

233

4 4546 Student Worker

5 4748 talk()

StudentWorker talk()
6-6

6-6

abstract class Person


{
String name ;
int age ;
String occupation ;
public Person(String name,int age,String occupation)
{
this.name = name ;

234

this.age = age ;
this.occupation = occupation ;
}
public abstract String talk() ;
}
class Student extends Person
{
public Student(String name,int age,String occupation)
{
//
super(name,age,occupation);
}
public String talk() {
return ">"+this.name+""+this.age+"
"+this.occupation+"" ;
}
}
class TestAbstractDemo2
{
public static void main(String[] args)
{
Student s = new Student("",20,"") ;
System.out.println(s.talk()) ;
}
}

>20

235

6.3

Object

Java Object
extends Object
Object Java Java
Object Oject

public class Person


{

// Object

public class Person extends Object


{

}
JDK Object toString()

toString()
toString()

TestToStringDemo1.java
01
02
03
04
05
06
07

class Person extends Object


{
String name = "";
int age = 25 ;
}
class TestToStringDemo1
{

236

08
09
10
11
12
13 }

public static void main(String[] args)


{
Person p = new Person() ;
System.out.println(p);
}

Person@1ea2dfe

1 1~5 Person Object


2 10 Person p11

Object toString()

TestToStringDemo2.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15

class Person extends Object


{
String name = "";
int age = 25 ;
// Object toString()
public String toString()
{
return ""+this.name+""+this.age+"";
}
}
class TestToStringDemo2
{
public static void main(String[] args)
{
Person p = new Person() ;

237

16
17
18 }

System.out.println(p);
}

25

TestToStringDemo1.java TestToStringDemo2.java Person


toString() p toString()
toString() 16
System.out.println(p.toString());

6.4

final

Java final
1 final
2 final
3 final

TestFinalDemo1.java
01 class TestFinalDemo1
02 {
03
public static void main(String[] args)
04
{
05
final int i = 10 ;
06
// final i
07
i++ ;
08
}
09 }

238


TestFinalDemo1.java:6: cannot assign a value to final variable i
i++ ;
^
1 error
TestFinalDemo2.java
01
02
03
04
05
06

final class Person


{
}
class Student extends Person
{
}

TestFinalDemo2.java:4: cannot inherit from final Person


class Student extends Person
^
1 error
TestFinalDemo3.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15

class Person
{
// final
final public String talk()
{
return "Persontalk()" ;
}
}
class Student extends Person
{
public String talk()
{
return "Studenttalk()" ;
}

239

16 }

TestFinalDemo3.java:12: talk() in Student cannot override talk() in Person;


overridden method is final
public String talk()
^
1 error

6.5

interface

interface Java

1
2 abstract

6-5
interface
//
{
final =

//

abstract
//
}

6-5 abstract

240


final
1
2

java java

implementation

6-6

6-6
class implements A, B
{

//

TestAbstractDemo1.java

TestInterfaceDemo1.java
01
02
03
04
05
06
07
08
09
10
11
12

interface Person
{
String name = "";
int age = 25 ;
String occupation = "" ;
// talk()
public abstract String talk() ;
}
// Student Person
class Student implements Person
{
// talk()

241

13
14
15
16
17
18
19
20
21
22
23
24
25
26

public String talk()


{
return ">"+this.name+""+this.age+"
"+this.occupation+"" ;
}
}
class TestInterfaceDemo1
{
public static void main(String[] args)
{
Student s = new Student() ;
System.out.println(s.talk()) ;
}
}

>25

1 1~8
Person nameage
occupation

2 10~18 Student Person Person talk()

3 23 Student s 24 talk()

java

242

extends
6-7
6-7
interface extends 1 2
{

}
TestInterfaceDemo2.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

interface A
{
int i = 10 ;
public void sayI() ;
}
interface E
{
int x = 40 ;
public void sayE() ;
}
// B AE
interface B extends A,E
{
int j = 20 ;
public void sayJ() ;
}
// C B ABE
class C implements B
{
public void sayI()
{
System.out.println("i = "+i);
}
public void sayJ()

243

26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

{
System.out.println("j = "+j) ;
}
public void sayE()
{
System.out.println("e = "+x);
}
}
class TestInterfaceDemo2
{
public static void main(String[] args)
{
C c = new C() ;
c.sayI() ;
c.sayJ() ;
}
}

i = 10
j = 20

1 1~5 A i sayI()
2 6~10 E x sayE()
3 12~16 B AE j
sayJ()
4 19~33 C B ABE

244

6.6

TestJavaDemo1.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23

class Person
{
public void fun1()
{
System.out.println("1.Person{fun1()}") ;
}
public void fun2()
{
System.out.println("2.Person{fun2()}") ;
}
}
// Student Person Person fun1()fun2()
class Student extends Person
{
// Person fun1()
public void fun1()
{
System.out.println("3.Student{fun1()}") ;
}
public void fun3()
{
System.out.println("4.Studen{fun3()}") ;

245

24
25
26
27
28
29
30
31
32
33
34
35
36
37

}
}
class TestJavaDemo1
{
public static void main(String[] args)
{
//
Person p = new Student() ;
// fun1() fun1()
p.fun1() ;
p.fun2() ;
}
}

3.Student{fun1()}
2.Person{fun2()}

1 1~11 Person fun1()fun2()


2 14~25 Student Person fun1()
3 32 Person
4 34 fun1()

p fun1()
fun1() fun1()

1
TestJavaDemo1.java

246

TestJavaDemo2.java
01 class Person
02 {

247

03
public void fun1()
04
{
05
System.out.println("1.Person{fun1()}") ;
06
}
07
public void fun2()
08
{
09
System.out.println("2.Person{fun2()}") ;
10
}
11 }
12
13// Student Person Person fun1()fun2()
14 class Student extends Person
15 {
16
// Person fun1()
17
public void fun1()
18
{
19
System.out.println("3.Student{fun1()}") ;
20
}
21
public void fun3()
22
{
23
System.out.println("4.Studen{fun3()}") ;
24
}
25 }
26
27 class TestJavaDemo2
28 {
29
public static void main(String[] args)
30
{
31
//
32
Person p = new Person() ;
33
// p
34
Student s = (Student)p ;
35
p.fun1() ;
36
p.fun2() ;
37
}
38 }

248


Exception in thread "main" java.lang.ClassCastException
at TestJavaDemo2.main(TestJavaDemo2.java:34)

32 Person p Person
34 Person p

32
Person p = new Student() ;

6.6.1

instanceof

instanceof
instanceof
instanceof ()
(true)(false)
TestJavaDemo3.java

249

TestJavaDemo3.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

class Person
{
public void fun1()
{
System.out.println("1.Person{fun1()}") ;
}
public void fun2()
{
System.out.println("2.Person{fun2()}") ;
}
}
// Student Person Person fun1()fun2()
class Student extends Person
{
// Person fun1()
public void fun1()
{
System.out.println("3.Student{fun1()}") ;
}
public void fun3()
{
System.out.println("4.Studen{fun3()}") ;
}
}
class TestJavaDemo3
{
public static void main(String[] args)
{
//
Person p = new Student() ;
// p Student
if(p instanceof Student)
{
// Person p Student
Student s = (Student)p ;

250

37
38
39
40
41
42
43
44 }

s.fun1() ;
}
else
{
p.fun2() ;
}
}

3.Student{fun1()}

1 31 p
2 33 instanceof p Student
p Student 36 p
Student fun1()
fun1()

6.6.2

Object equals

Object toString()
JDK Object equals

equals()

TestOverEquals.java
01 class Person
02 {
03
private String name ;
04
private int age ;

251

05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20

public Person(String name,int age)


{
this.name = name ;
this.age = age ;
}
}
class TestOverEquals1
{
public static void main(String[] args)
{
Person p1 = new Person("",25);
Person p2 = new Person("",25);
// p1 p2
System.out.println(p1.equals(p2)?"":"");
}
}

1 1~10 Person
2 1516 Person p1p2
3 18

p1 p2
equals Object equals
equals

TestOverEquals2.java
01 class Person
02 {
03
private String name ;

252

04
private int age ;
05
public Person(String name,int age)
06
{
07
this.name = name ;
08
this.age = age ;
09
}
10
// Object equals
11
public boolean equals(Object o)
12
{
13
boolean temp = true ;
14
// p1 equals
15
Person p1 = this ;
16
// Object Person
17
if(o instanceof Person)
18
{
19
// Person
20
Person p2 = (Person)o ;
21
// String equals
22
if(!(p1.name.equals(p2.name)&&p1.age==p2.age))
23
{
24
temp = false ;
25
}
26
}
27
else
28
{
29
// Person false
30
temp = false ;
31
}
32
return temp ;
33
}
34 }
35 class TestOverEquals2
36 {
37
public static void main(String[] args)
38
{
39
Person t_p1 = new Person("",25);
40
Person t_p2 = new Person("",25);

253

41 // p1 p2
42
System.out.println(t_p1.equals(t_p2)?"":"");
43
}
44 }

1 1~34 Person Object equals


2 15 Person p1 this this
42 t_p1
3 17 o Person
false
4 22 false
5 42 t_p1 equals t_p2 equals

6.6.3

TestInterfaceObject
01
02
03
04
05
06

interface Person
{
public void fun1() ;
}
class Student implements Person
{

254

07
public void fun1()
08
{
09
System.out.println("Student fun1()");
10
}
11 }
12 class TestInterfaceObject
13 {
14
public static void main(String[] args)
15
{
16
Person p = new Student() ;
17
p.fun1() ;
18
}
19 }

Student fun1()

1 1~4 Person fun1()


2 5~11 Student Person fun1()
3 16 Person p Student

4 17 fun1() fun1()

Person

USB MP3
USB

255

TestInterface.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

interface Usb
{
public void start() ;
public void stop() ;
}
class MoveDisk implements Usb
{
public void start()
{
System.out.println("MoveDisk start...") ;
}
public void stop()
{
System.out.println("MoveDisk stop...") ;
}
}
class Mp3 implements Usb
{
public void start()
{
System.out.println("Mp3 start...") ;
}
public void stop()
{
System.out.println("Mp3 stop...") ;
}
}
class Computer
{
public void work(Usb u)
{
u.start() ;
u.stop() ;
}
}

256

37
38 class TestInterface
39 {
40
public static void main(String[] args)
41
{
42
new Computer().work(new MoveDisk()) ;
43
new Computer().work(new Mp3()) ;
44
}
45 }

MoveDisk start...
MoveDisk stop...
Mp3 start...
Mp3 stop...

1 1~5 Usb start()stop()


2 6~16 MoveDisk Usb

3 17~27 Mp3 Usb

4 29~36 Computer work() Usb


startstop
5 4243 Computer work()

257

6.7

TestNonameInner1.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

interface A
{
public void fun1() ;
}
class B
{
int i = 10 ;
class C implements A
{
public void fun1()
{
System.out.println(i) ;
}
}
public void get(A a)
{
a.fun1() ;
}
public void test()
{
this.get(new C()) ;
}
}
class TestNonameInner1
{
public static void main(String[] args)

258

27
28
29
30
31 }

{
B b = new B() ;
b.test() ;
}

10

1 1~4 A fun1()
2 5~23 B C i
3 8~14 B C A fun1
4 15~18 get() A fun1()

5 19~22 test get()


6 28 B b 29 test()

TestNonameInner2.java
01
02
03
04
05
06
07
08
09

interface A
{
public void fun1() ;
}
class B
{
int i = 10 ;
public void get(A a)
{

259

10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

a.fun1() ;
}
public void test()
{
this.get(new A()
{
public void fun1()
{
System.out.println(i) ;
}
}
);
}
}
class TestNonameInner2
{
public static void main(String[] args)
{
B b = new B() ;
b.test() ;
}
}

10

A
14~21 A fun1()
get
14~21
get(new A()) ;
A
A fun1
get(new A()
{

260

}
);
get(new A()
{
public void fun1()
{
System.out.println(i) ;
}
}
);

261


1 extends
2 Java

3
super()
4 this() super()

5 this()
local
6 this() super()
1

2
this() super()
7 overloading
Java
8
overriding

9 final

10final
constant
11 Object
12 Object equals() method
13Java

14 abstract

15

262

1
2

16
17 method

1
2
abstract
18implementation
19Java
20

21Java

22 instanceof
23anonymous inner class

263

Java

7.1

1 ArithmeticException
2 NullPointerException
3 FileNotFoundException

Java Java
Java Java

7.1.1

if switch

if

Java

264

Java
Java

7.1.2

Java Java
TestException7_1

TestException7_1.java
01 public class TestException7_1
02 {
03
public static void main(String args[])
04
{
05
int arr[]=new int[5];
// 5
06
arr[10]=7;
//
07
System.out.println("end of main() method !!");
08
}
09 }
6

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10


at TestException7_1.main(TestException7_1.java:6)
Java
ArrayIndexOutOfBoundsException
Java

265

7.1.3

TestException7_1 Java
6 7

trycatch finally
7-1
try
{

try

}
catch( )
{

}
finally
{

}

catch

finally

7_1

1 try
2 catch() catch
catch
3 try catch()
finally

266

finally try-catch-finally
try
catch()
finally finally catch()
try-cath
7-1

7-1

7-1
TestException7_1
ArrayIndexOutOfBoundsException

try catch

TestException7_2.java
01 public class TestException7_2
02 {
03
public static void main(String args[])
04
{
05
try
//
06
{

267

07
08
09
10
11
12
13
14
15
16
17
18
19
20 }

int arr[]=new int[5];


arr[10]=7;
//
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("");
}
finally
//
{
System.out.println("");
}
System.out.println("main()");
}

main()

1 7 arr 5
2 8 10
catch finally

5~9 try
ArrayIndexOutOfBoundsException 10~13
8 ArrayIndexOutOfBoundsException 12

268

TestException7_2 10 catch
ArrayIndexOutOfBoundsException e
e

TestException7_3.java
01 public class TestException7_3
02 {
03
public static void main(String args[])
04
{
05
try
06
{
07
int arr[]=new int[5];
08
arr[10]=7;
09
}
10
catch(ArrayIndexOutOfBoundsException e){
11
System.out.println("");
12
System.out.println(""+e); // e
13
}
14
System.out.println("main()");
15
}
16 }

java.lang.ArrayIndexOutOfBoundsException: 10
main()

TestException7_3 finally 10
catch() e ArrayIndexOutOfBoundsException
e 11

12 java.lang.
ArrayIndexOutOfBoundsException java.lang ArrayIndexOutOfBoundsException

269

7.1.4

Java
Java
TestException7_1 Java
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at TestException7_1.main(TestException7_1.java:6)
TestException7_1

try-catch-finally
TestException7_2 TestException7_3
7-2

7-2

270

7.2

java.lang.Exception java.lang.Error
java.lang.Throwable 7-3 Throwable

7-3

Throwable

Error Exception
Error

JAVA
Error
Error Exception
TestException7_2
ArrayIndexOutOfBoundsException
Exception
IOExceptionRunntimeException RunntimeException

RunntimeException IOException

271

catch catch

7.3

try_catch_finally throw
try-catch
1
2

7.3.1

throw
7-2
throw
7-2 throw

TestException7_4.java
01 public class TestException7_4
02 {
03
public static void main(String args[])
04
{
05
int a=4,b=0;
06
try

272

07
08
09
10
11
12
13
14
15
16
17
18 }

{
if(b==0)
throw new ArithmeticException(""); //
else
System.out.println(a+"/"+b+"="+a/b);//
}
catch(ArithmeticException e)
{
System.out.println(""+e);
}
}

java.lang.ArithmeticException:

1 TestException7_4 a/b b 0 b 0
ArithmeticException 0
2 try 8 b 0 b=0 9 throw
ArithmeticException b 0 a/b
b 0 try 9 13 catch()

3 throw 9 throw
new

7.3.2

273

try-catch-finally

7-3
throws 1 2
TestException7_5
main() add()

TestException7_5.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18

class Test
{
// throws
void add(int a,int b) throws Exception
{
int c;
c=a/b;
System.out.println(a+"/"+b+"="+c);
}
}
public class TestException7_5
{
public static void main(String args[])
{
Test t = new Test() ;
t.add(4,0);
}
}

274

TestException7_5.java:16: unreported exception java.lang.Exception; must be


caught
or declared to be thrown
t.add(4,0);
^
1 error

1 1~10 Test add(int a,int b)


throws Exception
2 15 Test t 16 Test add()

throws
try-catch

TestExeption7_5 main() throws Exception


throws
main()
main() throws
JVM

7.4

Java
Exception

7-4

275

class extends Exception


{

}

Exception

TestException7_6.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23

class DefaultException extends Exception


{
public DefaultException(String msg)
{
// Exception
super(msg) ;
}
}
public class TestException7_6
{
public static void main(String[] args)
{
try
{
// throw DefaultException
throw new DefaultException("") ;
}
catch(Exception e)
{
System.out.println(e) ;
}
}
}

276

DefaultException:

1 1~8 DefaultException Exception

2 6 super Exception

Exception
public Exception(String message)
3 16 throw DefaultException

JDK API

277


1 Java
1
2
2 trycatch finally
7-1
3 try

1 catch()catch
catch
2 try catch()
finally
3 finally

4
1 Java
2 try-catch-finally
5 java.lang.Exception java.lang.Error
6 RunntimeException
Exception

7 catch() Throwable
8
1
2
9 throw
10 throws
try-catch-finally

278


Java

8.1
8.1.1

package

package

package
package

8-1 package
package package ;
package package
TestPackage1 package

TestPackage1.java
01 package demo.java ;
02 class Person
03 {
04
public String talk()
05
{

279

06
07
08
09
10
11
12
13
14
15
16

return "Person >> talk()" ;


}
}
class TestPackage1
{
public static void main(String[] args)
{
System.out.println(new Person().talk()) ;
}
}
TestPackage1.java 1 package demo.java

1 demo.java
Person TestPackage1 demo.java

javac -d . TestPackage1.java

-d
.

demo demo
java Person.class TestPackage1.class

java demo.java.TestPackage1

Person >> talk()

280

8.1.2

import

package
package

public
package public
package .
8-2 package
import package .
import package
package
import TestPackage1

8-1

Person.java
01 package demo.java.a ;
02
03 public class Person
04 {
05
public String talk()

281

06
07
08
09 }

{
return "Person >> talk()" ;
}

1 demo.java.a Person
TestPackage2.java
01
02
03
04
05
06
07
08
09
10

package demo.java.b ;
import demo.java.a.Person ;
class TestPackage2
{
public static void main(String[] args)
{
System.out.println(new Person().talk()) ;
}
}

Person >> talk()

1 1 demo.java.b TestPackage2
2 2 import demo.java.a Person

2 import demo.java.a.Person import demo.java.a.*


java

282

TestPackage2.java
TestPackage3.java
01 package demo.java.b ;
02
03 class TestPackage3
04 {
05
public static void main(String[] args)
06
{
07
System.out.println(new demo.java.a.Person().talk()) ;
08
}
09 }
TestPackage3.java import 7
Person . Person

8.1.3

JDK

SUN JDK

1 java.lang Java StringMathIntegerSystem


Thread java.lang java.lang.reflect
java
2 java.awt abstract window toolkits
(GUI)
3 javax.swing java.awt

4 java.applet applet
5 java.net
6 java.io /

283

7 java.util

java1.2 java.lang
import System

8.2

JAVA
JAVA privatedefaultprotectedpublic

1 private
private
private

private
2

default

3 protected
protected

4 public
public

284

8.1

private
3

default
3

protected
3

public
3

privatedefaultpublic
protected
Person.java
01 package demo.java.a ;
02
03 public class Person
04 {
05
protected String name ;
06
public String talk()
07
{
08
return "Person >> talk()" ;
09
}
10 }

5 String name protected

Student.java
01 package demo.java.b ;
02 import demo.java.a.* ;
03
04 public class Student extends Person
05 {
06
07

public Student(String name)


{

285

08
09
10
11
12
13
14 }

this.name = name ;
}
public String talk()
{
return "Person >> talk() "+this.name ;
}

1 2 Person
2 4 Student Person
3 8 Student Person name

TestPackage4.java
01
02
03
04
05
06
07
08
09
10
11
12

package demo.java.c ;
import demo.java.b.* ;
class TestPackage4
{
public static void main(String[] args)
{
Student s = new Student("javafans") ;
s.name = "javafans" ;
System.out.println(s.talk()) ;
}
}

TestPackage4.java:9: name has protected access in demo.java.a.Person


s.name = "javafans" ;
^
1 error
9 JDK

286

8.2

Java

JDK JDK

demo.java

TestPerson

talkMySelf

COUNTRY

8.3

Jar

JDK JDK jre\lib\rt.jar


Java jar jar
classpath
jar Java Archive File Java jar
ZIP jar
jar
jar classpath
jar Java jar jar
jar
jar JDK JDK bin
c:\j2sdk1.4.0\bin Windows jar.exeLinux
jarjar Java (.class )
.jar jar .jar

JDK SUN

287


jar.exe

8_2
JDK
jar
jar cvf create.jar demo

-c

-v

-f

create.jar jar

demo jar

288


1 java
2 java package
3 java import
4 java privatedefaultprotectedpublic
5 jar jar

289

Java

JAVA
IO

Java API

290

9
Java
Java

9.1

CPU
CPU CPU

1
2

291

9.2

if-else
forwhile

Java Thread

ThreadDemo9_1

ThreadDemo9_1.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17

public class ThreadDemo9_1


{
public static void main(String args[])
{
new TestThread().run();
//
for(int i=0;i<10;i++)
{
System.out.println("main ");
}
}
}
class TestThread
{
public void run()
{
for(int i=0;i<10;i++)

292

18
19
20
21
22 }

{
System.out.println("TestThread ");
}
}

TestThread
TestThread
TestThread
TestThread
TestThread
TestThread
TestThread
TestThread
TestThread
TestThread
main
main
main
main
main
main
main
main
main
main

1 15~21 run() 10
2 5 TestThread run()TestThread

main main

main TestThread run()


Java

293

9 19 main TestThread
Java

1 Thread
2 run()

9.2.1

Thread

Thread java.lang java.lang


run() Thread run()

9-1

class extends Thread


{

run(){
;
}
}

// Thread

// Thread run()

ThreadDemo9_1

294

ThreadDemo9_1.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22

public class ThreadDemo9_1


{
public static void main(String args[])
{
new TestThread().start();
//
Thread start() run()
for(int i=0;i<10;i++)
{
System.out.println("main ");
}
}
}
class TestThread extends Thread
{
public void run()
TestThread Thread
{
for(int i=0;i<10;i++)
{
System.out.println("TestThread ");
}
}
}

main
TestThread
main
TestThread
main
TestThread
main
TestThread
main

295

TestThread
main
TestThread
main
TestThread
main
TestThread
main
TestThread
main
TestThread

13 TestThread Thread
5 run() start() Thread
start() start() run()

9.2.2

Runnable

JAVA
Java
Thread Java Runnable

296

9-2
class implements Runnable // Runnable
{

run(){
// Thread run()
;
}
}

ThreadDemo9_2.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23

public class ThreadDemo9_2


{
public static void main(String args[])
Runnable
{
TestThread t = new TestThread() ;
new Thread(t).start();
//
Thread start()
for(int i=0;i<10;i++)
{
System.out.println("main ");
}
}
}
class TestThread implements Runnable
{
TestThread Runnable
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println("TestThread ");
}
}
}

297


main
TestThread
main
TestThread
main
TestThread
main
TestThread
main
TestThread
main
TestThread
main
TestThread
main
TestThread
main
TestThread
main
TestThread

1 14 TestThread Runnable Runnable


run()
2 5 TestThread
3 6 TestThread Runnable Thread
start()

298

Thread Runnable
Runnable
Thread start() JDK
Runnable run() 9-1

9-1

Runnable

Runnable start()
Runnable Thread start()
JDK Thread Thread
public Thread(Runnable target)

Runnable
Thread Runnable

9.2.3

Runnable Thread

299

JDK 9-2

9-2

Thread Runnable

9-2 Thread Runnable Thread


Runnable

ThreadDemo9_3.java
20
Thread

ThreadDemo9_3.java
01 public class ThreadDemo9_3
02 {
03
public static void main(String [] args)
04
{
05
TestThread t=new TestThread();
06
//
07
t.start();

300

08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

t.start();
t.start();
t.start();
}
}
class TestThread extends Thread
{
private int tickets=20;
public void run()
{
while(true)
{
if(tickets>0)
System.out.println(Thread.currentThread().getName()+""+tickets--);
}
}
}

Exception in thread "main" java.lang.IllegalThreadStateException


at java.lang.Thread.start(Native Method)
at ThreadDemo9_3.main(ThreadDemo9_3.java:8)
Thread-0 20
Thread-0 19
Thread-0 18
Thread-0 17
Thread-0 16
Thread-0 15
Thread-0 14
Thread-0 13
Thread-0 12
Thread-0 11
Thread-0 10
Thread-0 9
Thread-0 8
Thread-0 7
Thread-0 6

301

Thread-0 5
Thread-0 4
Thread-0 3
Thread-0 2
Thread-0 1
5 TestThread
start()
Thread
start()
21 Thread.currentThread().getName()

ThreadDemo9_3 main()

ThreadDemo9_3.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19

public class ThreadDemo9_3


{
public static void main(String [] args)
{
//
new TestThread().start();
new TestThread().start();
new TestThread().start();
new TestThread().start();
}
}
class TestThread extends Thread
{
private int tickets=20;
public void run()
{
while(true)
{
if(tickets>0)

302

20
21
22
23 }

System.out.println(Thread.currentThread().getName()+""+tickets--);
}
}

Thread-3 5
Thread-2 4
Thread-3 4
Thread-2 3
Thread-3 3
Thread-1 2
Thread-2 2
Thread-1 1
Thread-2 1
Thread-3 2
Thread-3 1
Thread-0 12
Thread-0 11
Thread-0 10
Thread-0 9
Thread-0 8
Thread-0 7
Thread-0 6
Thread-0 5
Thread-0 4
Thread-0 3
Thread-0 2
Thread-0 1

Thread
Runnable ThreadDemo9_3

303

ThreadDemo9_4.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

public class ThreadDemo9_4


{
public static void main(String [] args)
{
TestThread t = new TestThread() ;
//
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
}
}
class TestThread implements Runnable
{
private int tickets=20;
public void run()
{
while(true)
{
if(tickets>0)
System.out.println(Thread.currentThread().getName()+""+tickets--);
}
}
}

Thread-1 20
Thread-1 19
Thread-1 18
Thread-1 17
Thread-1 16
Thread-1 15
Thread-1 14
Thread-1 13
Thread-2 12
Thread-3 11
Thread-4 10

304

Thread-2 9
Thread-3 8
Thread-4 7
Thread-2 6
Thread-3 5
Thread-4 4
Thread-2 3
Thread-3 2
Thread-4 1
7 10

Runnable Thread
1 CPU

2 Java

Thread
Runnable
3

Runnable
Runnable

305

9.3

Java Java main()


Applet Java Applet

9-3

9-3

Thread thread=new Thread();

2
start()
CPU

306

run()run()

CPU
sleep()suspend()wait()

5
stop() run()

9.4

JAVA Thread
Runnable Runnable Thread
9-1 Thread

307

9-1

Thread

public static int activeCount()


public static native Thread

currentThread()

public void destroy()


public static int enumerate(Thread tarray[])

public final String getName()


public final int getPriority()

public final ThreadGroup getThreadGroup()

public static boolean interrupted()

true false

public final native boolean isAlive()

true false

public boolean isInterrupted()

true false

public final void join() throws


InterruptedException

public final synchronized void join(long


millis)
throws InterruptedException

millis

public final synchronized void join(long


millis,
int nanos) throws InterruptedException

millis nanos

public void run()


public final void
public final void

setName()

setPriority(int newPriority)

public static native void sleep(long millis)


throws InterruptedException

millis

public static void sleep(long millis,int nanos)


throws InterruptedException

millis
nanos

public native synchronized void start()

public String toString()

public static native void yield()

308

9.4.1

Thread getName() setName()

Thread

GetNameThreadDemo.java
01 public class GetNameThreadDemo extends Thread
02 {
03
public void run()
04
{
05
for(int i=0;i<10;i++)
06
printMsg();
07
}
08
public void printMsg()
09
{
10
//
11
Thread t = Thread.currentThread();
12
String name = t.getName();
13
System.out.println("name = "+name);
14
}
15
public static void main(String[] args)
16
{
17
GetNameThreadDemo t1 = new GetNameThreadDemo();
18
t1.start();
19
for(int i=0;i<10;i++)
20
{

309

21
22
23
24 }

t1.printMsg();
}
}

name = Thread-0
name = main
name = Thread-0
name = main
name = Thread-0
name = main
name = Thread-0
name = main
name = Thread-0
name = main
name = main
name = Thread-0
name = Thread-0
name = main
name = Thread-0
name = main
name = Thread-0
name = main
name = Thread-0
name = main

1 1 GetNameThreadDemo Thread 3~7


Thread run()
2 8~14 printMsg() 11
Thread currentThread() Thread
9-1
12 Thread getName()

3 6 21 printMsg() 6 run()

310

21 main()

main main() java


JVM main()
GC

SetNameThreadDemo.java
01 public class SetNameThreadDemo extends Thread
02 {
03
public void run()
04
{
05
for(int i=0;i<10;i++)
06
{
07
printMsg();
08
}
09
}
10
public void printMsg()
11
{
12
//
13
Thread t = Thread.currentThread();
14
String name = t.getName();
15
System.out.println("name = "+name);
16
}
17
public static void main(String args[])
18
{
19
SetNameThreadDemo tt = new SetNameThreadDemo();
20
//
21
tt.setName("test thread");
22
tt.start();
23
for(int i=0;i<10;i++)

311

24
25
26

{
tt.printMsg();
}

27
28 }

name = main
name = test thread
name = main
name = test thread
name = main
name = test thread
name = main
name = test thread
name = main
name = test thread
name = main
name = test thread
name = test thread
name = main
name = test thread
name = main
name = test thread
name = main
name = test thread
name = main

21 Thread
setName()
test thread

312

9.4.2

Thread start()
run()

isAlive()

StartThreadDemo.java
01 public class StartThreadDemo extends Thread
02 {
03
public void run()
04
{
05
for(int i=0;i<10;i++)
06
{
07
printMsg();
08
}
09
}
10
public void printMsg()
11
{
12
//
13
Thread t = Thread.currentThread();
14
String name = t.getName();
15
System.out.println("name = "+name);
16
}
17
public static void main(String[] args) {
18
StartThreadDemo t = new StartThreadDemo();
19
t.setName("test Thread");
20
System.out.println(" start() , t.isAlive() = "+t.isAlive());
21
t.start();
22
System.out.println(" start() , t.isAlive() = "+t.isAlive());
23
for(int i=0;i<10;i++)
24
{
25
t.printMsg();
26
}
27
// false true
28
System.out.println("main() , t.isAlive() = "+t.isAlive());

313

29
30 }

start() , t.isAlive() = false


start() , t.isAlive() = true
name = main
name = test Thread
name = main
name = test Thread
name = main
name = test Thread
name = main
name = test Thread
name = main
name = test Thread
name = test Thread
name = main
name = test Thread
name = main
name = test Thread
name = main
name = test Thread
name = main
name = test Thread
name = main
main() , t.isAlive() = false

1 20 isAlive()
false
2 22 isAlive()
true

314

3 28 main() isAlive()
true false

9.4.3

setDaemon()

Java

start() setDaemon(true)

ThreadDaemon.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19

public class ThreadDaemon


{
public static void main(String args[])
{
ThreadTest t = new ThreadTest() ;
Thread tt = new Thread(t) ;
tt.setDaemon(true) ;
//
tt.start();
}
}
class ThreadTest implements Runnable
{
public void run()
{
while(true)
{
System.out.println(Thread.currentThread().getName()+"is running.");
}

315

20
21 }

9-4

9-4

9.4.4

ThreadJoin.java
01 public class ThreadJoin
02 {
03
public static void main(String[] args)
04
{

316

05
06
07
08
09

ThreadTest t=new ThreadTest();


Thread pp=new Thread(t);
pp.start();
int i=0;
for(int x=0;x<10;x++)

10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

{
if(i==5)
{
try
{
//

pp.join();

}
catch(Exception e)
// InterruptedException
{
System.out.println(e.getMessage());
}
}
System.out.println("main Thread "+i++);
}
}
}
class ThreadTest implements Runnable
{
public void run()
{
String str=new String();
int i=0;
for(int x=0;x<10;x++)
{
System.out.println(Thread.currentThread().getName()+" ---->> "+i++);
}
}
}

main Thread 0
main Thread 1

317

main Thread 2
main Thread 3
main Thread 4
Thread-0 ---->> 0
Thread-0 ---->> 1
Thread-0 ---->> 2
Thread-0 ---->> 3
Thread-0 ---->> 4
Thread-0 ---->> 5
Thread-0 ---->> 6
Thread-0 ---->> 7
Thread-0 ---->> 8
Thread-0 ---->> 9
main Thread 5
main Thread 6
main Thread 7
main Thread 8
main Thread 9

1 main() pp
2 15 pp join()
join() pp join()

pp main pp
main JDK
join join join(long millis) join(long
millis,int nanos)

join

318

9.4.5

Thread sleep(long millis)

TwoThreadSleep.java
01 public class TwoThreadSleep extends Thread {
02
public void run() {
03
loop();
04
}
05
public void loop() {
06
String name = Thread.currentThread().getName();
07
System.out.println(name+" ---->> loop ");
08
for ( int i = 0; i < 10; i++ )
09
{
10
try {
11
Thread.sleep(2000);
12
} catch ( InterruptedException x ) {}
13
System.out.println("name=" + name);
14
}
15
System.out.println(name+" ---->> loop ") ;
16
}
17
public static void main(String[] args)
18
{
19
TwoThreadSleep tt = new TwoThreadSleep();
20
tt.setName("my worker thread");
21
tt.start();
22
try {
23
Thread.sleep(700);
24
} catch ( InterruptedException x ) {}
25
tt.loop();
26
}
27 }

my worker thread ---->> loop

319

main ---->> loop


name=my worker thread
name=main
name=my worker thread
name=main
name=my worker thread
name=main
name=my worker thread
name=main
name=my worker thread
name=main
name=my worker thread
name=main
name=my worker thread
name=main
name=my worker thread
name=main
name=my worker thread
name=main
name=my worker thread
my worker thread ---->> loop
name=main
main ---->> loop
11 23 sleep()

sleep() InterruptedException try..catch()

9.4.6

Thread interrupt()

320

SleepInterrupt.java
01 public class SleepInterrupt implements Runnable
02 {
03
public void run()
04
{
05
try {
06
System.out.println(" run() - 20 ");
07
Thread.sleep(20000);
08
System.out.println(" run() - ");
09
}
10
catch (InterruptedException x) {
11
System.out.println(" run() - ");
12
return;
13
}
14
System.out.println(" run() - ");
15
System.out.println(" run() - ");
16
}
17
public static void main(String[] args)
18
{
19
SleepInterrupt si = new SleepInterrupt();
20
Thread t = new Thread(si);
21
t.start();
22
//
23
try {
24
Thread.sleep(2000);
25
}
26
catch (InterruptedException x) {}
27
System.out.println(" main() - ");
28
t.interrupt();
29
System.out.println(" main() - ");
30
}
31 }

run() - 20
main() -
run() -

321

main() -

1 SleepInterrupt Runnable run() run()


20
2 21 start()
3 23~26 sleep() 2 run()

4 28 Thread t main() main()


interrupt()

Thread isInterrupted()
InterruptCheck.java
01 public class InterruptCheck
02 {
03
public static void main(String[] args)
04
{
05
Thread t = Thread.currentThread();
06
System.out.println("At.isInterrupted() = " + t.isInterrupted());
07
t.interrupt();
08
System.out.println("Bt.isInterrupted() = " + t.isInterrupted());
09
System.out.println("Ct.isInterrupted() = " + t.isInterrupted());
10
try {
11
Thread.sleep(2000);
12
System.out.println("");
13
} catch ( InterruptedException x ) {
14
System.out.println("");
15
}
16
// sleep
17
System.out.println("Dt.isInterrupted() = " + t.isInterrupted());
18
}

322

19 }

At.isInterrupted() = false
Bt.isInterrupted() = true
Ct.isInterrupted() = true

Dt.isInterrupted() = false

1 5 Thread currentThread()
main() main()
2 6 7

3 11

9.5
9.5.1

9-2-3
0

if(tickets>0)
System.out.println(Thread.currentThread().getName()+"

323

"+tickets--);
tickets 1 1 if(tickets>0)
CPU 2 tickets

1 2 tickets 0 CPU 1
1 if(tickets>0)
1

System.out.println(Thread.currentThread().getName()+""+tickets--);
tickets 0 0
Thread.sleep()
Thread.sleep() CPU
CPU
TestThread

ThreadDemo9_5.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17

public class ThreadDemo9_5


{
public static void main(String [] args)
{
TestThread t = new TestThread() ;
//
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
}
}
class TestThread implements Runnable
{
private int tickets=20;
public void run()
{

324

18
19
20
21

while(true)
{
if(tickets>0)
{

22
23
24
25
26
27
28
29
30 }

try{
Thread.sleep(100);
}
catch(Exception e){}
System.out.println(Thread.currentThread().getName()+""+tickets--);
}
}
}

if(tickets>0)
Thread.sleep(100) CPU

Thread-1 3
Thread-2 2
Thread-3 1
Thread-0 0
Thread-1 -1
Thread-2 -2

325

9.5.2

if(tickets>0)
{
System.out.println(Thread.currentThread().getName()+""+tickets--);
}
if(tickets>0)CPU

9-3

synchronized()
{
;
}

ThreadDemo9_5 TestThread

class TestThread implements Runnable


{
private int tickets=20;
public void run()
{

326

while(true)
{
synchronized(this)
{
if(tickets>0)
{
try{
Thread.sleep(100);
}
catch(Exception e){}
System.out.println(Thread.currentThread().getName()+""+tickets--);
}
}
}
}
}
synchronized

9.5.3

synchronized
9-4
synchronized ()
{
. ;
}
TestThread
class TestThread implements Runnable

327

{
private int tickets=20;
public void run()
{
while(true)
{
sale() ;
}
}
public synchronized void sale()
{
if(tickets>0)
{
try{
Thread.sleep(100);
}
catch(Exception e){}
System.out.println(Thread.currentThread().getName()+""+tickets--);
}
}
}

synchronized
synchronized
synchronized
synchronized
synchronized

9.5.3

328

1 A B
2 B A

A B funA() funB()
funA() funB() DeadLockDemo A
B funA() funB() sleep()

DeadLockDemo.java
01 class A
02 {
03
synchronized void funA(B b)
04
{
05
String name=Thread.currentThread().getName();
06
System.out.println(name+ " A.foo ");
07
try
08
{
09
Thread.sleep(1000);
10
}
11
catch(Exception e)
12
{
13
System.out.println(e.getMessage());
14
}
15
System.out.println(name+ " B last()");
16
b.last();

329

17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53

}
synchronized void last()
{
System.out.println("A last()");
}
}
class B
{
synchronized void funB(A a)
{
String name=Thread.currentThread().getName();
System.out.println(name + " B ");
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
System.out.println(name + " A last()");
a.last();
}
synchronized void last()
{
System.out.println("B last()");
}
}
class DeadLockDemo implements Runnable
{
A a=new A();
B b=new B();
DeadLockDemo()
{
//
Thread.currentThread().setName("Main -->> Thread");
new Thread(this).start();

330

54
55
56

a.funA(b);
System.out.println("main ");
}

57
58
59
60
61
62
63
64
65
66
67 }

public void run()


{
Thread.currentThread().setName("Test -->> Thread");
b.funB(a);
System.out.println("");
}
public static void main(String[] args)
{
new DeadLockDemo();
}

9-5

9-5

DeadLockDemo

Test -->> Thread b a


Main -->> Thread a b

331

9.6

9.6.1

CPU

9-6

9-6

332

9.6.2

run
Producer Consumer
class Producer implements Runnable
{
public void run()
{
while(true)
{
//
}
}
}
class Consumer implements Runnable
{
public void run()
{
while(true)
{
//
}
}
}

class P
{
String name;
String sex;

333

Producer Consumer run P


Producer Consumer
ThreadCommunation

ThreadCommunation.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

class Producer implements Runnable


{
P q=null;
public Producer(P q)
{
this.q=q;
}
public void run()
{
int i=0;
while(true)
{
if(i==0)
{
q.name="";
q.sex="";
}
else
{
q.name="";
q.sex="";
}
i=(i+1)%2;
}
}
}
class P
{

334

29
30
31 }
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55

String name="";
String sex="";

class Consumer implements Runnable


{
P q=null;
public Consumer(P q)
{
this.q=q;
}
public void run()
{
while(true)
{
System.out.println(q.name + " ---->" + q.sex);
}
}
}
public class ThreadCommunation
{
public static void main(String [] args)
{
P q=new P();
new Thread(new Producer(q)).start();
new Thread(new Consumer(q)).start();
}
}
9-7

335

9-7

ThreadCommunation

Producer Consumer
P Producer P Consumer P
P set() get()

ThreadCommunation.java
01 class Producer implements Runnable
02 {
03
P q=null;

336

04
05
06

public Producer(P q)
{
this.q=q;

07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

}
public void run()
{
int i=0;
while(true)
{
if(i==0)
{
q.set("","");
}
else
{
q.set("","");
}
i=(i+1)%2;
}
}
}
class P
{
private String name="";
private String sex="";
public synchronized void set(String name,String sex)
{
this.name = name ;
this.sex =sex ;
}
public synchronized void get()
{
System.out.println(this.name + " ---->" + this.sex ) ;
}
}
class Consumer implements Runnable
{

337

41
42
43
44
45
46
47
48
49
50
51
52
52
53
54
55
56
57
58
59
60
61

P q=null;
public Consumer(P q)
{
this.q=q;
}
public void run()
{
while(true)
{
q.get();
}
}
}
public class ThreadCommunation
{
public static void main(String [] args)
{
P q=new P();
new Thread(new Producer(q)).start();
new Thread(new Consumer(q)).start();
}
}
9-8

338

9-8

Consumer Producer
Producer Consumer
Producer Consumer
Java Object waitnotifynotifyAll
Object

wait
notify
notify wait

notifyAll wait

339

P
bFull Consumer bFull false
Producer bFull true bFull true Consumer
Producer bFull
falseProducer Consumer
P
01 class P
02 {
03
private String name="";
04
private String sex="";
05
boolean bFull = false ;
06
public synchronized void set(String name,String sex)
07
{
08
if(bFull)
09
{
10
try
11
{
12
wait() ; //
13
}
14
catch(InterruptedException e)
15
{}
16
}
17
this.name = name ;
18
try
19
{
20
Thread.sleep(10);
21
}
22
catch(Exception e)
23
{
24
System.out.println(e.getMessage());
25
}
26
this.sex = sex ;
27
bFull = true ;

340

28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45 }

//

notify();

}
public synchronized void get()
{
if(!bFull)
{
try
{
wait() ;
}
catch(InterruptedException e)
{}
}
System.out.println(name+" ---->"+sex);
bFull = false ;
notify();
}

9-9

341

9-9

waitnotifynotifyAll synchronized
wait notify
notify
wait
waitnotify wait notify
9-10

342

9-10

9.7

9-11

343

9-11

suspend resume stop


suspend resume
(1)
(2)

stop
stop
stop

ThreadLife.java
01 public class ThreadLife
02 {
03
public static void main(String [] args)
04
{
05
TestThread t=new TestThread();
06
new Thread(t).start();

344

07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

for(int i=0;i<10; i++)


{
if(i == 5)
t.stopMe();
System.out.println("Main ");
}
}
}
class TestThread implements Runnable
{
private boolean bFlag = true;
public void stopMe()
{
bFlag = false;
}
public void run()
{
while(bFlag)
{
System.out.println(Thread.currentThread().getName()+" ");
}
}
}

Main
Thread-0
Main
Thread-0
Main
Thread-0
Main
Thread-0
Main
Thread-0
Thread-0
Main

345

Main
Main
Main
Main

i main i
0 4 i 5
TestThread stopMe stopMe bFlag
false while run Thread-0 main
i 5 TestThread stopMe CPU
Thread-0 Thread-0 main
i Thread-0
run

346


1 thread

2
1 Thread
2 run()
3 run() Thread run()

4 Runnable run() Runnable


run()
5

6
1 wait()
2 sleep()
3 join()
7
1 wait() notify()

2sleep
8 run() stop()

9 Thread sleep() sleep()

10 join()
11join() InterruptedException join()
try-catch
12 synchronized

347

10

IO

IO
JAVA
java.io

10.1

File

File IO File
File

Java UNIX Windows/DOS Windows


Java / Windows/DOS
\\\
Java UNIX
URL
File
File(String directoryPath)

directoryPath
File File getName( )
getParent( )exists( ) true
false File
File

FileDemo.java
01 import java.io.*;
02 public class FileDemo
03 {

348

04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

public static void main(String[] args)


{
File f=new File("c:\\1.txt");
if(f.exists())
f.delete();
else
try
{
f.createNewFile();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
// getName()
System.out.println(""+f.getName());
// getPath()
System.out.println(""+f.getPath());
// getAbsolutePath()
System.out.println(""+f.getAbsolutePath());
// getParent()
System.out.println(""+f.getParent());
// exists()
System.out.println(f.exists()?"":"");
// canWrite()
System.out.println(f.canWrite()?"":"");
// canRead()
System.out.println(f.canRead()?"":"");
/// isDirectory()
System.out.println(f.isDirectory()?"":""+"");
// isFile()
System.out.println(f.isFile()?"":"");
// isAbsolute()
System.out.println(f.isAbsolute()?"":"");
// lastModified()
System.out.println(""+f.lastModified());
// length()

349

41
42
43 }

System.out.println(""+f.length()+" Bytes");
}

1.txt
c:\1.txt
c:\1.txt
c:\

1122277108000
0 Bytes
File
Java API

10-2

RandomAccessFile

RandomAccessFile Java
RandomAccessFile

RandomAccessFile

RandomAccessFile n
n

RandomAccessFile

350

IO

RandomAccessFile JDK
RandomAccessFile
RandomAccessFile
RandomAccessFile

//
//

new RandomAccessFile(f,"rw");
new RandomAccessFile(f,"r");

name 8
8 ("\u0000") 8
4

RandomFileDemo.java
01 import java.io.*;
02 public class RandomFileDemo
03 {
04
public static void main(String [] args) throws Exception
05
{
06
Employee e1 = new Employee("zhangsan",23);
07
Employee e2 = new Employee("lisi",24);
08
Employee e3 = new Employee("wangwu",25);
09
RandomAccessFile ra=new RandomAccessFile("c:\\employee.txt","rw");
10
ra.write(e1.name.getBytes());

351

11
12

ra.writeInt(e1.age);
ra.write(e2.name.getBytes());

13
ra.writeInt(e2.age);
14
ra.write(e3.name.getBytes());
15
ra.writeInt(e3.age);
16
ra.close();
17
RandomAccessFile raf=new RandomAccessFile("c:\\employee.txt","r");
18
int len=8;
19
raf.skipBytes(12); // , 8 , 4
20
System.out.println(":");
21
String str="";
22
for(int i=0;i<len;i++)
23
str=str+(char)raf.readByte();
24
System.out.println("name:"+str);
25
System.out.println("age:"+raf.readInt());
26
System.out.println(":");
27
raf.seek(0);
//
28
str="";
29
for(int i=0;i<len;i++)
30
str=str+(char)raf.readByte();
31
System.out.println("name:"+str);
32
System.out.println("age:"+raf.readInt());
33
System.out.println(":");
34
raf.skipBytes(12); //
35
str="" ;
36
for(int i=0;i<len;i++)
37
str=str+(char)raf.readByte();
38
System.out.println("name:"+str.trim());
39
System.out.println("age:"+raf.readInt());
40
raf.close();
41
}
42 }
43 class Employee
44 {
45
String name;
46
int age;
47
final static int LEN=8;

352

48
49

public Employee(String name,int age)


{

50
51
52
53
54
55
56
57
58
59
60
61
62 }

if(name.length()>LEN)
{
name=name.substring(0,8);
}
else
{
while(name.length()<LEN)
name=name+"\u0000";
}
this.name=name;
this.age=age;
}

:
name:lisi
age:24
:
name:zhangsan
age:23
:
name:wangwu
age:25
RandomAccessFile
String.substring(int beginIndex,int endIndex)

beginIndex endIndex-1
endIndex

353

10-3

Java /InputStream, OutputStream,


Reader Writer/

InputStream OutputStream Reader Writer

1 File
2 File
3
4

10.3.1

InputStream OutputStream

10.3.1.1

InputStream

InputStream Java

354

IOException 10-1 InputStream


10-1 InputStream

int available( )

IOException

void close( )

NBytes
void mark(int numBytes)
boolean markSupported( )

mark( )/reset( )true


-1

int read( )

buffer.lengthbuffer
int read(byte buffer[ ])
int read(byte buffer[ ], int offset,int

-1
bufferbuffer[offset]numBytes

numBytes)

-1

void reset( )

long skip(long numBytes)

10.3.1.2

numBytes

OutputStream

OutputStreamvoid
IOException10-2OutputStream

10-2

OutputStream

void close( )

IOException

void flush( )

void write(int b)

write

void write(byte buffer[ ])

void write(byte buffer[ ], int offset,int

bufferbuffer[offset]numBytes

numBytes)

355


InputStream OutputStream
mark( ) reset( )

10.3.1.3

FileInputStream

FileInputStream InputStream

FileInputStream(String filepath)
FileInputStream(File fileObj)

FileNotFoundExceptionfilepath
fileObjFile

FileInputStreams
InputStream f0 = new FileInputStream("c:\\test.txt") ;
File f = new File("c:\\test.txt");
InputStream f1 = new FileInputStream(f);

FileFileInputStream

10.3.1.4

FileOutputStream

FileOutputStream OutputStream

356

FileOutputStream(String filePath)
FileOutputStream(File fileObj)
FileOutputStream(String filePath, boolean append)

IOException SecurityException filePath


fileObj File append true
FileOutputStream
FileOutputStream
IOException
FileOutputStream
FileInputStream
StreamDemo.java
01 import java.io.*;
02 public class StreamDemo
03 {
04
public static void main(String args[])
05
{
06
File f = new File("c:\\temp.txt") ;
07
OutputStream out = null ;
08
try
09
{
10
out = new FileOutputStream(f) ;
11
}
12
catch (FileNotFoundException e)
13
{
14
e.printStackTrace();
15
}
16
//
17
byte b[] = "Hello World!!!".getBytes() ;
18
try
19
{
20
// byte

357

21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58

out.write(b) ;
}
catch (IOException e1)
{
e1.printStackTrace();
}
try
{
out.close() ;
}
catch (IOException e2)
{
e2.printStackTrace();
}
//
InputStream in = null ;
try
{
in = new FileInputStream(f) ;
}
catch (FileNotFoundException e3)
{
e3.printStackTrace();
}
//
byte b1[] = new byte[1024] ;
int i = 0 ;
try
{
// b1 read()
i = in.read(b1) ;
}
catch (IOException e4)
{
e4.printStackTrace();
}
try

358

59
60
61
62
63
64
65
66
67
68
69 }

{
in.close() ;
}
catch (IOException e5)
{
e5.printStackTrace();
}
// byte
System.out.println(new String(b1,0,i)) ;
}

Hello World!!!

8 ~ 34

36 ~ 65
1 6 File C temp.txt
2
1 8 ~ 15 File OutputStream
FileOutputStream OutputStream

2 byte 17 String
getBytes() byte
3 18 ~ 26 OutputStream write() byte

4 27 ~ 34 OutputStream close()
3
1 37 ~ 45 File InputStream
FileInputStream InputStream
2 byte 47 1024
byte

359

3 49 ~ 57 InputStream read()
byte
4 58 ~ 65 InputStream close()
5 67 byte

throws
JDK

10.3.2

/
Unicode Java

Reader Writer

10.3.2.1

Reader

ReaderJava
IOException

10-3Reader

360

10-3 Reader

abstract void close( )

IOException

void mark(int numChars)

numChars
mark( )/reset( )true

boolean markSupported( )

int read( )

-1
bufferbuffer.length

int read(char buffer[ ])

-1
bufferbuffer[offset]numChars

abstract int read(char buffer[ ],int offset,int

numChars)

-1
true

boolean ready( )

false
numChars

long skip(long numChars)

10.3.2.2

Writer

Writer void
IOException 10-4Writer

361

10-4

Writer

abstract void close( )

IOException

abstract void flush( )

write

void write(int ch)

void write(char buffer[ ])

buffer buffer[offset]

abstract void write(char buffer[ ],int offset,

NChars

int numChars)

str

void write(String str)

stroffsetnumChars
void write(String str, int offset,int numChars)

10.3.2.3

FileReader

FileReader Reader

FileReader(String filePath)
FileReader(File fileObj)

FileNotFoundException filePath
fileObj File

10.3.2.4

FileWriter

FileWriter Writer

362

FileWriter(String filePath)
FileWriter(String filePath, boolean append)
FileWriter(File fileObj)

IOException SecurityException filePath


fileObj File append true
FileWriter FileWriter
IOException

CharDemo.java
01 import java.io.*;
02 public class CharDemo
03 {
04
public static void main(String args[])
05
{
06
File f = new File("c:\\temp.txt") ;
07
Writer out = null ;
08
try
09
{
10
out = new FileWriter(f) ;
11
}
12
catch (IOException e)
13
{
14
e.printStackTrace();
15
}
16
// String
17
String str = "Hello World!!!" ;
18
try
19
{
20
// str
21
out.write(str) ;
22
}

363

23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59

catch (IOException e1)


{
e1.printStackTrace();
}
try
{
out.close() ;
}
catch (IOException e2)
{
e2.printStackTrace();
}
//
Reader in = null ;
try
{
in = new FileReader(f) ;
}
catch (FileNotFoundException e3)
{
e3.printStackTrace();
}
//
char c1[] = new char[1024] ;
int i = 0 ;
try
{
// c1 read()
i = in.read(c1) ;
}
catch (IOException e4)
{
e4.printStackTrace();
}
try
{

364

60
61
62
63
64
65
66
67
68
69 }

in.close() ;
}
catch (IOException e5)
{
e5.printStackTrace();
}
//
System.out.println(new String(c1,0,i)) ;
}

Hello World!!!

8
~ 34
36 ~ 65
1 6 File C temp.txt
2
1 7 ~ 15 File Writer
FileWriter Writer
2 17 String
str
3 18 ~ 26 Writer write()

4 27 ~ 34 Writer close()
3
1 37 ~ 45 File Reader
FileReader Reader
2 char 47 1024
char
3 49 ~ 57 Reader read() char

365


4 58 ~ 65 Reader close()
5 67 char

CharDemo 27 34

JDK FileWriter 10-1

10-1 FileWriter
FileWriter Writer
Writer OutputStreamWriter

Writer flush()

10.3.3

PipedInputStreamPipedOutputStreamPipedReaderPipedWriter
PipedInputStream PipedOutputStream
PipedInputStream PipedOutputStream
PipedOutputStream PipedInputStream

366

PipedOutputStream 10-2
PipedInputStream
PipedOutputStream

10-2

PipeStreamDemo.java
01 import java.io.*;
02 public class PipeStreamDemo
03 {
04
public static void main(String args[])
05
{
06
try
07
{
08
Sender sender = new Sender();
//
09
Receiver receiver = new Receiver();
10
PipedOutputStream out = sender.getOutputStream(); //
11
PipedInputStream in = receiver.getInputStream();
//
12
out.connect(in);
//
13
sender.start();
//
14
receiver.start();
15
}
16
catch(IOException e)
17
{

367

18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54

System.out.println(e.getMessage());
}
}
}
class Sender extends Thread
{
private PipedOutputStream out=new PipedOutputStream();
public PipedOutputStream getOutputStream()
{
return out;
}
public void run()
{
String s=new String("Receiver!");
try
{
out.write(s.getBytes());
//
out.close();
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
}
}
class Receiver extends Thread
{
private PipedInputStream in=new PipedInputStream();
public PipedInputStream getInputStream()
{
return in;
}
public void run()
{
String s=null;
byte [] buf = new byte[1024];
try

368

55
56
57
58
59
60
61
62
63
64
65
66 }

{
int len =in.read(buf);
//
s = new String(buf,0,len);
System.out.println(""+s);
in.close();
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
}

Receiver!

1 22~42 Sender Thread Runnable


run() 24 PipedOutputStream out

2 43~66 Receiver Thread


Runnable run() 45 PipedInputStream in

3 8 9 Sender Receiver
connect

369

10.3.4 ByteArrayInputStream ByteArrayOutputStream


ByteArrayInputStream

ByteArrayInputStream(byte[] buf)
ByteArrayInputStream(byte[] buf,int offse , int length)
ByteArrayOutputStream()
BuyteArrayoutputStream(int)
JDK
ByteArrayInputStream ByteArrayOutputStream

ByteArrayDemo.java
01 import java.io.* ;
02 public class ByteArrayDemo {
03
public static void main(String[] args) throws Exception
04
{
05
String tmp = "abcdefghijklmnopqrstuvwxyz";
06
byte[] src = tmp.getBytes();
// src
07
ByteArrayInputStream input = new ByteArrayInputStream(src);
08
ByteArrayOutputStream output = new ByteArrayOutputStream();
09
new ByteArrayDemo().transform(input, output);
10
byte[] result = output.toByteArray(); // result
11
System.out.println(new String(result));
12
}
13
public void transform(InputStream in, OutputStream out)
14
{
15
int c = 0;
16
try
17
{
18
while ((c = in.read()) != -1)
// read -1
19
{
20
int C = (int) Character.toUpperCase((char) c);
21

out.write(C);

370

22
23
24
25
26
27
28
29 }

}
}
catch (Exception e)
{
e.printStackTrace();
}
}

10.3.5

System.in System.out

Java System.in
System.outSystem.in InputStream System.in
System.out PrintStream PrintStream
OutputStream System.out

10.3.6

PrintStream print println


System.out.println
System.out PrintStream PrintStream
PrintStream(OutputStream out)
PrintStream(OutputStream out,boolean auotflush)
PrintStream(OutputStream out,boolean auotflush, String encoding)

autoflush Java (\n)encoding

println print

(\n) println() print("\n")

371

Java PrintStream print println


Objectprint println
221
2
2
1 221
print println
toString toString
IO PrintStream PrintWriter PrintWriter

PrintWriter(OutputStream)
PrintWriter(OutputStream, boolean)
PrintWriter(Writer)
PrintWriter(Writer, boolean)

PrintWriter (\n) autoflush


println PrintWriter PrintStream
println Windows "\r\n" Linux
"\n"
"\n" PrintWriter println PrintWriter println

PrintWriter
SystemPrintDemo.java
01 import java.io.*;
02 public class SystemPrintDemo
03 {
04
public static void main(String args[])
05
{
06
PrintWriter out = null;
07
// System.out PrintWriter
08
out = new PrintWriter(System.out);
09
//
10

out. print ("Hello World!");

372

11
12
13 }

out.close();
}

Hello World!

8 System.out PrintWriterPrintWriter
out 10 print()

PrintWriter

FilePrint.java
01 import java.io.*;
02 public class FilePrint
03 {
04
public static void main(String args[])
05
{
06
PrintWriter out = null ;
07
File f = new File("c:\\temp.txt") ;
08
try
09
{
10
out = new PrintWriter(new FileWriter(f)) ;
11
}
12
catch (IOException e)
13
{
14
e.printStackTrace();
15
}
16
// FileWriter
17
out. print ("Hello World!"+"\r\n");
18
out.close() ;
19

373

20 }

10-3 FilePrint

10 FileWriter PrintWriterPrintWriter
out 17 print()

10.3.7

DataInputStream DataOutputStream

DataInputStream DataOutputStream
DataOutputStream DataInputStream
java

order.txt

374

18.99

10

9.22

10

1 DataOutputStream
//
DataOutputStream out = new DataOutputStream(new FileOutputStream("order.txt"));
//
double[] prices = { 18.99, 9.22, 14.22, 5.22, 4.21 };
//
int[] units = { 10, 10, 20, 39, 40 };
//
String[] descs = { "T ", "", "", "", "" };
//
for (int i = 0; i < prices.length; i++)
{
// tab
out.writeDouble(prices[i]);
out.writeChar('\t');
//
out.writeInt(units[i]);
out.writeChar('\t');
//
out.writeChars(descs[i]);
out.writeChar('\n');
}
out.close();
2
//
DataInputStream in = new DataInputStream(new FileInputStream("order.txt"));
double price;
int unit;

375

StringBuffer desc;
double total = 0.0;
try
{
// EOFException
while (true)
{
//
price = in.readDouble();
// tab
in.readChar();
//
unit = in.readInt();
// tab
in.readChar();
char chr;
//
desc = new StringBuffer();
while ((chr = in.readChar()) != '\n')
{
desc.append(chr);
}
System.out.println(" " + ""+desc+"\t
"+unit+"\t "+price);
total = total + unit * price;
}
}
catch (EOFException e)
{
System.out.println("\n " + total+"");
}
in.close();

DataInputStreamDemo.java
01 import java.io.* ;

376

02 public class DataStreamDemo


03 {
04
public static void main(String[] args) throws IOException
05
{
06
//
07 DataOutputStream out = new DataOutputStream(new FileOutputStream("order.txt"));
08
//
09
double[] prices = { 18.99, 9.22, 14.22, 5.22, 4.21 };
10
//
11
int[] units = { 10, 10, 20, 39, 40 };
12
//
13
String[] descs = { "T ", "", "", "", "" };
14
15
//
16
for (int i = 0; i < prices.length; i++)
17
{
18
// tab
19
out.writeDouble(prices[i]);
20
out.writeChar('\t');
21
//
22
out.writeInt(units[i]);
23
out.writeChar('\t');
24
//
25
out.writeChars(descs[i]);
26
out.writeChar('\n');
27
}
28
out.close();
29
30
//
31
DataInputStream in = new DataInputStream(new FileInputStream("order.txt"));
32
33
double price;
34
int unit;
35
StringBuffer desc;
36
double total = 0.0;
37
38

try

377

39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70 }

{
// EOFException
while (true)
{
//
price = in.readDouble();
// tab
in.readChar();
//
unit = in.readInt();
// tab
in.readChar();
char chr;
//
desc = new StringBuffer();
while ((chr = in.readChar()) != '\n')
{
desc.append(chr);
}
System.out.println(" " + ""+desc+"\t
"
+unit+"\t "+price);
total = total + unit * price;
}
}
catch (EOFException e)
{
System.out.println("\n " + total+"");
}
in.close();
}

378

10 18.99

10 9.22

20 14.22

39 5.22

40 4.21

938.4799999999999

10.3.8

SequenceInputStream 10-4

10-4
SequenceDemo.java
01 import java.io.*;
02 public class SequenceDemo
03 {
04
public static void main(String[] args) throws IOException
05
{
06
//
07
FileInputStream in1 = null, in2 = null;
08
//
09
SequenceInputStream s = null;
10

FileOutputStream out = null;

379

11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

try
{
//
File inputFile1 = new File("c:\\1.txt");
File inputFile2 = new File("c:\\2.txt");
//
File outputFile = new File("c:\\12.txt");
in1 = new FileInputStream(inputFile1);
in2 = new FileInputStream(inputFile2);
//
s = new SequenceInputStream(in1, in2);
out = new FileOutputStream(outputFile);
int c;
while ((c = s.read()) != -1)
out.write(c);
in1.close();
in2.close();
s.close();
out.close();
System.out.println("ok...");
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if (in1 != null)
try {
in1.close();
} catch (IOException e) {
}

380

48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65 }

if (in2 != null)
try {
in2.close();
} catch (IOException e) {
}
if (s != null)
try {
s.close();
} catch (IOException e) {
}
if (out != null)
try {
out.close();
} catch (IOException e) {
}
}
}

10-5 SequenceDemo

381

10.3.9

Java

InputStreamReader OutputStreamWriter
InputStreamReader OuputStreamWriter

InputStreamReader
InputStreamReader(InputStream in)
// InputStreamReader
InputStreamReader(InputStream in,String CharsetName)
//

OutputStreamWriter

OutputStreamWriter(OutputStream in)
// OutputStreamWriter
OutputStreamWriter(OutputStream in,String CharsetNarme)
// OutputStreamWriter

BufferedWriter OutputStreamWriter
BufferedReader InputStreamReader
BufferedWriter out=new BufferedWriter(newOutputStreamWriter(System.out));
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
InputStreamReader

BufferedReader in=new BufferedReader(new InputStreamReader(System.in));

382

String strLine = in.readLine();


BufferedReader Reader
System.in InputStream
InputStreamReader System.in

10-1
import java.io.*;
public class class_name
//
{
public static void main(String args[]) throws IOException
{
BufferedReader buf; // buf BufferedReader
String str;
// str String
... ...
buf=new BufferedReader(new InputStreamReader(System.in));
str=buf.readLine();
// buf
... ...
}
}
BufferDemo.java
01 public class BufferDemo
02 {
03
public static void main(String args[])
04
{
05
BufferedReader buf = null;
06
buf = new BufferedReader(new InputStreamReader(System.in));
07
String str = null;
08
while (true)
09
10
11

{
System.out.print("");
try

383

12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32 }

{
str = buf.readLine();
} catch (IOException e)
{
e.printStackTrace();
}
int i = -1;
try
{
i = Integer.parseInt(str);
i++;
System.out.println("" + i);
break;
}
catch (Exception e)
{
System.out.println("");
}
}
}

22
23

1 5 6 BufferedReader
System.in System.in InputStream
InputStreamReader
BufferedReader
2 13 BufferedReader readLine()
3 21 Integer
4 22 23

384

10.3.10
10.3.10.1

IO
InputStream

InputStream 10-6

10-6 InputStream

10.3.10.2

OutputStream 10-7

385

10-7 OutputStream

10.3.10.3

Reader 10-8

10-8 Reader

386

10-3.10.4

Writer 10-9 :

10-9 Writer

10.4

bit 0 0 127 a 97
b 98
ASCII

387


ASCII ASCII
bit 1

GBK GBK
GB2312 GBK GB2312
D6D0
A4A4
BIG5

D6D0

Unicode

4e2d

Unicode
2 16 65536 Unicode

388

Unicode
Unicode
Unicode
Java Unicode Java Unicode

String get Bytes()

EncodingDemo.java
01 public class EncodingDemo
02 {
03
public static void main(String args[]) throws Exception
04
{
05
// getBytes() GB2312
06
byte b[] = " Java ".getBytes("GB2312") ;
07
OutputStream out = new FileOutputStream(new File("c:\\encoding.txt")) ;
08
out.write(b) ;
09
out.close() ;
10
}
11 }

10-10

389


byte GB2312
EncodingDemo
ISO8859-1
SetDemo.java
01 public class SetDemo
02 {
03
public static void main(String args[])
04
{
05
System.getProperties().put("file.encoding","GB2312") ;
06
}
07 }
EncodingDemo.java
EncodingDemo.java
01 public class EncodingDemo
02 {
03
public static void main(String args[]) throws Exception
04
{
05
// getBytes() ISO8859-1
06
byte b[] = " Java ".getBytes("ISO8859-1") ;
07
OutputStream out = new FileOutputStream(new File("c:\\encoding.txt")) ;
08
out.write(b) ;
09
out.close() ;
10
}
11 }

10-11

390


setDemo.java
JDK JDK

GetDemo.java
01 public class GetDemo
02 {
03
public static void main(String args[])
04
{
05
//
06
System.getProperties().list(System.out);
07
}
08 }

10-12

391

file.encoding=GBK
GBK EncodingDemo.java 6
byte b[] = " Java ".getBytes("ISO8859-1") ;

ISO8859-1
ISO8859-1
GBK

10.5

Java ObjectlnputStream ObjectOutputStream

ObjectInputStream ObjectOutputStream

Serializable Serializable

Person.java
01 import java.io.* ;
02 public class Person implements Serializable
03 {
04
private String name ;
05
private int age ;
06
public Person(String name,int age)
07
{
08
this.name = name ;
09
this.age = age ;
10
}
11
public String toString()

392

12
13
14
15 };

{
return " "+this.name+""+this.age ;
}

2 Person Serializable
ObjectOutputStream ObjectInputStream Person

SerializableDemo.java
01 import java.io.*;
02 public class SerializableDemo
03 {
04
public static void main( String args[] ) throws Exception
05
{
06
File f = new File("SerializedPerson") ;
07
serialize(f);
08
deserialize(f);
09
}
10
11
//
12
public static void serialize(File f) throws Exception
13
{
14
OutputStream outputFile = new FileOutputStream(f);
15
ObjectOutputStream cout = new ObjectOutputStream(outputFile);
16
cout.writeObject(new Person("",25));
17
cout.close();
18
}
19
20
21
22
23
24
25

//
public static void deserialize(File f) throws Exception
{
InputStream inputFile = new FileInputStream(f);
ObjectInputStream cin = new ObjectInputStream(inputFile);
Person p = (Person) cin.readObject();
System.out.println(p);

393

26
27 }

25

1 12 ~ 18 serialize()
14 15 ObjectOutputStream
FileOutputStream Person
2 20 ~ 26 deserialize()
22 23 ObjectInputStream 24
ObjectInputStream readObject()
Person 25 Person
Person toString()

transient Person.java
transient
04
05

private transient String name ;


private transient int age ;

SerializableDemo.java
null0

Person

394


1 Java IO java.io
2 Java File
3 Java
1 OutputStreaInputStream
2 WriterReader

4 Java System.in System.outSystem.in


InputStream System.in ;System.out

5 InputStreamReader OutputStreamWriter
InputStreamReader OuputStreamWriter

6 Serializable

transient

395

11
11.1

Java Applet

Applet

Applet Java Appletviewer


Java Web Applet
Applet Applet
Applet Internet www
Applet
Web Applet

Applet HTML
Applet

HelloApplet.java
01
02
03
04
05
06
07
08
09
10

package test ;
import java.awt.Graphics;
import java.applet.Applet;
public class HelloApplet extends Applet
{
public void paint(Graphics g)
{
g.drawString("Hello World!!",5,30);
}
}

//

applet java html applet


html

396

hello.htm
<HTML>
<HEAD>
<TITLE> Applet </TITLE>
<BODY>
<APPLET CODE="test.HelloApplet" WIDTH="300" HEIGHT="100">
</APPLET>
</BODY>
</HTML>
appletviewer hello.htm

11-1

11-1 applet

11.2

Applet

Applet java
Apple public Apple() Apple
Applet java.applet.Applet
Applet Applet
Applet init()start()stop() destroy() 4

397

Applet
Applet Applet
paint()
Applet init()start()stop()destroy() paint()
Appletviewer

1 public void init()


init() Applet Applet

2 public void start()


start() Applet Applet Web
Web
Applet Applet init()
start()

3 public void stop()


stop() Applet Applet Web

4 public void destroy()


destroy() Applet
Applet stop() destroy()
5 paint(Graphics g)
paint(Graphics g) Applet
g Graphics g
g drawstring()
repaint() paint()

398

paint()

HelloAppletDemo.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

package test ;
import java.awt.Graphics;
import java.applet.Applet;
public class HelloAppletDemo extends Applet
{
String mystring="";
public void paint(Graphics g)
{
g.drawString(mystring,5,30);
//
}
public void init()
{
mystring=mystring+"";
repaint();
}
public void start()
{
mystring=mystring+"";
repaint();
}
public void stop()
{
mystring=mystring+"";
repaint();
}
public void destory()
{
mystring=mystring+"";
repaint();
}
}

399

hello.htm
<HTML>
<HEAD>
<TITLE> Applet </TITLE>
<BODY>
<APPLET CODE="test.HelloAppletDemo" WIDTH="300" HEIGHT="100">
</APPLET>
</BODY>
</HTML>

11-2

11-2
applet
Applet init() start() Applet
stop() destroy()

400

11.2

HTML Applet

11.2.1

HTML

WWW HTML HyperText


Markup LanguageHTML
< >/

<HTML>
<HEAD>
<TITLE> </TITLE>
</HEAD>
<BODY> </BODY>
</HTML>

1 HTML
2 HEAD 2

3 TITLE HEAD

4 BODY

HTML

11.2.2

Applet

<APPLET> CODE
WIDTH HEIGHT<APPLET><APPLET>

401

</APPLET>
<APPLET>
1 CODEBASE = codebaseURL
Java URL
.html CODEBASE Java
.class

2 ARCHIVE = archiveList

archiveList
JAVA 2 CODEBASE Applet
ClassLoader Applet
Applet CODEBASE
archiveList codebaseURL

3 CODE = AppletFile
Applet Applet AppletFile
Java Applet .class <APPLET>
CODE OBJECT

4 OBJECT = serialiaedApplet
Applet Applet
init() start()

5 ALT=alternateText
<APPLET> Java Applet

402

6 NAME=AppletInstanceName
Applet Applet

7 WIDTH=pixels HEIGHT = pixels


Applet
Applet

8 ALIGN=alignment
Applet IMG
LEFTRIGHTTOPTEXTTOPMIDDLEABSMIDDLEBASELINE
BOTTOM ABSBOTTOM

9 VSPACE= pixels HSPACE= pixels


Applet VSPACE
HSPACE IMG VSPACE HSPACE

10<PARAM NAME=AppletAttribute 1 VALUE =value>


<PARAM NAME= AppletAttribute 2 VALUE = value>
Applet Applet
getParameter()

HTML <APPLET>
Web Applet

403

11.2.3

HTML Applet

Applet
Web HTML Applet HTML Applet
<APPLET><PARAM>Applet
String getParameter(String name) HTML <APPLET> PARAM
init()

AcceptParam.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23

package test ;
import java.awt.Graphics;
import java.applet.Applet;
public class AcceptParam extends Applet
{
String tempString,score;
public void init()
{
// web str
tempString = getParameter("str");
if(tempString.equals(""))
// ""
score = "60-70";
else if(tempString.equals(""))
// ""
score = "70-80";
else if(tempString.equals(""))
// ""
score = "80-90";
else if(tempString.equals(""))
// ""
score = "90-100";
else
score = "0-60" ;
}
public void paint(Graphics g)
{

404

24
25
26 }

//

g.drawString(score,10,25);
}

HTML HTML PARAM APPLET

appletdemo.htm
<HTML>
<HEAD> HTML Applet </HEAD>
<HR>
<BODY>
<APPLET CODE="test.AcceptParam" WIDTH=150 HEIGHT=30>
<PARAM NAME="str" VALUE="">
</APPLET>
<BR>
<APPLET CODE="test.AcceptParam" WIDTH=150 HEIGHT=30>
<PARAM NAME="str" VALUE="">
</APPLET>
<BR>
<APPLET CODE="test.AcceptParam" WIDTH=150 HEIGHT=30>
<PARAM NAME="str" VALUE="">
</APPLET>
<BR>
<APPLET CODE="test.AcceptParam" WIDTH=150 HEIGHT=30>
<PARAM NAME="str" VALUE="">
</APPLET>
<BR>
<APPLET CODE="test.AcceptParam" WIDTH=150 HEIGHT=30>
<PARAM NAME="str" VALUE="">
</APPLET>
</BODY>
</HTML>

405

11-3
java Applet
Applet Applet

406


1 Applet Applet
paint(Graphics g)
2 Applet HTML

407

12
12.1

Java

API

API (Application Programming Interface)

Java
Java
Java
Xxx Robot API Xxx API Java
Robot API Windows VC++ Robot API

Windows Windows API Windows


Windows CreateWindow API

Java API JDK Java

12.2

String StringBuffer

Java
String StringBuffer java.lang
import java.lang
String
String
StringBuffer

408

StringBuffer
StringBuffer.toString String
String
Java +
+ StringBuffer
append
String x = "a" + 4 + "c";

String x=new StringBuffer().append("a").append(4).append("c").toString();

StringBuffer
String

12.3

Java

JDK Java
Object
Integer

Java
12-1

409

12-1

int

Integer

char

Character

float

Float

double

Double

byte

Byte

long

Long

short

Short

boolean

Boolean

IntegerDemo.java
01 class IntegerDemo
02 {
03
public static void main(String[] args)
04
{
05
String a = "123" ;
06
int i = Integer.parseInt(a) ;
07
i++;
08
System.out.println(i);
09
}
10 }

124

Integer parseInt()

410

12.4
12.4.1

System Runtime
System

Java Java
System System
System
in out System
JDK
exit(int status)

CurrentTimeMillis 1970 1 1 0 0 0
long

getProperties Java
getProperties Windows
1 classpath

Java Properties
Hashtable /
getProperties Properties

SystemInfo.java
01 import java.util.*;
02 public class SystemInfo

411

03 {
04
05
06
07
08
09
10
11
12
13
14 }

public static void main(String[] args)


{
Properties sp=System.getProperties();
Enumeration e=sp.propertyNames();
while(e.hasMoreElements())
{
String key=(String)e.nextElement();
System.out.println(key+" = "+sp.getProperty(key));
}
}

12-1 SystemInfo.java
Windows Java
Java
Java -D<name>=<value>

412


java -DAuthor=lxh SystemInfo

12-2

12-2
Author = lxh Java
Author

-D Author

getProperties setProperties

413

12.4.2

Runtime

Runtime Java System


Runtime Runtime.getRuntime
Runtime
Java
exec exec Process
Java
RuntimeDemo.java
01 public class RuntimeDemo
02 {
03
public static void main(String[] args)
04
{
05
Runtime run = Runtime.getRuntime() ;
06
try
07
{
08
run.exec("notepad.exe") ;
09
}
10
catch (Exception e)
11
{
12
e.printStackTrace();
13
}
14
}
15 }
Runntime

414

12.5

Date CalendarDateFormat

Date Date()
Date Date
Date Calendar DateFormat
Calendar
Calendar.add
Calendar.get
Calendar.set
Calendar.getInstance Calendar
GregorianCalendar JDK
Calendar Calendar.getInstance
GregorianCalendar
230 xxxx xx xx
xx xx xx

CalendarDemo.java
01 import java.util.*;
02 public class CalendarDemo
03 {
04
public static void main(String[] args)
05
{
06
Calendar c1=Calendar.getInstance();
07
//
08
System.out.println(c1.get(c1.YEAR)+""+(c1.get(c1.MONTH)+1)+
09
""+c1.get(c1.DAY_OF_MONTH)+""+c1.get(c1.HOUR)+
10
":"+c1.get(c1.MINUTE)+":"+c1.get(c1.SECOND));
11
// 230
12
c1.add(c1.DAY_OF_YEAR,230);
13
14
// 230
15
System.out.println(c1.get(c1.YEAR)+""+(c1.get(c1.MONTH)+1)+

415

16
17
18
19 }

""+c1.get(c1.DAY_OF_MONTH)+""+c1.get(c1.HOUR)+
":"+c1.get(c1.MINUTE)+":"+c1.get(c1.SECOND));
}

2005 7 29 5:56:57
2006 3 16 5:56:57

Calendar Date
Date Date
Date
Date Java.text.DateFormat
java.text.SimpleDateFormat JDK DateFormat
Date
Date
2005-8-11 18:30:382005 08 11
06 30 38

DateFormatDemo.java
01
02
03
04
05
06
07
08
09
10
11
12
13

import java.text.* ;
import java.util.Date;
public class DateFormatDemo
{
public static void main(String[] args)
{
SimpleDateFormat sp1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss") ;
SimpleDateFormat sp2 =
new SimpleDateFormat("yyyy MM dd hh mm ss ") ;
try
{
Date d = sp1.parse("2005-8-11 18:30:38") ;
System.out.println(sp2.format(d)) ;

416

14
15
16
17
18
19
20

}
catch (ParseException e)
{
e.printStackTrace();
}
}
}

2005 08 11 06 30 38

SimpleDateFormat yyyy MM
dd JDK JDK
SimpleDateFormat sp1
2005-8-11 18:30:38 sp2 sdf1
Date sp2
SimpleDateFormat Date
Date

12.6

Math Random

Math
JDK
Random
Random Random

Java Random Random()


Random

Random 5 0~100

417

RandomDemo.java
01
02
03
04
05
06
07
08
09
10
11
12

import java.util.Random;
public class RandomDemo
{
public static void main(String[] args)
{
Random r = new Random() ;
for(int i=0;i<5;i++)
{
System.out.print(r.nextInt(100)+"\t") ;
}
}
}

82 83 62 39 96

12.7

Java Collection Java 2


Java DictionaryVectorStack Properties
Vector
Properties

LinkedListHashSet TreeSet

418


Algorithms Collections

Iterator iterator

enumerating the contents of a collection


Iterator Iterator

Maps

collection-view

java.util

12.7.1

collection
12-1

419

12-1

Collection

List

Collection

Set

Collection

SortedSet

Set

ComparatorIteratorListIterator
Comparator

IteratorListIterator

modifiableunmodifiable

UnsupportedOperationException

12.7.1.1

Collection
12-2 Collection
UnsupportedOperationException

ClassCastException

420

boolean add(Object obj)

objobj
trueobj
false

boolean addAll(Collection c)

c
truefalse

void clear( )

boolean contains(Object obj)

objtruefalse

boolean containsAll(Collection
c)

ctrue
false

boolean equals(Object obj)


int hashCode( )

objtruefalse

boolean isEmpty( )

truefalse

Iterator iterator( )

Boolean remove(Object obj)

obj
truefalse

Boolean removeAll(Collection
c)

c
truefalse

Boolean retainAll(Collection
c)

c
true
false

int size( )

Object[ ] toArray( )

Object[ ] toArray(Object
array[ ])

array
arrayarray

array
nullarray
ArrayStoreException
12-2 Collection

421

add( ) add( ) Object


Object
intchardouble
addAll( )
remove( )
removeAll( ) retainAll( )
clear( )
contains( )
containsAll( )
isEmpty( ) size( )

toArray( )

equals( )

equals( )
equals( )
iterator( )

12.7.1.2

List

List Collection

Collection List
12-3
UnsupportedOperationException
ClassCastException

422

12-3

List

Void add(int index,Object obj)

objindex

Boolean addAll(int
index,Collection c)

c
index

truefalse

Object get(int index)

int indexOf(Object obj)

obj
obj-1

int lastIndexOf(Object obj)

obj
obj-1

ListIterator listIterator()

ListIterator listIterator(int
index)

Object remove(int index)

index

Object set(int index,Object obj)

objindex

List subList(int start,int end)

startend1

Collection add( ) addAll( )List add(int, Object)


addAll(int, Collection) Collection
add(Object) addAll(Collection) List

get( )
set( ) indexOf( )
lastIndexOf( ) subList( )

423

12.7.1.3

Collection
add() false

12.7.1.4

SortedSet

SortedSet Set Set


SortedSet 12-4
NoSuchElementException
ClassCastException null
null NullPointerException
12-4 SortedSet

Comparator comparator( )

null

Object first( )

end
SortedSet

SortedSet headSet(Object end)

Object last( )

SortedSet subSet(Object start,


Object end)

SortedSetstart
end1

SortedSet tailSet(Object start)

SortedSet
start

424

SortedSet first()
last()
subSet()
headSet()
tailSet()

12.7.2

Collection

Collection
Collection12-5
12-5 Collection

AbstractCollection
AbstractList
AbstractSequentialList

Collection
AbstractCollectionList
AbstractList

LinkedList

AbstractSequentialList

ArrayList

AbstractList

AbstractSet

AbstractCollectionSet

HashSet

AbstractSet

TreeSet

AbstractSet

Collection Vector
Stack Hashtable
Collection

425

12.7.2.1

ArrayList

ArrayList AbstractList List ArrayList


Java

ArrayList
ArrayList ArrayList

Vector
ArrayList
ArrayList( )
ArrayList(Collection c)
ArrayList(int capacity)

c
capacity

ArrayList String
String

ArrayListDemo.java
01 import java.util.*;
02 public class ArrayListDemo
03 {
04
public static void main(String args[])
05
{
06
// ArrarList
07
ArrayList al = new ArrayList();

426

08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 }

System.out.println("a1 " + al.size());


// ArrayList
al.add("C");
// 0
al.add("A");
// 1
al.add("E");
// 2
al.add("B");
// 3
al.add("D");
// 4
al.add("F");
// 5
// A2 ArrayList 2
al.add(1, "A2");
// C A2 A E B D F
System.out.println("a1 " + al.size());
// Arraylist
System.out.println("a1 : " + al);
// ArrayList
al.remove("F");
al.remove(2);
// C A2 E B D
System.out.println("a1 : " + al.size());
System.out.println("a1 : " + al);
}

a1 0
a1 7
a1 : [C, A2, A, E, B, D, F]
a1 : 5
a1 : [C, A2, E, B, D]
a1
toString( )
toString( ) AbstractCollection

toString( )
ArrayList
ensureCapacity( ) ArrayList

427

ArrayListToArray.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22

import java.util.*;
public class ArrayListToArray
{
public static void main(String args[])
{
// ArrayList al
ArrayList al = new ArrayList();
// ArrayList
al.add(new Integer(1));
al.add(new Integer(2));
al.add(new Integer(3));
al.add(new Integer(4));
System.out.println("ArrayList " + al);
//
Object ia[] = al.toArray();
int sum = 0;
//
for (int i = 0; i < ia.length; i++)
sum += ((Integer) ia[i]).intValue();
System.out.println(" " + sum);
}
}

ArrayList [1, 2, 3, 4]
10

Integer toArray( ) Object

428

Integer

12.7.2.2

LinkedList

LinkedList AbstractSequentialList List

LinkedList( )
LinkedList(Collection c)

c
LinkedList
addFirst( ) addLast( )

void addFirst(Object obj)


void addLast(Object obj)

obj
getFirst( ) getLast( )

Object getFirst( )
Object getLast( )
removeFirst( )
removeLast( )
Object removeFirst( )
Object removeLast( )

LinkedList

429

LinkedListDemo.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

import java.util.*;
public class LinkedListDemo
{
public static void main(String args[])
{
// LinkedList
LinkedList ll = new LinkedList();
// LinkedList
ll.add("F");
ll.add("B");
ll.add("D");
ll.add("E");
ll.add("C");
//
ll.addLast("Z");
//
ll.addFirst("A");
//
ll.add(1, "A2");
System.out.println("ll " + ll);
// linkedlist
ll.remove("F");
ll.remove(2);
System.out.println(" ll " + ll);
//
ll.removeFirst();
ll.removeLast();
System.out.println("ll " + ll);
//
Object val = ll.get(2);
ll.set(2, (String) val + " Changed");
System.out.println("ll " + ll);
}
}

430


ll [A, A2, F, B, D, E, C, Z]
ll [A, A2, D, E, C, Z]
ll [A2, D, E, C]
ll [A2, D, E Changed, C]

LinkedList List add(Object)


addLast( ) add( ) add(int, Object)
add1A2
get( ) set( ) ll
get( )
set( )

12.7.2.3

HashSet

HashSetAbstractSetSet

hashing
hash code

add()
contains()remove()size( )

HashSet( )
HashSet(Collection c)
HashSet(int capacity)
HashSet(int capacity, float fillRatio)

431

capacity
0.01.0

0.75
HashSet

TreeSet

HashSetDemo.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17

import java.util.*;
public class HashSetDemo
{
public static void main(String args[])
{
// HashSet
HashSet hs = new HashSet();
// HastSet
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
System.out.println(hs);
}
}

[D, A, F, C, B, E]

432

12.7.2.4

TreeSet

TreeSet Set
TreeSet

TreeSet( )
TreeSet(Collection c)
TreeSet(Comparator comp)
TreeSet(SortedSet ss)

c
comp

ss TreeSet

TreeSetDemo.java
01 import java.util.*;
02 public class TreeSetDemo
03 {
04
public static void main(String args[])
05
{
06
// TreeSet
07
TreeSet ts = new TreeSet();
08
// TreeSet
09
ts.add("C");
10
ts.add("A");
11
ts.add("B");
12
ts.add("E");
13
ts.add("F");
14
ts.add("D");
15
System.out.println(ts);

433

16
17 }

[A, B, C, D, E, F]

TreeSet

12.7.3

iteratoriterator
Iterator ListIterator Iterator
ListIterator Iterator
Iterator 12-6 ListIterator 12-7

12-6

Iterator

boolean hasNext( )

truefalse

Object next( )

NoSuchElementException

void remove( )

next( )
remove( )IllegalStateException

434

12-7

ListIterator

void add(Object obj)

obj
next( )

boolean hasNext( )

truefalse

boolean hasPrevious( )

truefalse

Object next( )

NoSuchElementException

int nextIndex( )

Object previous( )

NoSuchElementException

int previousIndex( )

-1

void remove( )

remove( )next( )
previous( )
IllegalStateException

void set(Object obj)

objnext( )
previous( )

12.7.3.1

Collection
iterator( )

1 iterator( )
2 hasNext( ) hasNext( ) true

3 next( )

435

List ListIterator

ListIterator Iterator IteratorDemo.java


Iterator ListIterator ArrayList
ListIterator List

IteratorDemo.java
01 import java.util.* ;
02 public class IteratorDemo
03 {
04
public static void main(String args[])
05
{
06
// ArrayList
07
ArrayList al = new ArrayList();
08
// ArrayList
09
al.add("C");
10
al.add("A");
11
al.add("E");
12
al.add("B");
13
al.add("D");
14
al.add("F");
15
// iterator a1
16
System.out.print("a1 ");
17
Iterator itr = al.iterator();
18
while (itr.hasNext())
19
{
20
Object element = itr.next();
21
System.out.print(element + " ");
22
}
23
System.out.println();
24
// ListIterator
25
ListIterator litr = al.listIterator();
26
while (litr.hasNext())

436

27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50 }

{
Object element = litr.next();
// set
litr.set(element + "+");
}
System.out.print("a1 ");
itr = al.iterator();
while (itr.hasNext())
{
Object element = itr.next();
System.out.print(element + " ");
}
System.out.println();
//
System.out.print("");
// hasPreviours
while (litr.hasPrevious())
{
Object element = litr.previous();
System.out.print(element + " ");
}
System.out.println();
}

a1 C A E B D F
a1 C+ A+ E+ B+ D+ F+
F+ D+ B+ E+ A+ C+

litr
litr.hasNext( ) false
litr

437

12.7.4

Java 2 java.util map


/

null null

12.7.4.1

12-8

12-8

Map

Map.Entry

/Map

SortedMap

Map

Map
Mapkey
Map
Map12-9
NoSuchElementException
ClassCastException

438

nullNullPointerException
UnsupportedOperationException
12-9

Map

void clear()

boolean containsKey(Object k)

k
truefalse

boolean containsValue(Object v)

v
truefalse

Set entrySet()

Set
Map.Entry

Boolean equals(Object obj)

objMap
truefalse

Object get(Object k)

int hashCode()

boolean isEmpty()

true
false

Set keySet()

Set

Object put(Object k,Object v)

k
vnull

void putAll(Map m)

Object remove(Object k)

int size()

439

get()
put()put()

get()

Collection values()

entrySet( )Set
keySet( )
values()

SortedMap
SortedMapMapSortedMap
12-10
NoSuchElementException
ClassCastExceptionnull
ullPointerException
12-10 SortedMap

Comparator comparator()

null

Object firstKey()
SortedMap headMap(Object end)
Object lastKey()
SortedMap subMap(Object
start,Object end)

end

startend

440

SortedMap tailMap(Object start)

start

headMap()tailMap()subMap()
firstKey()
lastKey()

Map.Entry
Map.EntryMapentrySet( )
Set
Map.Entry12-11
12-11 Map.Entry

boolean equals(Object
obj)

obj
Map.Entrytrue

Object getKey()
Object getValue()
int hashCode()

Object setValue(Object v)

12.7.4.2

vv
ClassCastExceptionv
IllegalArgumentException
vnullnull
NullPointerException
UnsupportedOperationException

12-12
12-12

441

AbstractMap

Map

HashMap

AbstractMap

TreeMap

AbstractMap

AbstractMapWeakHashMap

HashMap
HashMapMapget( )put( )

HashMap( )
HashMap(Map m)
HashMap(int capacity)
HashMap(int capacity, float fillRatio)
m
capacity
HashSet

HashMapMapAbstractMap

HashMap

HashMapDemo.java
01 import java.util.* ;
02 public class HashMapDemo
03 {
04
public static void main(String args[])
05
{

442

06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33 }

// HashMap
HashMap hm = new HashMap();
// HashMap
hm.put("John Doe", new Double(3434.34));
hm.put("Tom Smith", new Double(123.22));
hm.put("Jane Baker", new Double(1378.00));
hm.put("Todd Hall", new Double(99.22));
hm.put("Ralph Smith", new Double(-19.08));
//
Set set = hm.entrySet();
// Iterator HashMpa
Iterator i = set.iterator();
//
while (i.hasNext())
{
// Map.Entry
Map.Entry me = (Map.Entry) i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
// John Doe 1000
double balance = ((Double) hm.get("John Doe")).doubleValue();
//
hm.put("John Doe", new Double(balance + 1000));
System.out.println("John Doe's " + hm.get("John Doe"));
}

Todd Hall: 99.22


Ralph Smith: -19.08
Tom Smith: 123.22
John Doe: 3434.34
Jane Baker: 1378.0

443

John Doe's 4434.34

entrySet( )
Map.Entry getKey( ) getValue( )
John Doe put( )
John Doe John Doe

TreeMap
TreeMap Map TreeMap
/

TreeMap
TreeMap( )
TreeMap(Comparator comp)
TreeMap(Map m)
TreeMap(SortedMap sm)

Comparator comp
Comparators m
sm
sm
TreeMap SortedMap AbstractMap

TreeMap
TreeMapDemo.java
01 import java.util.* ;
02 public class TreeMapDemo
03 {

444

04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21 }

public static void main(String args[])


{
// TreeMap
TreeMap tm = new TreeMap();
// TreeMap
tm.put(new Integer(10000 - 2000), "");
tm.put(new Integer(10000 - 1500), "");
tm.put(new Integer(10000 - 2500), "");
tm.put(new Integer(10000 - 5000), "");
Collection col = tm.values();
Iterator i = col.iterator();
System.out.println("");
while (i.hasNext())
{
System.out.println(i.next());
}
}

12.7.4.3

TreeSet TreeMap
Java

445

A B 1 2

Comparator

Comparator compare( ) equals( ) compare( )

int compare(Object obj1, Object obj2)

obj1 obj2 0 obj1


obj2
ClassCastException compare( )

equals( )
boolean equals(Object obj)

obj obj Comparator


true false equals( )

compare( )

ComparatorDemo.java
01 import java.util.*;
02 class MyComp implements Comparator
03 {
04
public int compare(Object o1, Object o2)
05
{
06
String aStr, bStr;
07
aStr = (String)o1;
08
bStr = (String)o2;
09
return bStr.compareTo(aStr);
10
}
11 }

446

12 public class ComparatorDemo


13 {
14
public static void main(String args[])
15
{
16
// TreeSet
17
TreeSet ts = new TreeSet(new MyComp());
18
// TreeSet
19
ts.add("C");
20
ts.add("A");
21
ts.add("B");
22
ts.add("E");
23
ts.add("F");
24
ts.add("D");
25
// Iterator
26
Iterator i = ts.iterator();
27
//
28
while (i.hasNext())
29
{
30
Object element = i.next();
31
System.out.print(element + " ");
32
}
33
}
34 }

FEDCBA

Comparator compare( ) MyComp


equals( ) compare( )
String compareTo( ) bStr aStr
compareTo( )
TreeMap

447

TreeMapDemo2.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

import java.util.* ;
class Employee implements Comparator
{
public int compare(Object a, Object b)
{
int k;
String aStr, bStr;
aStr = (String) a;
bStr = (String) b;
k = aStr.compareTo(bStr);
if(k==0)
return aStr.compareTo(bStr);
else
return k;
}
}
public class TreeMapDemo2
{
public static void main(String args[])
{
// TreeMap
TreeMap tm = new TreeMap(new Employee());
// Map
tm.put("Z", new Double(3534.34));
tm.put("L", new Double(126.22));
tm.put("W", new Double(1578.40));
tm.put("Z", new Double(99.62));
tm.put("S", new Double(-29.08));
Set set = tm.entrySet();
Iterator itr = set.iterator();
while(itr.hasNext())
{
Map.Entry me = (Map.Entry)itr.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}

448

38
39
40
41
42
43 }

System.out.println();
double balance = ((Double)tm.get("Z")).doubleValue();
tm.put("Z", new Double(balance + 2000));
System.out.println(" " + tm.get("Z"));
}

L: 126.22
S: -29.08
W: 1578.4
Z: 3534.34
Z: 99.62

5534.34

12.7.5

java.util
Java 2

Java 2 API

Collections

java.util
Dictionary

Hashtable

Properties

449

Stack

Vector

Enumeration
Enumeration

12.7.5.1

Enumeration

Enumeration
Iterator Enumeration
Vector
Properties API

Enumeration
boolean hasMoreElements( )
Object nextElement( )

hasMoreElements( ) true
falsenextElement( )
Object nextElement( )

12.7.5.2

Vector

Vector ArrayList Vector


Java 2
Vector AbstractList List

Vector
Vector( )
Vector(int size)
Vector(int size, int incr)
Vector(Collection c)

450

10
size size
incr
c Java 2

Vector
int capacityIncrement;
int elementCount;
Object elementData[ ];
capacityIncrement
elementCount elementData
List Vector
12-13
12-13 Vector

final void
addElement(Object element)

element

int capacity()

Object clone()

Boolean contains(Object
element)

elementtrue
false

void copyInto(Object
array[])

array

Object elementAt(int index)

index

Enumeration elements()

451

Object firstElement()

int indexOf(Object element)

element
-1

int indexOf(Object
element,int start)

elementstart

-1

void
insertElementAt(Object
element,int index)
boolean isEmpty()
Object lastElement()

indexelement
true
false

int lastIndexOf(Object
element)

element
-1

int lastIndexOf(Object
element,int start)

elementstart

-1

void removeAllElements()
boolean
removeElement(Object
element)

0
element

true
false

void removeElementAt(int
index)

index

void setElementAt(Object
element,int index)

indexelement

void setSize(int size)

size

null

int size()

String toString()

void trimToSize()

Vector List ArrayList


Vector
addElement( ) elementAt( )

452

firstElement( ) lastElement( )
indexOf( ) lastIndexOf( )
removeElement( ) removeElementAt( )
Vector
Enumeration

VectorDemo.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19

import java.util.* ;
public class VectorDemo
{
public static void main(String[] args)
{
Vector v = new Vector() ;
v.add("A") ;
v.add("B") ;
v.add("C") ;
v.add("D") ;
v.add("E") ;
v.add("F") ;
Enumeration e = v.elements() ;
while(e.hasMoreElements())
{
System.out.print(e.nextElement()+"\t") ;
}
}
}

Java 2 Vector

Iterator i = v.iterator() ;

453

while(i.hasNext())
{
System.out.print(i.next()+"\t") ;
}

12.7.5.3

Stack

Stack Vector Stack


Stack Vector
12-14
12-14 Stack

boolean empty()

true
false

Object peek()

Object pop()

Object push(Object
element)

elementelement

int search(Object element)

element
-1push()
pop()
pop()
EmptyStackExceptionpeek()
empty()
true

search()

454

Integer

StackDemo.java
01 import java.util.* ;
02 public class StackDemo
03 {
04
static void showpush(Stack st, int a)
05
{
06
st.push(new Integer(a));
07
System.out.println("(" + a + ")");
08
System.out.println("Stack: " + st);
09
}
10
11
static void showpop(Stack st)
12
{
13
System.out.print(" -> ");
14
Integer a = (Integer) st.pop();
15
System.out.println(a);
16
System.out.println("Stack: " + st);
17
}
18
19
public static void main(String args[])
20
{
21
Stack st = new Stack();
22
System.out.println("Stack: " + st);
23
showpush(st, 42);
24
showpush(st, 66);
25
showpush(st, 99);
26
showpop(st);
27
showpop(st);
28
showpop(st);
29
// EmptyStackException
30
try {
31
showpop(st);
32
} catch (EmptyStackException e) {
33
System.out.println("");

455

34
35
36 }

}
}

EmptyStackException

Stack: []
(42)
Stack: [42]
(66)
Stack: [42, 66]
(99)
Stack: [42, 66, 99]
-> 99
Stack: [42, 66]
-> 66
Stack: [42]
-> 42
Stack: []
->

12.7.5.4

Dictionary

Dictionary/
MapDictionary

/ Java 2 Dictionary
Map Dictionary

Dictionary 12-15

456

12-15 Dictionary

Enumeration elements()

Object get(Object key)

keykey

boolean isEmpty()

true
false

Enumeration keys()

Object put(Object key,Object


value)

key
nullkey
key

Object remove(Object key)

keykeykey
null

int size()

put()
get()
keys() elements()
Enumeration

size()

/
isEmpty() true
remove()/

Dictionary Map /

12.7.5.5

Hashtable

Hashtablejava.utilDictionary
Java 2HashtableMap
HashtableHashMap
HashMapHashtable/Hashtable

457


ObjecthashCode()equals()
hashCode()equals()
JavahashCode()Hashtable
StringStringhashCode()equals()
Hashtable
Hashtable( )
Hashtable(int size)
Hashtable(int size, float fillRatio)
Hashtable(Map m)

sizesize
fillRatio0.01.0

0.75
mm
0.75Java 2
HashtableMapHashtable
12-16

12-16 Hashtable

void clear()
Object clone()
boolean contains(Object value)

value
true
false

458

boolean containsKey(Object
key)

key
true
false

boolean containsValue(Object
value)

value
truefalse
Java 2
Map

Enumeration elements()

Object get(Object key)

keykey

boolean isEmpty()

true
false

Enumeration keys()

Object put(Object key,Object


value)

key
nullkey
key

void rehash()

Object remove(Object key)

keykey
key

int size()
String toString()

HashtableDemo.java
01 import java.util.* ;
02 public class HashtableDemo
03 {
04
public static void main(String[] args)
05
{
06
Hashtable numbers = new Hashtable();
07
numbers.put("one", new Integer(1));
08
numbers.put("two", new Integer(2));
09
numbers.put("three", new Integer(3));
10
Integer n = (Integer) numbers.get("two");
11
if (n != null)
12
{
13
System.out.println("two = " + n);
14
}
15
}

459

16 }

two = 2

12.7.5.5

Properties

PropertiesHashtable
StringPropertiesJava
System.getProperties( )
Properties
Properties defaults;

Properties
Properties
Properties( )
Properties(Properties propDefault)

Properties
propDefault
PropertiesHashtableProperties
12-16Propertiessave( )
store( )
12-16 Properties

String getProperty(String key)

keykey

null

460

String getProperty(String key,String


defaultProperty)

keykey

defaultProperty

void list(PrintStream streamOut)

streamOut

void list(PrintWriter streamOut)

streamOut

void load(InputStream streamIn)


throws IOException

streamIn
Enumeration propertyNames()

Object setProperty(String key,String


value)

valuekeykey
null
Java
2

void store(OutputStream
streamOut,String description)

description
streamOut
Java 2

Properties

getProperty( )
getProperty(namedefault value)name
defaultvalue Properties
Properties
Properties getProperty(foo)fooJava
Properties foo
Properties

PropertiesDemo.java
01 import java.util.*;
02 public class PropertiesDemo
03 {
04
public static void main(String args[])

461

05 {
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 }

Properties capitals = new Properties();


Set states;
String str;
capitals.put("", "");
capitals.put("", "");
capitals.put("", "");
capitals.put("", "");
capitals.put("", "");
//
states = capitals.keySet();
Iterator itr = states.iterator();
while (itr.hasNext())
{
str = (String) itr.next();
System.out.println("" + str + " "+ capitals.getProperty(str) + ".");
}
System.out.println();
//
str = capitals.getProperty("", "");
System.out.println("" + str + ".");
}

.
.
.
.
.
.
getProperty( )

462

Properties

12.7.5.6

Properties store() load()

Properties store() load()


Properties
Properties

PropertiesFile.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22

import java.io.* ;
import java.util.* ;
public class PropertiesFile
{
public static void main(String[] args)
{
Properties settings = new Properties();
try {
settings.load(new FileInputStream("c:\\count.txt"));
} catch (Exception e) {
settings.setProperty("count", new Integer(0).toString());
}
int c = Integer.parseInt(settings.getProperty("count")) + 1;
System.out.println("" + c + "");
settings.put("count", new Integer(c).toString());
try {
settings.store(new FileOutputStream("c:\\count.txt"), "PropertiesFile use it .");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}

463


12-3

12-3 PropertiesFile

0 Properties store()

HashTable putget Properties


setPropertygetProperty

TreeMap
TreeSet

464

12.8

hashCode()

Object equals()toString()
equals() Object hashCode()
hashCode()

HashCodeDemo.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

import java.util.* ;
class Person
{
private String name ;
private int age ;
Person(String name,int age)
{
this.name = name ;
this.age = age ;
}
public String toString()
{
return ""+this.name+""+this.age ;
}
}
public class HashCodeDemo
{
public static void main(String args[])
{
HashMap hm = new HashMap() ;
hm.put(new Person("",20),"") ;
System.out.println(hm.get(new Person("",20))) ;
}
}

null

465

null
hashCode()

// true
public boolean equals(Object obj)
{
return true ;
}
public int hashCode()
{
return 20 ;
}
HashCodeDemo.java

hashCode()
Person

12.9

clone Java clone


java.lang.Cloneable clone Object clone
Cloneable
clone() CloneNotSupportedException

1 Cloneable
clone
Cloneable clone Clone
clone
Object clone()
2 Object clone()
Object clone() jdk JDK

466

Object clone()
protected native Object clone() throws CloneNotSupportedException;
clone() protected public
clone() clone()
public protected

CloneDemo.java
01 class Employee implements Cloneable
02 {
03
private String name;
04
private int age;
05
public Employee(String name, int age)
06
{
07
this.name = name;
08
this.age = age;
09
}
10
public Object clone() throws CloneNotSupportedException
11
{
12
return super.clone();
13
}
14
public String toString()
15
{
16
return "" + this.name + "" + this.age;
17
}
18
public int getAge()
19
{
20
return age;
21
}
22
public void setAge(int age)
23
{
24
this.age = age;
25
}
26
public String getName()
27
{
28
return name;

467

29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53

}
public void setName(String name)
{
this.name = name;
}
}
public class CloneDemo
{
public static void main(String args[])
{
Employee e1 = new Employee("", 21);
Employee e2 = null;
try {
e2 = (Employee) e1.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
e2.setName("");
e2.setAge(30);
System.out.println("" + (e1 == e2));
System.out.println(e1);
System.out.println(e2);
}
}

false
21
30

468


1 String StringBuffer StringBuffer
String StringBuffer String
2 JAVA ArrayListVector ArrayList
Vector
3 JAVA HashMapHashtable
Iterator HashMap Hashtable
4 JAVA Iterator ArrayList Vector Vector
Enumeration
5 Cloneable

469

Java
13-1Socket
Socket
Java Socket
Socket
Java Socket
Java Socket
getInputStream() getOutputStream()
getInputStream() Socket getInputStream()
getOutputStream()
Socket getOutputStream()

Sockets sockets

sockets

socket socket.

TCP socket
socket sockets

470

---

13-2Socket
Java

hello
world!
HelloServer.java
01 import java.io.*;
02 import java.net.*;
03 public class HelloServer
04 {
05
public static void main(String[] args) throws IOException
06
{
07
ServerSocket serversocket=null;
08
PrintWriter out=null;
09
try
10
{
11
// Socket
12
serversocket=new ServerSocket(9999);
13
}
14
catch(IOException e)
15
{
16
System.err.println("Could not listen on port:9999.");
17
System.exit(1);
18
}
19
Socket clientsocket=null;
20
try
21
{
22
// accept()
23
clientsocket=serversocket.accept();
24
}

471

25
26
27
28
29
30
31
32
33
34
35 }

catch(IOException e)
{
System.err.println("Accept failed.");
System.exit(1);
}
out=new PrintWriter(clientsocket.getOutputStream(),true);
out.println("hello world!");
clientsocket.close();
serversocket.close();
}

13-1 HelloServer

1 7 ServerSocket
2 8 PrintWriter
3 9 ~ 18 ServerSocket 9999
4 19 Socket clientsocket Socket

472

5 20 ~29 ServerSocket accept() Socket


Socket
6 30 Socket PrintWriter out

7 31 println()
8 32 Socket
9 33 Socket
java HelloServer

HelloClient.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22

import java.io.*;
import java.net.*;
public class HelloClient
{
public static void main(String[] args) throws IOException
{
Socket hellosocket=null;
BufferedReader in=null;
// socket
try
{
hellosocket=new Socket("localhost",9999);
in=new BufferedReader(new InputStreamReader(hellosocket.getInputStream()));
}
catch(UnknownHostException e)
{
System.err.println("Don't know about host:localhost!");
System.exit(1);
}
catch(IOException e)
{
System.err.println("Couldn't get I/O for the connection.");

473

23
24
25
26
27
28
29 }

System.exit(1);
}
System.out.println(in.readLine());
in.close();
hellosocket.close();
}

13-2 HelloClient

1 7 Socket hellosocket
2 8 BufferedReader in

3 12 hellosocket 9999
4 13 hellosocket BufferedReader
5 25
6 26 BufferedReader
7 27 Socket

474

Socket Echo
Echo
EchoServer.java
01 import java.io.*;
02 import java.net.*;
03 public class EchoServer
04 {
05
public static void main(String[] args) throws IOException
06
{
07
ServerSocket serverSocket = null;
08
PrintWriter out = null;
09
BufferedReader in = null;
10
try
11
{
12
//
13
serverSocket = new ServerSocket(1111);
14
}
15
catch (IOException e)
16
{
17
System.err.println("Could not listen on port: 1111.");
18
System.exit(1);
19
}
20
Socket incoming = null;
21
while(true)
22
{
23
incoming = serverSocket.accept();
24
out = new PrintWriter(incoming.getOutputStream(), true);
25 // InputStreamReader
26
in = new BufferedReader(new InputStreamReader(incoming.getInputStream()));
27
//
28
out.println("Hello! . . . ");
29
out.println("Enter BYE to exit");
30
out.flush();
31
//
32
while(true)

475

33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59 }

{
//
String str = in.readLine();
// null
if(str == null)
{
//
break;
}
else
{
// Echo
out.println("Echo: "+str);
out.flush();
// equalsIgnoreCase()
if(str.trim().equalsIgnoreCase("BYE"))
break;
}
}
//
out.close();
in.close();
incoming.close();
serverSocket.close();
}
}

Echo
EchoClient.java
01 import java.io.*;
02 import java.net.*;
03 //
04 public class EchoClient
05 {
06
public static void main(String[] args) throws IOException

476

07
{
08
Socket echoSocket = null;
09
PrintWriter out = null;
10
BufferedReader in = null;
11
try
12
{
13
echoSocket = new Socket ( "localhost", 1111);
14
out = new PrintWriter(echoSocket.getOutputStream(), true);
15
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
16
}
17
catch (UnknownHostException e)
18
{
19
System.err.println("Don't know about host: localhost.");
20
System.exit(1);
21
}
22
System.out.println(in.readLine());
23
System.out.println(in.readLine());
24 BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
25
String userInput;
26 // Socket Socket
27
while ((userInput = stdIn.readLine()) != null)
28
{
29
out.println(userInput);
30
System.out.println(in.readLine());
31
}
32
out.close();
33
in.close();
34
echoSocket.close();
35
}
36 }

477

13-3 Echo

"bye"

Socket

EchoServer
EchoMultiServerThread.java
01 import java.net.*;
02 import java.io.*;
03 public class EchoMultiServerThread extends Thread
04 {
05
private Socket socket = null;
06
public EchoMultiServerThread(Socket socket)
07
{
08
super("EchoMultiServerThread");
09
// socket
10
this.socket = socket;
11
}
12
public void run()
13
{

478

14
try
15
{
16
PrintWriter out = null;
17
BufferedReader in = null;
18
out = new PrintWriter(socket.getOutputStream(), true);
19 in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
20
out.println("Hello! . . . ");
21
out.println("Enter BYE to exit");
22
out.flush();
23
while(true)
24
{
25
String str = in.readLine();
26
if(str == null)
27
{
28
break;
29
}
30
else
31
{
32
out.println("Echo: "+str);
33
out.flush();
34
if(str.trim().equalsIgnoreCase("BYE"))
35
break;
36
}
37
}
38
out.close();
39
in.close();
40
socket.close();
41
}
42
catch (IOException e)
43
{
44
e.printStackTrace();
45
}
46
}
37 }

479

EchoServerThread.java
01 import java.io.*;
02 import java.net.*;
03 //
04 public class EchoServerThread
05 {
06
public static void main(String[] args) throws IOException
07
{
08
// serverSocket
09
ServerSocket serverSocket = null;
10
//
11
boolean listening = true;
12
try
13
{
14
serverSocket = new ServerSocket(1111);
15
}
16
catch (IOException e)
17
{
18
System.err.println("Could not listen on port: 1111.");
19
System.exit(1);
20
}
21
//
22
while(listening)
23
{
24
// socket socket
25
new EchoMultiServerThread(serverSocket.accept()).start();
26
}
27
// serverSocket
28
// false
29
serverSocket.close();
30
}
31 }

Socket

480

13-3DatagramSocket
API
datagram socket UDP

IP IP
60000 13-4 IP

13-4
TCP UDP
UDP
UDP
UDP UDP

DatagramPacket DatagramSocket
DatagramPacket DatagramSocket
java.net

481

DatagramPacket
DatagramPacket

DatagramPacket
byte [] buffer int lengthbuffer
length
DatagramPacket(byte [] buffer, int length)

setAddress(InetAddress addr) setPort(int port)

DatagramSocket
DatagramSocket

DatagramSocket() DatagramSocket(int port)

SocketException DatagramSocket
send(DatagramPacket dgp) receive(DatagramPacket dgp)

UdpReceive.java
01 import java.net.*;
02 import java.io.*;
03
04 public class UdpReceive
05 {
06
public static void main(String[] args)
07
{
08
DatagramSocket ds = null;
09
byte[] buf = new byte[1024];
10
DatagramPacket dp = null;

482

11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30 }

try {
ds = new DatagramSocket(9000);
} catch (SocketException ex) {
}
// DatagramPacket byte
dp = new DatagramPacket(buf, 1024);
try {
ds.receive(dp);
} catch (IOException ex1) {
}
/*
* public String(byte[] bytes,int offset,int length)
* byte
*/
String str = new String(dp.getData(), 0, dp.getLength()) + " from "
+ dp.getAddress().getHostAddress() + " : " + dp.getPort();
System.out.println(str);
ds.close();
}

UdpSend.java
01 import java.net.*;
02 import java.io.*;
03 public class UdpSend
04 {
05
public static void main(String[] args)
06
{
07
// UDP java.net.DatagramSocket
08
DatagramSocket ds = null;
09
DatagramPacket dp = null;
10
try {
11
ds = new DatagramSocket(3000);
12
}
13
catch (SocketException ex) {
14
}
15
String str = "hello world ";

483

16
17
18
19
20
21
22
23
24
25
26
27
28 }

try {
dp = new DatagramPacket(str.getBytes(), str.length(), InetAddress
.getByName("localhost"), 9000);
// InetAddress.getByName() InetAddress
} catch (UnknownHostException ex1) {
}
try {
ds.send(dp);
} catch (IOException ex2) {
}
ds.close();
}

13-5 UDP
UDP

UDP UDP UDP

UDP DatagramSocket.receive
receive
receive

484


1 Java TCPUDP
2 TCP Socket ServerSocket
3 UDP DatagramPacket DatagramSocket

485

Java

486

JAVA
3-1
;

3-2 if
if ()

3-3 if
if ()
{
1
2

3
}
3-4 ifelse
if ()
{
1
}
else
{
2
}

3-5 ifelse
1 2

3-6 ifelse

487

if ()
x = 1
else
x = 2

488

3-7 ifelse if else


if ( 1)
{
1
}
else if ( 2)
{
2
}
.
// else if()
else
{
3
}

3-8

switch

switch()
{
case 1 1
break
case 2 2
break
.
case n n
break
default
}

3-9

while

while ()
{
1
2

n
}

489

490

3-10 dowhile
do
{
1
2
.
n
}while ();

3-11 for
for ()
{
1
.
n
}

3-12 break
for ()
{
1
2

break

// break
n
}

3-13 continue
for ()
{
1
2

491

continue

// continue

n
}
.

492

4-1

[]
//
new [] ;
//

4-2
[] = new []

4-3
.length

4-4
[] = { 0 1 n}

4-5
[][]
= new [][]

4-6
[][] = new [][]

4-7
= {{ 0 },
{ 1 }

{ n },
};

4-8
.length
[].length

//
//

493

4-9
1 2
{

return
}
5-1
class
{

1 2
{

return
}
}

5-2
= new () ;

5-3
.
. ()

5-4
private
private

5-5

494

class
{
1 1 2 2
{

//
}
}

5-6
class
{
//
class
{
//
}
}

6-1
class
{
}
class extends
{
}

// CCircle

// extends

6-2 super
super. ;
super.() ;

6-3
class Super
{

495

1 1
{}
}
class Sub extends Super
{
1 1
{}
}

496

6-4
abstract class //
{


{

}
abstract

//
}

6-5
interface
//
{
final =

//

abstract
//
}

6-6
class implements A, B
{

//

6-7
interface extends 1 2
{

497

7-1
try
{

try

}
catch( )
{

}
finally
{

}

catch

finally

7-2
throw

7-3
throws 1 2

7-4
class extends Exception
{

}

8-1 package
package package ;

8-2 package
import package .

498

10-1
import java.io.*;
public class class_name
//
{
public static void main(String args[]) throws IOException
{
BufferedReader buf; // buf BufferedReader
String str;
// str String
... ...
buf=new BufferedReader(new InputStreamReader(System.in));
buf
str=buf.readLine();
... ...

// buf

}
}

499

//

You might also like