Вы находитесь на странице: 1из 566

Java

27 2003
:
( Sun ) <vyazovick@itc.mipt.ru>
( Sun ) < gene@itc.mipt.ru>
Copyright 2003 Sun , , .

Rendered by www.RenderX.com

ii

,
Java
,
Sun Microsystems () .
Java
. Sun Microsystems ,
Java , .

Java , Sun
.
Java
Sun Microsystems
.

Java

Rendered by www.RenderX.com

iii

1. Java? .................................................................. 1
1. Java? .............................................................................................................. 1
2. Java ................................................................................................. 2
2.1. Sun Microsystems .................................................................. 2
2.2. Green .........................................................................................................4
2.3. FirstPerson.............................................................................................6
2.4. World Wide Web..................................................................................................... 7
2.5. Oak ................................................................................................. 9
2.6. Java .............................................................................................10
3. Java .................................................................................................11
3.1. ............................................................................................................. 11
3.2. ......................................................................................... 14
3.3. Java ................................................................................................. 17
4. .................................................................................................................. 26
5. ...................................................................................................26

Java

Rendered by www.RenderX.com

iv

Java

Rendered by www.RenderX.com

. 1 30

1. Java?
.
.
1. Java? ..............................................................................................................1
2. Java .................................................................................................2
2.1. Sun Microsystems ........................................................................ 2
2.2. Green .............................................................................................................. 4
2.3. FirstPerson.................................................................................................. 6
2.4. World Wide Web........................................................................................................... 7
2.5. Oak ....................................................................................................... 9
2.6. Java .................................................................................................. 10

3. Java ................................................................................................ 11
3.1. ................................................................................................................... 11
3.2. ...............................................................................................14
3.3. Java ....................................................................................................... 17

4. ................................................................................................................. 26
5. .................................................................................................. 26

1. Java?
Java ?
, ?
Java - ,
,
- (-). Java -
( , ..).
, ++
garbage collector' - "" ( ,
). , Java
, - ,
, HTML-.
, ,
, - ,
Java

Rendered by www.RenderX.com

. 2 30

Java

- Java . ,
, ,
, .
. -,
Java -
" ". -, JavaOne,
1996 , 10.000
(
5.000). Sun,
Java , Java Developer Connection
1996 , 100.000 , 2000
- 1.5 . Java
3 .
5 , 1.0 1995 1.4
2002 . 1.5 2003 .

- Java http://java.sun.com/. Java - JDK 1.1 (
Java)
220.000 . 1.4 2 5
.
Java ,
. " " IBM, Macintosh
Apple, Oracle,
Sun - Microsoft - Java 1996 .
,
Java, , ,
, ,
.

2. Java
Java, ,
Oak (), 1990
Sun. ,
.

2.1. Sun Microsystems


, 1990 ,
WWW (World Wide Web - " ") .
.
, Sun Microsystems,
,
"" -
Sun " ,
"" " [3].
Java

Rendered by www.RenderX.com

Sun Microsystems

. 3 30

(Scott McNealy), , CEO


( ) Sun, , 25-
(Patrick Naughton),
3 , NeXT. ,
- " ".
, . ,
, , Sun . ,
, ,
.
, .
NeWS,
,
NeXTstep. :
-,
Sun ;
, (
, ,
); , Window Systems
Group ( , ).
, , ,
NeXT - .
.
,
. , , ,
, , .
(Bill Joy) (James Gosling). -
- Sun,
UNIX . Sun 1984 (
IBM) ,
EMACS C.
.
, - ,
. , 4.30
, . : , ;
- ;
,
, - .
, (John Gage),
Sun, .
,
: Sun,
; ,
Sun;
Sun;
.
Java

Rendered by www.RenderX.com

. 4 30

Java

2.2. Green
5 1990 , , NeXT, Sun
.
. - " - ". 1 1991
, (Mike Sheridan)
, Green.
- ,
(
), .
,
, .
Sun 1991 , ,
,
, , , !
,
- , .
,
, ,
.
, ,
-.
1991 Sun
.
, Nintendo, ,
, ,
, .
,
, ,
42 . , ,
, ,
- 50- .
,
. ,
,
, , .
,
, ,
, , , ,
, ,
.
++,
, .
, . ++ -
, .
,
. 1991 ,
Java

Rendered by www.RenderX.com

Green

. 5 30

14 , C++.
, , ,
. - Oak ().
, Java.
, ,
, .
,
.
, ,
, ,
, ( !) .
,
" ". - ,
,
. ,
.
Sun.
- *7, Star7 (
,
,
).
(Duke),
. Java,
, , , .
, , ,
. , .
1991 .
Sun . ,
.
, , - "1st Person" (
" ").
, 4 1992 Star7 .
5" (16 ) .
, .
- !
, "" , ,
- .
, ""
, .
! ,
(PDA), Newton, ,
. 286i 386i Intel (486i ,
) MS DOS,
.
Sun ,
, HP, IBM Microsoft.
Java

Rendered by www.RenderX.com

. 6 30

Java

. - Oak
,
. , ,
,
.
Oak, , , , ,
. , ,
, ,
. , ,
, Oak , ,
, , ,
.

2.3. FirstPerson
-, Mitsubishi Electric, France Telecom, Dolby Labs,
, .
- "Beyond the Green Door" (" "),
Sun
Oak . 1 1992 FirstPerson,
(Wayne Rosing), Sun Labs. ,
14 60 .
, (, ,
) $50.
,
.

, ,
. , 1993 Time Warner

, FirstPerson .
- (James Clark), Silicon
Graphics Inc., ,
Oak. , Time Warner SGI ,
Netscape, Java.
3DO.
10 , Oak ,
, 3DO ,
.
, 1994 ,
. , .
FirstPerson , ,
. Sun
-, .

Java

Rendered by www.RenderX.com

World Wide Web

. 7 30

2.4. World Wide Web



. 1993
(Marc Andreessen) (Eric Bina),
(National Center for Supercomputing Applications, NCSA)
,
("") Mosaic 1.0 WWW. Internet
20 , (FTP, telnet .)
,
. Mosaic
(HyperText Markup Language, HTML), 1991
(CERN) .
, -
,
, ,
. ,

, HTML
- (World Wide Web, WWW).
-
.

, .
WWW ,
. , ,
,
- , ,
.
, Sun .
Sun Mosaic ! ,
50%
Sun.
- FirstPerson ,
.
,
, .
Oak, ,
CD-ROM , ,
. ,
, Oak
. Mosaic
.
Sun (
-
Sun). - FirstPerson
Sun Interactive,
Java

Rendered by www.RenderX.com

. 8 30

Java

- Oak.
, ,
Java.
FirstPerson , ,
, Oak,
WWW. ,
UNIX ,
, .
WWW,
Netscape ,
.
Sun,
Oak (,
"Liveoak"). -
Oak .
, "" ,
Oak .
, .
.
, Cobol. Fortran IBM,
. Basic -
Microsoft - -
. ++
, Mac OS Windows. Oak ,
.
, 1994 WWW (,
), -
, .
- ,
HTML-, .
- CGI (Common Gateway
Interface).
.
(, ,
), ,
, .
GIF- .

,
, .
, - ,
(enterprise) ,
. - ,
, ,
,
.
( " ", ,
Java

Rendered by www.RenderX.com

Oak

. 9 30

, , ).
, ,
. , ,
.
.
-
. -,
- ,

. -, .
, .

, - . ,
, , ,
CD-ROM'. ,
.
Oak, ,
, , WWW .
, ,
Green.

2.5. Oak
Oak - ,
. ""
,
.
WebRunner. ,
. , 1994 WebRunner
Sun. , Oak
, (applets),
.
,
- .
WebRunner, , ,
Mosaic.
.
, ! , ,
, ,
.
. .
, .
, ,
.
Java Development Kit . ,
Java

Rendered by www.RenderX.com

. 10 30

Java

, , Oak WebRunner
,
, .
, 1995 , ,
, . Oak
Java, WebRunner HotJava.
, . , Java -
( ), . ,
HotJava ( Java).
( Java Beans , Java JAR ..) , " ".
, , ,
( , ,
, - Neon, Lyric, Pepper Silk).
Java, HotJava
. ,
-
-. ,
, ,
. 1994
Sun. 1995 ,
, -, , - Oak WebRunner
.
, , -
. . ,
10.000, " ".
10.000 , .
, ,
- .
, , .
, .
, , 2-3
.
Sun , Java
.
23 1995 Sun Jose Mercury News
,
http://java.sun.com/,
Java.

2.6. Java
, .
Java,
, SunWorld. ,

Java

Rendered by www.RenderX.com

. 11 30

,
- UNIX-. , .
4 , , Sun
. - Netscape, 1994
( Oak ,
Time Warner) ( NCSA Mosaic).
, 1994
Netscape Navigator,
, 75% .
23 1995 Java HotJava Sun [14],
, Netscape Navigator
2.0 [15]. , , Java
WWW, HTML.
.
Java .

3. Java
, Java ,
, Sun
.

3.1.
, .
,
. ,
. ,
.
Java - ,
- -
, (
GIF, - Macromedia Flash);
; , , ,
.
Java - , HTML.
,
. Java Development Kit (
Java) ,
. , .
, , , .
, , ,
.
" " HTML
. ,
Java

Rendered by www.RenderX.com

. 12 30

Java

, . ,
, ,
. ,
, , ,
.
, ,
- -
. - "" .
,
, , ,
.
Java, , HotJava,
. Netscape Navigator,
2.0, Java. , ,
- Microsoft Internet Explorer.
Microsoft,
, ( )
Sun, IBM, Netscape .
Microsoft Windows
(MS Office), ,
Internet. 1995
"" Netscape WWW,
. Netscape
Sun, Microsoft .
Internet Explorer 2.0 , ,
- Netscape Navigator. ,
IE 3.0 , NN 2.0. 7
1995 Microsoft Java, 1996
.
, ,
.
.
, Microsoft .
Netscape Navigator 3.x , Netscape 4.x
Internet Explorer 4.x. NN 5.x , NN 6.x
"". 7.0,
, Internet Explorer 5.0, 5.5 6.0
95% .
, Microsoft , Netscape
. . ,
Microsoft , W3C,
HTML 3. Netscape
, HTML,
- .
Microsoft, , ,
, Netscape Navigator,
Java

Rendered by www.RenderX.com

. 13 30

. , ,
W3C , Navigator .
, NN ( )
, IE Windows,
( , , ).
Netscape ?
(, )
NCSA Mosaic. HTML ,
, Navigator',
.
Mosaic,
Netscape.
Netscape Navigator .
, ,
Microsoft, , ,
" ", HTML
, .
HotJava, , . Sun
- HTML.
, HotJava
. 3.0.
, , - Java Script,
Java, ,
. , .
4 1995 Netscape Sun " "
(scripting language) Java Script. - , .
Java Script HTML (
.js). ,
. , Java
Script HTML, - Java.
Java -,
.
Java Script Java:
. Java Script Visual Basic -
, .
-. Java Script . ,

, . ,
, HTML - .
.
.
, Java Script
-.
Java

Rendered by www.RenderX.com

. 14 30

Java

Java Script Java . ,


.
Java Script - (
), ,
.
. Sun
Netscape . Netscape Navigator 2.0 . ,
Java Script , Java,
, " Java". ,
Netscape.
, Java Java Script -
, - . Java
- (),
, Java - .
Java Script, ,
HTML. , ,
, 3D
( , ),
.
, Java Script, ,
, . ,
-
,
.

3.2.
, ,
Java. Java
NeWS ( ,
, X Window), Sun
,
, . 9 1996
JavaSoft, Java-
. -
, . , 1 1997
, NASA (National Aeronautics and Space Administration,
, ) Java-
, ("Java !").
, Java
- "", Java ?
, , -,
(""), (Intel x86, Sun SPARC,
PowerPC .), , -, (MS Windows, Sun Solaris, Linux,
Mac OS .).
Java

Rendered by www.RenderX.com

. 15 30

, ,
(GUI) . ,
,
(API, Application Programming Interface),
, .
,
. .
,
- (,
Mac OS ,
Windows ).
.
( ), , ,
, , .
, ,
,

.
,
, .
,

. Java
, ,
Oak ,
.
"" ?
, - . Java
, , Java Virtual Machine.
JVM - , ,
, -
Java-. Sun JVM
.
Java, , .
JVM , , Sun
, ,
. 29 1996 Java OS (
). - - ",
, Java". ,
Java-
- , (PDA), ,
, . , Java OS
.
Java -
, .
Java

Rendered by www.RenderX.com

. 16 30

Java

, Java -
. -
, , Java
.
Java- " 100%".
, Sun
-
.
Sun, " - ".
,
, - . , , ,
WWW , .
,
- . , ,
,
.
, -
, . ,
, , , - !
,
,
- Microsoft. (
) Windows
Intel ( - Wintel).
, -
, ,
Wintel.
Microsoft
(, Netscape Navigator
MS Internet Explorer),
. ,
Wintel .
,
, ,
.
, Microsoft Java, , ,
, Internet
Explorer .
. 30 1997 IE 4.0, 7 Sun ,
.
18 Sun , "
Java" ("Java compatible") MS IE 4.0. , Microsoft ""
Java, .
, ,
. , Sun
. Java ,
Java

Rendered by www.RenderX.com

Java

. 17 30

"Write once, run everywhere" (" , ").


, "
".
Sun . 24 1998
(, ,
23 2001 , Sun 20
), 12 Sun
Microsoft Java Windows
98 .
. , Microsoft Internet Explorer'
java.rmi, ,
DCOM - , Win32.
(patch),
. Microsoft Java
1.1,
.
, (
),
. Sun Java Plugin, MS IE NN, Java
,
( Java Activator 10
1997 ). Microsoft , Java
Windows XP, ,
.
Java OS, ,
. , JVM
,
. Java, ,
.

3.3. Java
, Java ,
, ,
.
, ,
- -. ,
JVM, ,

Java-. JVM ,
-
.
Java,
- Java
? , .

Java

Rendered by www.RenderX.com

. 18 30

Java

Java
,
.java.
Java-, Java -.
JVM
Java.
.class.
Java-, , ,
, , .
Sun "Write once,
run everywhere",
. ,
. Java ,
. ,
, .
Sun ,
( Java) .
.
JVM 600 ,
, (
MS IE 4.0). , ,
, . - ,
,
. Java 2 Micro Edition (J2ME),
.
Java,
-.
, , Java
- (threads) (steams), ,
, , ..
, Java - ,
.
Java ,
. -,
. ,
. - "".
.
, Java . ,
, .
,
. (exceptions -
Java ) (runtime)
, , ,
. ,
, (
, ).
Java

Rendered by www.RenderX.com

Java

. 19 30

Java 8 , .
. 5 : byte, short, int,
long, char. 2 float double,
boolean. (
primitive), , .
- (. reference).
Java - .
C/C++, ,
Java, , .
- "Java - C++
, garbage collector".
(garbage collector) , Java ,
C++, - .
, , Java
. -,
C++ . -,
- , ? , ,

, Java
. ,
.
, , ++ ,
Sun, , Java
, .
.
, ,
Smalltalk IBM 60-
Simula, Java .
Java - -
. ,
,
C/C++. .
Java (
garbage collector). , , ,
, .
, .
/++ . ,
- , - (
, ),
, , ,
.
Java .
,
, garbage collector.
, ,
. - ,
Java

Rendered by www.RenderX.com

. 20 30

Java

, .
garbage collector,
. ,
, .
,
, . ,
, , (
) .. ,
, , ,
/++, ,

.
, . ,
( ,
!), Java ,
,
( ,
..). .
, , .
,
.
.
, - 90- ,
. ,
, ,
, .
garbage collector,
. - ,
.
Java ( ,
, ,
). .
, Java, C/C++,
. , -
, .
Java - .
,
, .
Java .
.
-, . ,
. JVM,
, ,
.
.

Java

Rendered by www.RenderX.com

Java

. 21 30

-, -
. - ,
, class-. JVM ,
Java,
- ( ).
, .
, ,
(
). ,
.
Java.
, ,
. ,
, . , ,
,
, ,
. ,
.
Java ,
- -( ) .
, Java - .
,
. .
, . Java- :
, -;
, ;
/++;
;
-, ;
, ;
.
, ,
. ,
, Java
. .
,
Sun, " " (reference implementation).
, Java 23 1995 . ,
-, :
Java language specification, JLS, Java ( ,
, , ..);

Java

Rendered by www.RenderX.com

. 22 30

Java

JVM;
Java Development Kit, JDK - , ,
.
,
. , ,
, (,
), .
.
JVM ,
Java-.
JDK .
, java-.
javac (java compiler) .
java. appletviewer.
,
javadoc.
8 :
java.lang - , ( language);
java.util - ;
java.applet - ;
java.awt, java.awt.peer -
(GUI), Abstract Window Toolkit, AWT.
.
java.awt.image - ;
java.io - (streams) ;
java.net - .
, java, .
( com, org .)
.
JDK 1.0 1996 .
. .
1. ,
1... , , JDK,
.
- JDK,
,
.
0 4 ( ).
(212, 504, 1781, 2130

Java

Rendered by www.RenderX.com

Java

. 23 30

2738 - 1.0 1.4),


. , JDK.
, .
, , ,
() . , JDK 1.0 - 1.0.2.
1. , , -
. deprecated,
2.0 ( ), .
JDK 1.0 . ,
, . -, , .
. , JVM
, ,
. , , , .
AWT,
.
1996 JDK 1.1,
-. 1997 .
Java?
, . -,
Assembler,
C, . , 1996 Sun - JustIn-Time , JIT. - Java - ""
. , ,
50 ! 1997
Windows, JIT JDK
.
. JavaBeans - ,
1996 , ,
. JDBC (Java DataBase Connectivity)
. RMI (Remote Method Invocation)
. .
3 JDK 1.1 220.000 , -
2- . 1.1 ,
1.1.8. - ,
MS IE ,
.
, 11 1997 Sun Java Runtime Environment, JRE ( Java).
, Java-,
. , ,
.
,
(GUI). 1996 Sun Netscape
IFC (Internet Foundation Classes), Netscape
Java .
Java

Rendered by www.RenderX.com

. 24 30

Java

1997 , AWT Sun


IFC Netscape Java Foundation Classes, JFC,
:
, Swing;
Drag-and-Drop.
2D , ;
Accessibility API ;
. IBM . 1997
JFC. , ,
com.sun.java.swing Swing. 1998
. 500.000 .
Java 1.2 ,
1.1,
Java 2 ( , ,
1.., ). -
1997 , 8 1998 ,
.
,
:
, (policy)
(permission);
JFC JDK, , ,
javax.swing Swing ( javax ,
Java);
(collection framework) -
;
Java Plug-in JDK;
, (
), "-2000".
1999 JVM
.
JDK 1.2. 15
1999 JavaOne Sun
Java 2 :
Java 2 Platform, Standard Edition (J2SE);
Java 2 Platform, Enterprise Edition (J2EE);
Java 2 Platform, Micro Edition (J2ME).
, ,
,
. ,
Java.
Java

Rendered by www.RenderX.com

Java

. 25 30

J2SE
. , Standard Edition - Java
JDK ( j2sdk).
J2EE , ,
. , Enterprise Edition -
(, Enterprise Java Beans, EJB) (
, Application Server), .
j2sdk.
J2ME Standard Edition ,
,
.
. J2SE
, J2EE 1999 .
j2sdk 1.2 - 1.2.2.
, Sun
. 1999 (engine) Java HotSpot.
,
(garbage collector) .
,
Java-.
- .
.
.
HotSpot , 2000
JVM J2SE.
,
j2sdk 1.3 (
1.3.1).
, J2SE 1.4 2002 .
- (web services).
XML (Extensible Markup Language).
- assert,
,
. , .
j2sdk 1.4 . 2002
1.4.1,
.
Standard Edition
, ,
1.3: 1.4:

Java

Rendered by www.RenderX.com

. 26 30

4.
, Sun
1990 .

.
Green. , ,
Oak. Sun FirstPerson,
, , Java,
. 1993
Mosaic 1.0
. Java- ,
HotJava. , 4-
, Java .
Netscape, .
Java
. Java Script, ,
, Java.
Java. Sun: JDK JRE.
Java,
.

5.
1-1.

Java. JVM?
a.) :

Java,
/++

(garbage collection)

Java-

Java

Rendered by www.RenderX.com

. 27 30

( SSL .)

JVM Java Virtual Machine, Java,


-, class-.
-,
,
.
1-2.

Java ?
a.) . , .

1-3.

(garbage collector)?
a.)
Java. ,
, .

1-4.

Java C/C++?
a.) .
Java -,
, .

1-5.

Java , ?
a.) ,
,
, , .Java
,

.

1-6.

- Sun Microsoft
MS Internet Explorer 4.0?
a.) Java -,
.
,
.
Microsoft Internet Explorer 4.0
,
,
Java.

1-7.

, Java?

Java

Rendered by www.RenderX.com

. 28 30

a.) Java ,
java.
.class-, -,
. -
(.jar .zip).
1-8.

Java-,
Sun ?
a.) Java
. ,
.
Java ,
.
Sun, JVM, JIT
(Just-in-time),
,
. 1.3 HotSpot,

.

1-9.

?
a.) , Java, ,
,
. HTML-.

,
, .

1-10. Java?
a.) 23 1995 SunWorld.
1-11. Java?
a.) Java http://java.sun.com
1-12. Java? Java2?
Java?
a.) .
.
, , ,
,
.
,
, ,
.
0 4 ( 1.0 1.4).
.
Java 1.2 1.1, ,
Java

Rendered by www.RenderX.com

. 29 30

, Java2 (
).
.
, ,
.
Java 1.4.0.
1-13. deprecated?
a.) Java
,
, ,
. deprecated,
,
.
1-14. Java Java2?
a.) 1999 Java
:

J2SE Java2 Standard Edition, Java,


JDK

J2EE Java2 Enterprise Edition, ,


,

J2ME Java2 Micro Edition, J2SE


1-15. Java ? Java Plugin?


a.) Java 1.1,
,
..
,
.
Sun 1997
Java Plug-in,

Java. Plug-in .
1-16. JDK JRE? ?
?
a.) JDK Java Development Kit, Java,
,
. :

java JVM

javac Java

appletviewer
Java

Rendered by www.RenderX.com

. 30 30

jar JAR

javadoc

JRE Java Runtime Environment, Java,


Java-,

.

Java

Rendered by www.RenderX.com

Java
2.
-

27 2003
:
( Sun ) <vyazovick@itc.mipt.ru>
( Sun ) < gene@itc.mipt.ru>
Copyright 2003 Sun , , .

-
() . Java (
8 ) ,
. , .

-.

Rendered by www.RenderX.com

ii

2. - ............................. 1
1. - ...........................................1
1.1. - ................... 1
1.2. - ........................4
1.3. ................................................................................................................ 5
1.3.1. . ....................................................................................................6
1.3.2. .................................................................................................... 6
1.3.3. ............................................................................................... 7
1.4. ................................................................................................................... 7
1.4.1. ................................................................................................8
1.4.2. ............................................................................................... 9
1.5. .....................................................................12
1.5.1. ................................................................................................... 12
1.5.2. ................................................................................................ 13
1.5.3. ............................................................................................ 14
1.5.4. ................................................................................................ 15
1.6. ............................................................................................... 16
1.7. ..................................................................................................17
1.8. ........................................................................................................... 18
1.9. .......................................................................................... 19

Java

Rendered by www.RenderX.com

. 1 24

2.

.
1. - .......................................... 1
1.1. - ......................... 1
1.2. - ..............................4
1.3. ...................................................................................................................... 5
1.3.1. . ......................................................................................................... 6
1.3.2. ..........................................................................................................6
1.3.3. ..................................................................................................... 7
1.4. ......................................................................................................................... 7
1.4.1. ......................................................................................................8
1.4.2. ..................................................................................................... 9
1.5. .......................................................................... 12
1.5.1. ......................................................................................................... 12
1.5.2. ...................................................................................................... 13
1.5.3. .................................................................................................. 14
1.5.4. ...................................................................................................... 15
1.6. ..................................................................................................... 16
1.7. ........................................................................................................17
1.8. ................................................................................................................. 18
1.9. ................................................................................................19

1. -

1.1. -

. ,
,
,
. ,
Java

Rendered by www.RenderX.com

. 2 24

.
, ,
. FOCAL (FOrmula
CALculator) FORTRAN (FORmula TRANslator).

.
,
.
. - . ,
,


.

.
.
.
,

.
, ,
, .
,
. , Pascal
:
Procedure printGreeting(name: String)
Begin
Print("Hello, ");
PrintLn(s);
End;

- "Hello, Name", Name


.
, ,
.
. ,
.
, , ,
.
,
(),
.

-.
19.701-90. - (. 1.1).

Java

Rendered by www.RenderX.com

. 3 24


.
,
goto .
, "bowl of spaghetti",
, , ,
. ,
goto .

.

,
.

.
, "-".
70- - 80 .
.
,
. ,
, .
, .
"-" "-".
,
, , .
Java

Rendered by www.RenderX.com

. 4 24

1.2. -

, , ,
.
,
.
,
. " "
,
, , .

.
,
.
.
, -
.
,
,
. 80-
,
. -
().
, , ,
. -
.
.
, ,
, ..
,
(. 1.2). -

,
..

,
.

Java

Rendered by www.RenderX.com

. 5 24

,
, .
"", , , .
.

.
() , .
- ,

-
,
.

, ,
.
-

.
.

1.3.
,
,
. :

();

.
Java

Rendered by www.RenderX.com

. 6 24

: , "", , 7461,
..
.
-
.
:
- , ,
.[1]
,
.

1.3.1. .
. ()
, , , .
, , , - ,
. -

.
.
, ( ),
, , . ,
, , ,
.
, ,
:

(, , );

( ).

, , ,
( ).
(state) - : ,
, ;
(,
) (, ) .
[1]

1.3.2.
, .
, :

Java

Rendered by www.RenderX.com

. 7 24


, .. , , , - ().
-
"" "" "" .
, , ,
. ,
.
- "", ""
"" . .. " ",
" " " -
" . . ,
, ,
, .
, ,
. , , ,
.
(behavior) - ,
; .
[1]

1.3.3.
- , . ,
, ()
( , ..)
- - .

.
Identity () , ,
, .
,
, , , Identity .

. , ..
( ) .
, (identity) - ; , .[1]

1.4.

( ). , ,
, - :
Java

Rendered by www.RenderX.com

. 8 24

. ""
"" "", -
.
.
,
. , , :
. ,
, ,
, ..
.
.
(, ), .
, , .
(record),
;
, (
).
-
, . (,
)

UML (Unified Modeling Language, )


:
, .
, - , - ,
().
,
:

(constructor) - ;

(destructor) - ;

,
, .

1.4.1.
(encapsulation) -
(). -
-
.
.
(
). , Java,
. .
Java

Rendered by www.RenderX.com

. 9 24

. ,
. ,
,
.

, .

. -, ,
,
.
-, .
, ,
, ,
.
, , .
,
, ,
.

, .

1.4.2.
-
.
" ". ,
- ,
.
,
- Point, Line, Circle, Box, ..
draw
.
, ,
,
, draw . ,
, :
,
draw.
:

// ,
// Point 1000
Point[] p = new Point[1000];
Line[] l = new Line[1000];
Java

Rendered by www.RenderX.com

. 10 24

Circle[] c = new Circle[1000];


Box[] b = new Box[1000];

// ,
//

for(int i = 0; i < p.length;i++){ // .


// draw() ,
// .
if(p[i]!=null) p.draw();
}
for(int i = 0; i < l.length;i++){
if(l[i]!=null) l.draw();
}
for(int i = 0; i < c.length;i++){
if(c[i]!=null) c.draw();
}
for(int i = 0; i < b.length;i++){
if(b[i]!=null) b.draw();
}


. ,

, Text, Star ..,
,
, .
,
. ,
. Point. ,
(1.3).

draw ,
.

Java

Rendered by www.RenderX.com

. 11 24

, ,
:

Point p[] = new Point[1000];


p[0] = new Circle();
p[1] = new Point();
p[2] = new Box();
p[3] = new Line();

for(int i = 0; i < p.length;i++){


if(p[i]!=null) p.draw();
}

p[] ,
Point. -
, .
, p[0] Circle, draw

p[0].draw()

, .
:
(polymorphism) - ,
(, ) ( )
. , , , [1].
,
.
,
.
, - (overloading).
.
Java PrintWriter,
.
println, /
. :
void println() //
// (true false)
void println(boolean x)
void println(String x) // -

Java

Rendered by www.RenderX.com

. 12 24

. Java
, .
.

1.5.
, , - ,
, .
. ,
, .
,
.
(
,
):

(Aggregation)

(Association)

(Inheritance)

(Metaclass)

1.5.1.
"" " "
. , ,
, .
(aggregation)
, .
.
"contain" . Aquarium
Fish. "",
. .
"home" Aquarium (
), "inhabitants" Fish ( ).
.
, . ..
Aquarium () inhabitants, Fish home.
, , .
"0..n" " ". :

"1..n" - ;

"0" - ;

"1" - ;

"n" - ;

Java

Rendered by www.RenderX.com

. 13 24

"0..1" - .

, , ,
, :
// Fish
public class Fish {
// home ( Aquarium)
private Aquarium home;
public Fish() {
}
}
// Aquarium
public class Aquarium {
// inhabitants ( Fish)
private Fish inhabitants[];
public Aquarium() {
}
}

1.5.2.
,
, ""
, (association).
, , ,
- , .
.
, . ,
- ,
.
--.
Programmer Computer
"0..n", ..
( ).
( ).
, , , , :
public class Programmer {
private Computer computers[];
public Programmer() {
}
Java

Rendered by www.RenderX.com

. 14 24

}
public class Computer {
private Programmer programmers[];
public Computer() {
}
}

1.5.3.
(inheritance) - ,
( ) (
) . "/",
.
.
,
" " " ". ,
. , 4 , ,
.. ,
, 5- 12-.
, "",
" " " "
.

. (- ),
- (- )
,
,
.
.
.

.
"",
"". .. , ,
.

, -
.
-
.
-
.

Java

Rendered by www.RenderX.com

. 15 24

Java
.

1.5.4.
, , . ,
, , ,
, , .
, , ,
. , ,
, ,
, .
, , (,
, , ..).
, .
, ,
. , ,
.
, ,
. , -
, , ,
(, ). ,
(,
, ) (
).
. ,
,
(,
) " " .
, , - . , ,
. ,
, Python. ,
:
set_XXX
get_XXX, XXX, .
, "-".
Java . , - Class
( ) java.lang.
. .class-,
, JVM Class,
. , Java
. Class (static)
. , , .
.

Java

Rendered by www.RenderX.com

. 16 24

1.6.
,
.
. ,
, . ,
.
.

,
,
.

,
,
, .
.

,

.

.
,
. ,
, - .
.
.

.
, ,
. .

.
,
, ,
.

.
,
.

(framework).

, (framework),
, .


- , .
,
.

Java

Rendered by www.RenderX.com

. 17 24

,
.

,
, .

, ,
,
.

,
,
.

1.7.
- ,
. ,
, , ,
. ,
. , , ,
. , ,
,
.
.
, .

. ,
. , ,
, , ,
.
, , ,
. .
, , ,
"" .
.
, . ,
, ,
.
, .
?
, ,
.
1. . Smalltalk

. ,
.
Smalltalk- C-.
Java

Rendered by www.RenderX.com

. 18 24

Oberon-2, Object Pascal C++


.
10% , .
,
.
, :
. ,
.
.
, , (..
, ), .
2. .

. ,
.
. , -

.
3. . ,
.
, .
, . ,
.
- ,
,
.
- .

.
, . ,
, -
. ,
,
.

1.8.
- ,
, .
.
, .
, , ,
.
UML.

Java

Rendered by www.RenderX.com

. 19 24

1.9.
2-1.

-
?

a.) ,

,
. 80-
,
. ().
2-2.

? .
a.) ,
,
. :

();

: , "", ,
7461, ..
2-3.

, :
1. ;
2. ;
3. ;
4. 113-043-429-18.
a.) ,
113-043-429-18 - .
,
. , 113-043-429-18
,
.

Java

Rendered by www.RenderX.com

. 20 24

2-4.

a.) .

, .

.
2-5.

.
a.) :
1. ;
2. ;
3. ;
4. , .

2-6.

? :
1. ;
2. ;
3. .
a.) : -
.

2-7.

?
a.) ,
( ),
, ,
.

2-8.

-
: ? .

Java

Rendered by www.RenderX.com

. 21 24

a.) : . . ,
,
, .
2-9.

: , , .
?
.
a.) :

2-10. :
1. Java2:
2. 342 Java2:
3.
4. ()
.
a.)

2-11. , .
, , ..
( ,
), ( ).
, , 2 :
1. ( , )
2. ( ,
)
Java

Rendered by www.RenderX.com

. 22 24

.
a.) :
1.

2.

2-12. . ,
.
a.) :

2-13. , , .
,
, ,
.
a.) : ,
.
, .

.
Java

Rendered by www.RenderX.com

. 23 24

2-14. ,
:

- ;

, .
a.) :
:

- ;

, .

Java

Rendered by www.RenderX.com

Java ()

Java

Rendered by www.RenderX.com

Java
3.
20 2003
:
( Sun ) <vyazovick@itc.mipt.ru>
( ) <hel@cos.ru>
( Sun ) < gene@itc.mipt.ru>
Copyright 2003 Sun , , .

Java.
, , ,
() .
( tokens ) - "",
Java.
,
, .
.

Rendered by www.RenderX.com

ii

3. ....................................................................................................1
1. ................................................................................................................ 1
1.1. ..............................................................................................................2
1.2. ............................................................................................... 2
1.2.1. ....................................................................................................... 3
1.2.2. .................................................................................................4
1.2.3. ........................................................................................................8
1.3. ......................................................................................................... 9
1.3.1. ......................................................................................... 9
1.3.2. .......................................................................................... 9
1.3.3. ....................................................................................................10
1.3.3.1. ............................................................... 10
1.3.3.2. ............................................................................ 11
1.3.3.3. ....................................................................... 13
1.3.3.4. .....................................................................13
1.3.3.5. ........................................................................ 14
1.3.3.6. Null .......................................................................................15
1.3.3.7. ......................................................................................15
1.3.3.8. .........................................................................................15
1.3.3.9. ....................................................................................... 15
1.4. : ................................................................. 16
1.4.1. ................................................... 16
1.4.2. .......................................................................17
1.4.3. .............................................................................. 18
1.4.4. ..................................................................................... 19
1.5. ........................................................................................................... 22
1.6. .......................................................................................... 22

Java

Rendered by www.RenderX.com

. 1 26

3.
.
1. ................................................................................................................1
1.1. ....................................................................................................................2
1.2. ..................................................................................................... 2
1.2.1. ............................................................................................................. 3
1.2.2. .......................................................................................................4
1.2.3. ..............................................................................................................8
1.3. ............................................................................................................... 9
1.3.1. ............................................................................................... 9
1.3.2. ................................................................................................ 9
1.3.3. ..........................................................................................................10
1.3.3.1. ..................................................................... 10
1.3.3.2. .................................................................................. 11
1.3.3.3. ............................................................................. 13
1.3.3.4. ...........................................................................13
1.3.3.5. ..............................................................................14
1.3.3.6. Null ............................................................................................ 15
1.3.3.7. ............................................................................................15
1.3.3.8. ...............................................................................................15
1.3.3.9. ............................................................................................. 15
1.4. : .......................................................................16
1.4.1. ......................................................... 16
1.4.2. .............................................................................17
1.4.3. .................................................................................... 18
1.4.4. ........................................................................................... 19
1.5. ................................................................................................................. 22
1.6. ................................................................................................22

1.
, , ,
() .
( tokens ) - "",
Java.
,
, .
.
Java

Rendered by www.RenderX.com

. 2 26

1.1.
Java, ,
, , ASCII (American
Standard Code for Information Interchange,
), ,
(, , .)
.
Unicode.
, Unicode 2 , , ,
65.535 .
. 128 ASCII. , ,
,
Unicode, 65
. Unicode,
ASCII. , 6917,
(1B05) :
\u1B05

u , A, B, C, D, E, F
, , .
Unicode \u0000 \uFFFF.
\u0410 ( \u0401) \u044F ( \u0451).
JDK
SymbolTest,
Unicode. .
native2ascii, JDK.
- Unicode, ASCII, ( -reverse) - Unicode
.
Java 1.1 Unicode 1.1.5, 1.4
3.0. , Java
. JDK Unicode, ,
Character. - ,
- http://www.unicode.org/.
, ASCII,
Unicode . , Unicode
, , ,
: , , .
ASCII .

1.2.
, ,

(white spaces);

(comments);

Java

Rendered by www.RenderX.com

. 3 26

(tokens).

1.2.1.
,
. (space, \u0020, 32),
. ,
, . ,
( ):
double a = 1, b = 1, c = 6;
double D = b * b - 4 * a * c;
if (D >= 0) {
double x1 = (-b + Math.sqrt (D)) / (2 * a);
double x2 = (-b - Math.sqrt (D)) / (2 * a);
}

:
double a=1,b=1,c=6;double D=b*b-4*a*c;if(D>=0){double
x1=(-b+Math.sqrt(D))/(2*a);double x2=(-b-Math.sqrt(D))/(2*a);}

.
, -
.
ASCII - " "
(carriage return, CR, \u000d, 13) (linefeed, LF, \u000a,
10). , Java
.

ASCII- LF, ;

ASCII- CR, " ";

CR, LF.

( ,
),
(. ""),
(
, ).
, Java :

ASCII- SP, space, , \u0020, 32;

ASCII- HT, horizontal tab, , \u0009,


9;

ASCII- FF, form feed, (


), \u000c, 12;

Java

Rendered by www.RenderX.com

. 4 26

1.2.2.

.
Java 2 :

ASCII- // .
, , :
int y=1970; //
ASCII- /* */,
, :
/*

-
*/
for (int i=1; i<10; i++) {
...
}

(
*):
/*
*
* while
*/
while (x > 0) {
...
}

,
:
float s = 2*Math.PI/*getRadius()*/; //

.
Math.PI PI, Math.
getRadius() , s
2 PI. .
,
( ).
:
// /**/ s
String s = "text/*just text*/";
/*
* ,

Java

Rendered by www.RenderX.com

. 5 26

* getRadius()
*/
circle.get/*comment*/Radius();

:
// :
cirle./*comment*/getRadius();
// :
int/*comment*/x=1;

int x
, , .
. /*, */, //
, , . ,

/* /* // /** : */

. (
)
1. /*
2.
comment
3. /*
4.
more comments
5. */
6.
finish
7. */

. 1
/*. /* 3 ,
. */ 5 , 7
- , .
,
, , .
- ,
, - .
,

int x = 2;
int y = 0;
/*
if (x > 0)
y = y + x*2;
else
y = -y - x*4;
*/

Java

Rendered by www.RenderX.com

. 6 26

y = y*y;// + 2*x;

if-else +2*x.
, Unicode,
, .
, - .
.
JDK, 1.0, javadoc.
, HTML ,
, .
,
(, ,
, ). ,

. .
, .
-
/**. :
/**
* .
*
* x.
*/
int getAbs(int x) {
if (x>=0)
return x;
else
return -x;
}

.
(
,
).
HTML-,
HTML. , <b> <p> . ,
<h1> <h6> <hr> ,
javadoc .
*
. , ,
, , .
/**
* - .
* <p>
* :
* <blockquote>
Java

Rendered by www.RenderX.com

. 7 26

* <pre>
* if (condition==true) {
*
x = getWidht();
*
y = x.getHeight();
* }
* </pre></blockquote>
* HTML-:
* <ul>
* <li> <i></i>,
* <li> <b></b>.
* </ul>
*/
public void calculate (int x, int y) {
...
}

HTML-, :
- .
:
if (condition==true) {
x = getWidht();
y = x.getHeight();
}
HTML-:
,
.

, javadoc . @.
. ,
@see, , ,
-.
/**
* .
*
* .
*
* @see java.lang.String
* @see java.lang.Math#PI
* @see <a href="java.sun.com">Official Java site</a>
*/

String (java.lang - ,
), - PI Math ( #
), Java.
, ,
, . /** */ ,
Java

Rendered by www.RenderX.com

. 8 26

, , javadoc. ,
( , , Java).
package.html, ,
. HTML-, <body>
</body> , ,
.
Java ,
, .
javadoc.
,
. , Java javadoc
.

1.2.3.
, ( , .. ,
) ,
. ,
.
, , ,
- ,
.
, :
// .
int x = 3 ;
//
int
x
=
3
;
//
int x = 3 ;
/*
*
* int x
* .
*/
int/**/x=3;

, , .
.

Java

Rendered by www.RenderX.com

. 9 26

1.3.
Java:

(identifiers);

(key words);

(literals);

(separators);

(operators).

1.3.1.
- ,
. , , , , ,
( ).
Unicode, , .
.
. . Java-,
, ASCII- A-Z (\u0041-\u005a),
a-z (\u0061-\u007a), _ (ASCII underscore, \u005f) $
(\u0024). (
), -
, . Java-
ASCII- 0-9 (\u0030-\u0039).
(
, true false null- null). , 2
, (,
A), .
:
Character, a, b, c, D, x1, x2, Math, sqrt, x, y, i, s, PI, getRadius, circle,
getAbs, calculate, condition, getWidth, getHeight, java, lang, String
,

COLOR_RED, _, aVeryLongNameOfTheMethod

1.3.2.
abstract
default
if
private
this
boolean
do
implements
protected
throw
break
double
import
public
throws
byte
else
instanceof
return
transient
case
extends
int
short
try
catch
final
interface
static
void
char
finally
long
strictfp
volatile
class
float
native
super
while

Java

Rendered by www.RenderX.com

. 10 26

const
continue

for
goto

new
package

switch
synchronized

goto const , . ,

. , true, false null- null
( ,
), .
.

1.3.3.
,
, null-. Java :

(integer);

(floating-point);

(boolean);

(character);

(string);

null- (null-literal).

.
1.3.3.1.
,
.
, .
, , , 8 9 .
0x 0X ( 0 ASCII- X
). ,
:
0
00
0x0

, 10-15
A, B, C, D, E, F, . :
0xaBcDeF, 0xCafe, 0xDEC

,
int long 4 8 ( 32 64
). , .. int -231 231-1,
-2.147.483.648 2.147.483.647. int,
, 0 2147483648,
. 2147483648
-:

Java

Rendered by www.RenderX.com

. 11 26

int x = -2147483648; \\
int y = 5-2147483648; \\

, 00
017777777777 (=231-1), - -020000000000 (= -231).
- 0x0 0x7fffffff (= 231-1), 0x80000000 (= -231).
long 64 , , -263 263-1.
, L l,
long.
:
9223372036854775807L
0777777777777777777777L
0x7fffffffffffffffL
// :
-9223372036854775808L
-01000000000000000000000L
-0x8000000000000000L

long:
0L, 123l, 0xC0B0L

1.3.3.2.
.
, .
:
3.14
2.
.5
7e10
3.1E-20

, :

( ASCII- );

( ASCII- E
+ -);

- .

, (
L l long) 2
Java

Rendered by www.RenderX.com

. 12 26

- ASCII- D ( double) F ( float) .


.
:

. , ""
, , :
1.
.1
1e1
1f

Java , ,- float double. - 4 8


32 64 . float,
F .
double D d, double
( ).
// float-:
1f, 3.14F, 0f, 1e+5F
// double-:
0., 3.14d, 1e-4, 31.34E45D

Java 32- float 64- double


, IEEE 754 (
- IEEE Standard for Binary Floating-Point Arithmetic, ANSI/IEEE Standard 754-1985 (IEEE, New
York)). ,
, :

(positive/negative infinity);

" ", Not-a-Number, NaN;

.
(,
0.0/0.0 NaN), Float Double,
POSITIVE_INFINITY, NEGATIVE_INFINITY NaN.
.
,
. :

float: 3.40282347e+38f

double: 1.79769313486231570e+308

Java

Rendered by www.RenderX.com

. 13 26

, :

float:1.40239846e-45f

double: 4.94065645841246544e-324

(, 1e40F)
. .
, (, 1e350) . .
, :
// , 0
0.0000000000000000000000000000000000000000000001f
// , 1
1.0000000000000000000000000000000000000000000001f

Java
, Float Double ,
.
1.3.3.3.
truefalse
1.3.3.4.
'a' //
' ' //
'K' //

(.
""). :
'\u0041' // A
'\u0410' //
'\u0391' // A

,
, \.
( , ", ', \) :
\b
\t
\n
\f
\r
\"
\'
\\

\u0008
\u0009
\u000a
\u000c
\u000d
\u0022
\u0027
\u005c

backspace BS -
horizontal tab HT -
linefeed LF -
form feed FF -
carriage return CR -
double quote " -
single quote ' -
backslash \ -

Java

Rendered by www.RenderX.com

. 14 26

\ \u0000 to \u00ff .

,
Java-. Unicode-.
. \
.

. ,
'\101' // '\u0041'

\u0000 \u00ff (.. 0


255), Unicode- .
Unicode- (\uhhhh)
, :
'\u000a' //

\u000a ,
, .
:
'\n' //

\u000d ( )
\r.
,
.
1.3.3.5.
.
.
, \ (. "
").
"" //
"\"" //, "
" " // 13

.
, ,
\n / \r. ,
, +.
:
// -, 2
" " +
" "

Java

Rendered by www.RenderX.com

. 15 26

/*
* , :
* Hello, world!
* Hello!
*/
"Hello, world!\r\nHello!"

, ,
\u000a \u000d.
String.
,
.
1.3.3.6. Null
Null : null. ,
, . ,
.
.
1.3.3.7.
( ) [ ] { } ; . ,

1.3.3.8.
- , , ,
, . 37 ( ASCII) Java:
= > < ! ~ ? :
== <= >= != && ||
+ - * / & | ^ %
+= -= *= /= &= |=

++
<<
^=

->>
%=

>>>
<<=

>>=

>>>=


, Java
, .
1.3.3.9.
, Java-.
, Unicode
:

(, , , null-,
) ASCII-.
Unicode-
Java

Rendered by www.RenderX.com

. 16 26

ASCII- ( - \uhhhh, hhhh -


).
( Hello, world!),
:
public class Demo {
/**
* ,
* Java .
*/
public static void main (String args[]) {
System.out.println("Hello, world!");
}
}

, , 7 ,
5 , 1 , 13 .
Demo.java, ( JDK
). ,
:
Hello, world!

1.4. :
Java.
, .
,
(, 1/2 0, 1/2. - 0.5).

1.4.1.
-, , = ==.
x = 1; // x 1
x == 1 // x

.
true false.
, :
//
if (x=0) { // ==
...
}

Java . x=0 (
),
( x==0).
Java

Rendered by www.RenderX.com

. 17 26

" " !=. :


if (x!=0) {
float f = 1./x;
}

- = (.
"") ,
, :
x = x + 1;
x += 1;

1.4.2.
4 +, -, *, /,
%, ,
.
.
a b, (a/b)*b+(a%b) a.
, , / . :
9/5 1
9/(-5) -1
(-9)/5 -1
(-9)/(-5) 1

, .
,
.
9%5 4
9%(-5) 4
(-9)%5 -4
(-9)%(-5) -4

0 .

. ,
%. 9 5 ,
( , ).
9.0%5.0 4.0
9.0%(-5.0) 4.0
(-9.0)%5.0 -4.0
(-9.0)%(-5.0) -4.0

Java

Rendered by www.RenderX.com

. 18 26

IEEE 754 .
Math.IEEEremainder(double f1, double f2). , f1-f2*n, n - , f1/f2,
2 , .
:
Math.IEEEremainder(9.0, 5.0) -1.0
Math.IEEEremainder(9.0, -5.0) -1.0
Math.IEEEremainder(-9.0, 5.0) 1.0
Math.IEEEremainder(-9.0, -5.0) 1.0

++ --, ,
, .
int x=1;
int y=++x;

++ x, ,
, x
y. x y 2.
int x=1;
int y=x++;

x y,
. x 2, y
1.

1.4.3.
"" "" ( & |) .
, , , ,
.
, -
, ,
.
(&, |) , - ( &&, || )
, . :
int x=1;
(x>0) | calculate(x) // calculate
(x>0) || calculate(x) // -

"" !,
. .
int x=1;
x>0 //
!(x>0) //

Java

Rendered by www.RenderX.com

. 19 26

? : - .
( ),
, -
. , x:
x>0 ? x : -x

1.4.4.
,
. ,
:
0 0
1 1
2 10
3 11
4 100
5 101

. ? -,
. , 0
, 1 - . ,
. , 8- :
-1 10000001 // !
-2 10000010 // !
-3 10000011 // !

! , - 00000000
100000000, .
. -1, 0 1:
00000000
-00000001
--------11111111

, -1 11111111.
( 1):
0
-1
-2
-3

00000000
11111111
11111110
11111101

10000000,
. 8-
01111111 (=127), 10000000 (=-128). 8
Java

Rendered by www.RenderX.com

. 20 26

28=256 , , ,

, .
, "", "", " " 2 ,
.
, , , ,
() . , 5&6 :
00000101 // 5
&00000110 // 6
--------00000100 // ""

, 5&6 4.
"" "NOT",
~ ( !).
. , ~(-1)= 0.
:
n - , -n ~(n-1).
, . Java
.
.
<<
, .
2n, ,
.
int, .. 32-
. 20, -21.
// 20
20 << 00 = 00000000000000000000000000010100
20 << 01 = 00000000000000000000000000101000
20 << 02 = 00000000000000000000000001010000
20 << 03 = 00000000000000000000000010100000
20 << 04 = 00000000000000000000000101000000
...
20 << 24 = 00010100000000000000000000000000
20 << 25 = 00101000000000000000000000000000
20 << 26 = 01010000000000000000000000000000
20 << 27 = 10100000000000000000000000000000
20 << 28 = 01000000000000000000000000000000
20 << 29 = 10000000000000000000000000000000
20 << 30 = 00000000000000000000000000000000
20 << 31 = 00000000000000000000000000000000

Java

Rendered by www.RenderX.com

=
=
=
=
=

20
40
80
160
320

=
=
=
=
=
=
=
=

335544320
671088640
1342177280
-1610612736
1073741824
-2147483648
0
0

//
-21
-21
-21
-21
-21
-21
...
-21
-21
-21
-21
-21
-21
-21
-21

. 21 26

<< 00
<< 01
<< 02
<< 03
<< 04
<< 05

-21
= 11111111111111111111111111101011
= 11111111111111111111111111010110
= 11111111111111111111111110101100
= 11111111111111111111111101011000
= 11111111111111111111111010110000
= 11111111111111111111110101100000

=
=
=
=
=
=

-21
-42
-84
-168
-336
-672

<<
<<
<<
<<
<<
<<
<<
<<

=
=
=
=
=
=
=
=

=
=
=
=
=
=
=
=

-352321536
-704643072
-1409286144
1476395008
-1342177280
1610612736
-1073741824
-2147483648

24
25
26
27
28
29
30
31

11101011000000000000000000000000
11010110000000000000000000000000
10101100000000000000000000000000
01011000000000000000000000000000
10110000000000000000000000000000
01100000000000000000000000000000
11000000000000000000000000000000
10000000000000000000000000000000

, ,
.
,
, . -
, . .
>> ,
, . >>>
, .
// 20
//
20
20
20
20
20
20

>>
>> 00 = 00000000000000000000000000010100
>> 01 = 00000000000000000000000000001010
>> 02 = 00000000000000000000000000000101
>> 03 = 00000000000000000000000000000010
>> 04 = 00000000000000000000000000000001
>> 05 = 00000000000000000000000000000000

//
20
20
20
20
20
20

>>> 00 =
>>> 01 =
>>> 02 =
>>> 03 =
>>> 04 =
>>> 05 =

=
=
=
=
=
=

>>>
00000000000000000000000000010100
00000000000000000000000000001010
00000000000000000000000000000101
00000000000000000000000000000010
00000000000000000000000000000001
00000000000000000000000000000000

20
10
5
2
1
0

=
=
=
=
=
=

20
10
5
2
1
0

, >> >>>
.
.
// -21

Java

Rendered by www.RenderX.com

. 22 26

//
-21 >> 00 =
-21 >> 01 =
-21 >> 02 =
-21 >> 03 =
-21 >> 04 =
-21 >> 05 =

>>
11111111111111111111111111101011
11111111111111111111111111110101
11111111111111111111111111111010
11111111111111111111111111111101
11111111111111111111111111111110
11111111111111111111111111111111

=
=
=
=
=
=

// >>>
-21 >>> 00 = 11111111111111111111111111101011
-21 >>> 01 = 01111111111111111111111111110101
-21 >>> 02 = 00111111111111111111111111111010
-21 >>> 03 = 00011111111111111111111111111101
-21 >>> 04 = 00001111111111111111111111111110
-21 >>> 05 = 00000111111111111111111111111111
...
-21 >>> 24 = 00000000000000000000000011111111
-21 >>> 25 = 00000000000000000000000001111111
-21 >>> 26 = 00000000000000000000000000111111
-21 >>> 27 = 00000000000000000000000000011111
-21 >>> 28 = 00000000000000000000000000001111
-21 >>> 29 = 00000000000000000000000000000111
-21 >>> 30 = 00000000000000000000000000000011
-21 >>> 31 = 00000000000000000000000000000001

-21
-11
-6
-3
-2
-1

=
=
=
=
=
=

-21
2147483637
1073741818
536870909
268435454
134217727

=
=
=
=
=
=
=
=

255
127
63
31
15
7
3
1

, 2n. ,
n 0,
-1.

1.5.
Java.
Unicode,
.
Unicode ASCII-.
( ,
) ,
( , ).
.
, .
.

1.6.
3-1.

Java- 514?
a.) 514
b.) \u0546

Java

Rendered by www.RenderX.com

. 23 26

c.) \u222
d.) \u0222
a) ,
, , .
\u, 4
, c) . b)
0x0546=1350.
3-2.

:
int x = 3; int y=1;
int z = x+y;

a.) 7
b.) 8
c.) 9
d.) 11
9: 5 , 1 , 3 .
3-3.

:
int x = 0; /* text // text /*
int y=1; // text */ // text */

a.) 1 , 0
b.) 1 , 1
c.) 1 , 2
d.) 2 , 3
b).
x, */
text. .
3-4.

?
a.) , ,
/**. javadoc
HTML,
, , , , .
HTML-,
, <hr> <h1>..<h6>,
javadoc. , ,
@, .

Java

Rendered by www.RenderX.com

. 24 26

3-5.

?
a.) abc
b.)

1ab

c.)

_bc

d.) _1c $ac


e.)

$ac

f.)

for_

g.)

Int

h.)

byte

1ab , . byte
, byte.
. ($ac)
. Int ,
int .
3-6.

:
a.) true
b.) goto
c.) null
d.) const
e.) false
goto const , .
,
, Java.
true, false, null , .

3-7.

:
a.) 5 05
b.) 9 09
c.) 10 010
d.) 0x5A 90L

Java

Rendered by www.RenderX.com

. 25 26

5 05 . 09 , . 010
8 10. 0x5A 90, 90L.
3-8.

?
1/0 1./0 1/0. 1./0.
\n+\r

a.) 1/0 . 3
POSITIVE_INFINITY.
23.
3-9.

x
?
int x=0;
print(++x==x++);

a.) . 1, x
1 .
1, x
. 2.
3-10. x y
?
int x=0, y=0;
print((++x==1) || (y++==1));

a.) , .
,
. x 1, y 0.

Java

Rendered by www.RenderX.com

Java ()

Java

Rendered by www.RenderX.com

Java
4.
20 2003
:
( Sun ) <vyazovick@itc.mipt.ru>
( Sun ) < gene@itc.mipt.ru>
Copyright 2003 Sun , , .

. , Java
,
.
, Java.
,
, Class, Java.

Rendered by www.RenderX.com

ii

4. ..................................................................................................... 1
1. .......................................................................................................................... 1
2. ...................................................................................................................2
3. ....................................................................3
3.1. ............................................................................................... 5
3.2. ............................................................................................ 5
4. .............................................................................................................. 12
5. .............................................................................................................. 17
6. ..........................................................................................................17
6.1. ................................................................... 17
6.2. Object ......................................................................................................... 22
6.3. String ......................................................................................................... 24
6.4. Class ..........................................................................................................25
7. .................................................................................................................. 26
8. .................................................................................................................... 27
9. ...................................................................................................27

Java

Rendered by www.RenderX.com

. 1 31

4.
.
1. ......................................................................................................................... 1
2. .................................................................................................................. 2
3. ................................................................... 3
4. ............................................................................................................. 12
5. ............................................................................................................. 17
6. ......................................................................................................... 17
7. ................................................................................................................. 26
8. ................................................................................................................... 27
9. .................................................................................................. 27

1.
Java . ,
.
. , ,
, "" (
bugs) (
), , .
Java
.
. 8
( primitive) . :

byte

short

int

long

char ( )

float
Java

Rendered by www.RenderX.com

. 2 31

double

boolean

( reference)
. , .
Java , .
, ,
Java .
.

2.
.
:

.
, . - ,
.
(declaration). ,
. , Java
, .
( ),
.
int
:
int
int
int
int

a;
b = 0, c = 3+2;
d = b+c;
e = a = 5;

, ,
.
( 3+2), .
(, b+c).
,
( ), .
:
. ,
, , , ,
. ,
Java

Rendered by www.RenderX.com

. 3 31

.
.
,
.
, , ,
.
, final.
,
. , final-
- , , ,
, .
final-:
final double pi=3.1415;

3.

. , 2
, , .
?
int:
int a=5; //
int b=a; // ,
a=3; //
print(b); //

, print(...) ( ,
) ( ,
System.out.println(...),
).
, b ,
5. , ,
.
:
byte b=3;
int a=b;

(
). ,
b 3 byte, a - 3 int.
, .
.
. ,
Java

Rendered by www.RenderX.com

. 4 31

. -
, :
class Point {
int x, y;
}

, int-, ,
new Point(3,5) - (3,5).
Point p1 = new Point(3,5);
Point p2=p1;
p1.x=7;
print(p2.x);

,
p1, , ,
p2. , ,
.
"" , .
,
. , .
,
, .
,
.
, ,
:
Point p1 = new Point(3,5);
Point p2=p1;
p1 = new Point(7,9);
print(p2.x);

3, p1 p2
.
null.
. , ,
. ,
(, ) .
null
( ).
Java
, , .
,
.
, .. ,
Java

Rendered by www.RenderX.com

. 5 31

.
- - .
"",
. .
garbage collector -
, .
, , ,
, . ,
- , ,
.
.
.

3.1.
, 8 ,
(integer), (floating-point) (boolean).

3.2.
- byte, short, int, long, char.
1, 2, 4 8 , char - 2 ,
, Java Unicode.
. , Java
, ,
.
4 . char ,
JVM - . ,
, char - .
, .
char - , , ,
, ..
:

()

byte

-128 .. 127

short

-32.768 .. 32.767

int

-2.147.483.648 .. 2.147.483.647

long

-9.223.372.036.854.775.808 ..
9.223.372.036.854.775.807 (
1019)

char

'\u0000' .. '\uffff', 0 .. 65.535

, int 2 ,
, .
long, , Java .
, 1 1970 . ,

Java

Rendered by www.RenderX.com

. 6 31

long (!), ,
.
, int long? ,
int long, L
l. ,
4 8 . .
, :
1
-2147483648
2147483648L
0L
111111111111111111L

( )
-

<, <=, >, >=

==, !=

( )
-

+ -

+, -, *, /, %

( ): ++ --

<< , >>, >>>

~, & , |, ^

? :

.
(true false).
, .
+ -,
( ), ( ).
.
+ , (+x x). -,
x, , 0-x.
,
.
int x=-2147483648; // int
int y=-x;

Java

Rendered by www.RenderX.com

. 7 31

y 2147483648,
int, x!
-x==x !
,
, , Java
. ,
, .
, ,
.
int x= 300000;
print(x*x);

:
-194313216

-2147483648, ,
+231 , , 10.0 ( 31 ).
int ,
-2147483648.
, ,
, (. "").
, ""
.
, -5 .
5 -. ,
(, 2147483648) -.
, Java .
8, 16, 32 64 ,
32- 64- . ,
.
long,
, long.
64 , , ,
.
long , 32 ,
int ( byte, short, char).
int. 32- .
, , .
:
int i=300000;
print(i*i); // 32
long m=i;
print(m*m); // 64

Java

Rendered by www.RenderX.com

. 8 31

print(1/(m-i)); // int long

:
-194313216
90000000000

, i m
, , .
32 , .
- 64 , .
, ,
.
, ,
. -, ,
.
double x = 1/2;

x 0, 0.5, .
,
0.5 1./2 ( ,
).
, Java . ,
:
print(1000*60*60*24*7); //
print(1000*60*60*24*30); //

(1000), -
(60), - (60), - (24), (7 30
). :
604800000
-1702967296

, .
long:
print(1000*60*60*24*30L); //

:
2592000000

64-
, , .

Java

Rendered by www.RenderX.com

. 9 31

, , Java
. ,
:
//
int x=1;
byte b=x;

, b 1,
byte, x
, , int.
:
//
byte b=1;
byte c=b+1;

.
b int, ,
, byte.
:
//
int x=2;
long y=3;
int z=x+y;

long.
:
//
byte b=5;
byte c=-5;

- 32 .
,
,
:
byte b=1;
byte c=(byte)-b;

, int long.
.
-, .
,
,
Java

Rendered by www.RenderX.com

. 10 31

( ,
). , . (
32 ,
.)
byte x=5;
byte y1=x++;
byte y2=x--;
byte y3=++x;
byte y4=--x;
print(y1);
print(y2);
print(y3);
print(y4);

//
//
//
//

x
x
x
x

5
6
5
6

:
5
6
6
5

++ -- byte.
, :
byte x=-128;
print(-x);
byte y=127;
print(++y);

:
128
-128


.
? :.
, .
byte
byte
byte
byte

x=2;
y=3;
z=(x>y) ? x : y; // , x y
abs=(x>0) ? x : -x; // !

Java

Rendered by www.RenderX.com

. 11 31

, ,
, int, int, .
byte, - short, int.
, . +
. ,
- , , .
int x=1;
print("x="+x);

:
x=1

:
print(1+2+"text");
print("text"+1+2);

:
3text
text12

char.
:
char c1=10;
char c2='A'; // A (\u0041, 65)
int i=c1+c2-'B';

i 9.
:
char c='A';
print(c);
print(c+1);
print("c="+c);
print('c'+'='+);

:
A
66
c=A
225

print char,
. , ,
Java

Rendered by www.RenderX.com

. 12 31

. char
. : 'c' ( 99),
'=' ( 61) c (.. 'A' - 65).
-
(wrapper classes). byte, short, int, long, char Byte, Short, Integer, Long, Character.
.
, . , Math,
,
.
, ,
Java - ( / %).

4.
- float double. - 4 8 . .
:

()

float

3.40282347e+38f ; 1.40239846e-45f

double

1.79769313486231570e+308 ;
4.94065645841246544e-324

,
. , -
. ,
, , overflow.
, ,
underflow.
//
float f = 1e40f; // , overflow
double d = 1e-350; // , underflow

, F f,
float. double,
D d.
:

( )
-

<, <=, >, >=

==, !=

( )
-

+ -

+, -, *, /, %

Java

Rendered by www.RenderX.com

. 13 31

( ): ++ --

? :

,
( % ,
++ -- ).
,
. ,
.
- overflow underflow.
, Java .
, . ,
. ,
.
.
IEEE 754 "":

(positive/negative infinity);

" ", Not-a-Number, NaN;

float, double.
:
1f/0f // , float
-1d/0d // , double

Float Double POSITIVE_INFINITY NEGATIVE_INFINITY. ,


.
NaN , , :
0.0/0.0 //
(1.0/0.0)*0.0 //

NaN Float Double.


:
0.0 //
+0.0 // +, -
-0.0 // -, -

Java

Rendered by www.RenderX.com

. 14 31

.
, - . +0.0 -0.0
, 0.0==-0.0 , 0.0>-0.0 - .
, , 1.0/0.0 , 1.0/0.0 - .
- NaN.
NaN, false ( !=
true). , x,
x!=x , NaN.
.
(overflow),
.
print(1e20f*1e20f);
print(-1e200*1e200);

:
Infinity
-Infinity

, , (underflow),
. ,
:
print(1e-40f/1e10f); // underflow float
print(-1e-300/1e100); // underflow double
float f=1e-6f;
print(f);
f+=0.002f;
print(f);
f+=3;
print(f);
f+=4000;
print(f);

:
0.0
-0.0
1.0E-6
0.002001
3.002001
4003.002

, 6- .
Java

Rendered by www.RenderX.com

. 15 31

( Java):
double d = 1e-305 * Math.PI;
print(d);
for (int i = 0; i < 4; i++)
print(d /= 100000);

:
3.141592653589793E-305
3.1415926535898E-310
3.141592653E-315
3.142E-320
0.0

, , ,
(overflow) (underflow) ,
(. "").
, .
. double,
,
double. 64 .
double , float,
float, 32 ,
float.
, .
NaN, NaN.
:
print(1/2);
print(1/2.);

:
0
0.5

,
.
:
int x=3;
int y=5;
print (x/y);

Java

Rendered by www.RenderX.com

. 16 31

print((double)x/y);
print(1.0*x/y);

:
0
0.6
0.6

, . ,
,
, .
( ),
( ).
,
.
-, ,
. , 3.84 3, -3.84
-3.
Math.round().
-, int float long
float double , ,
, .
:
long l=111111111111L;
float f = l;
l = (long) f;
print(l);

:
111111110656

float , long float


.
-
(wrapper classes). float double Float Double.
. ,
.
, Math
, , ,
, . PI
E.

Java

Rendered by www.RenderX.com

. 17 31

5.
boolean,
- true false.
.
:

( )
-

==, !=

( )
-

&, |, ^

&&, ||

? :

&& || .
? : boolean. ,
.
"true"
"false" .
, ,
if.
.
, ( ),
x!= 0. boolean
ref!=null.

6.
, null, ,
JVM.

6.1.
(object) - .
. -
, ,
. ,
.
new,
new ( , ).
, .
Java

Rendered by www.RenderX.com

. 18 31

(
), ,
, . ,
Point, new Point(3,5)
Point, 2 int. ,
.
,
Point:
class Point {
int x, y;
/**
* 2 ,
* .
*/
Point (int newx, int newy){
x=newx;
y=newy;
}
}

, new
. , . JVM
. , ,
(garbage collector).
"" .
Point p=new Point(1,2); // ,
Point p1=p; // 2 (1,2)
p=new Point(3,4); // (1,2)
p1=null;

- (1,2) ,
.
new.
- String. ,
. +,
,
new.
:
"abc"+"def"

Java

Rendered by www.RenderX.com

. 19 31

3 String.
,
.
- Java.
.
, , , .
,
, ,
.
Java 1.1 reflection,
, , .
new,
, , , , ,
. ,
:
Point p = null;
try {
// ,
// Point,
// new
p = (Point)Class.forName("Point").newInstance();
} catch (Exception e) { //
System.out.println(e);
}

"", . ,
, , .
, . , Parent
Child:
// Parent
class Parent {
}
// Child,
// Parent
class Child extends Parent {
}

- .
, :
Parent p = new Child();

Parent , Child.
Java

Rendered by www.RenderX.com

. 20 31

instanceof ( )

== != ( )

? :


. . ().
.
instanceof, , .
. , - ,
. :
Parent p = new Child();
// p Parent
// Child
print(p instanceof Child);

true. , instanceof ,
, .
, .
:
//
// Child
class ChildOfChild extends Child {
}

:
Parent p = new ChildOfChild();
print(p instanceof Child);

Parent,
, ChildOfChild. instanceof
Parent Child,
, . , true,
, , Child.

Java

Rendered by www.RenderX.com

. 21 31

:
class Child2 extends Parent {
}

Parent:
Parent p=new Child();
print(p instanceof Child);
print(p instanceof Child2);

p Parent, , Child
Child2. instanceof :
true
false

null instanceof false.


Java,
instanceof.
= != ( )
. - .
.
, Java,
. ,
, true ,
.
Point p1=new Point(2,3);
Point p2=p1;
Point p3=new Point(2,3);
print(p1==p2);
print(p1==p3);

:
true
false

, p2
, p1. , , p3
- . ,
new.
= null, - ,
false. null, true.
equals,
. , :
Java

Rendered by www.RenderX.com

. 22 31

String s = "abc";
s=s+1;
print(s.equals("abc1"));

? : ,
, .
.
, .
null, "null". ,
( , toString()),
, , .

6.2. Object
Java .
. , ,
. , ,
Object. ,
. ,
Object. ,
( Object ),
.
:

getClass()

Class, ,
. Class .
getName()
, :
String s = "abc";
Class cl=s.getClass();
print(cl.getName());

:
java.lang.String

instanceof, getClass() ,
.

equals()

Object boolean. ,
equals() , .
, , .
Point p1=new Point(2,3);
Java

Rendered by www.RenderX.com

. 23 31

Point p2=new Point(2,3);


print(p1.equals(p2));

true.
Object , , , equals
.
(
). Point
:
public boolean equals(Object o) {
// ,
// Point
if (o instanceof Point) {
// ,
Point p = (Point)o;
//
return p.x==x && p.y==y;
}
// Point, false
return false;
}

hashCode()

int. hashCode() -
. - ( Java
, ). ,
, -, ,
, , ( equals()
true) -.
Object JVM.
-, .

toString()

.
, .
Object , toString(),
:
getClass().getName()+"@"+hashCode()

getName() Class , -
.

Java

Rendered by www.RenderX.com

. 24 31

:
print(new Object());

:
java.lang.Object@92d342

,
, , -, ,
.
,
.

finalize()


(garbage collector). Object , -
, ,
, , ..
, .
, .
finalize() ,
. , JVM
.

6.3. String
, String Java .
new.
String, ( null),
.
,
, , ,
.
. , ,
, -,
, .
String s="a";
s="b";

,
String.
,
Java,
.

Java

Rendered by www.RenderX.com

. 25 31

-, ,
.
String s1 = "abc";
String s2 = "abc";
String s3 = "a"+"bc";
print(s1==s2);
print(s1==s3);

:
true
true

, , ,
, .
,
, :
String s1="abc";
String s2="ab";
print(s1==(s2+"c"));

false,
.
String intern(), -,
, . , s1 s2
s1.equals(s2), s1.intern()==s2.intern().
, equals() hashCode(). toString()
, -, s
String, null, s==s.toString().

6.4. Class
, , .
Class Java. JVM
.class, , Class,
.
, :
Point p=new Point(1,2);

, :
1. , Point, (1,2)
2. Class, Point

Java

Rendered by www.RenderX.com

. 26 31

3. Class, Object. Point


Object, .
4. Class, Class. Java-,
.
Class - getClass()
Object. :
Class cl=p.getClass(); // 2
Class cl2=cl.getClass(); // 4
Class cl3=cl2.getClass(); // 4

cl2==cl3 .
Class
reflection.
, Java
, (
, ..).

7.
- . ,
. , :

- ;

- , ;

- ;

instanceof;

- , import- ..


. Java
- ,
.
.
Java 1.5 (templates),
, .

Java

Rendered by www.RenderX.com

. 27 31

8.
, Java ,
.
,
.
Java , ,
(8 ) ().
.
.
null, . JVM
,
.
.
, .
. final.
5 , , 2 1
. , .
,
.
, , ,
, instanceof.
Java Object, Class, String.
.

9.
4-1.

?
byte b=3;
int c=b;
c++;
print(++b==c);

a.) 3.
,
,
. true.
4-2.

?
Point p = new Point(1, 2);
int a=p.x;
p = new Point(3, 4);
print(a);

Java

Rendered by www.RenderX.com

. 28 31

a.)
. 1.
4-3.

?
Point p1 = new Point(3, 4);
Point p2 = p1;
p1.x=5;
p1 = new Point(4, 4);
print(p2.x-p1.x);

a.) ,
x 5. p1
, x 4.
5-4=1.
4-4.

?
1/2 1./2 1/2. 1./2.

a.) ,
, .. 0.
, , 0.5.
4-5.

,
+.
a.) , , (
) .
(+=).

4-6.

x,
:
a) x*30/30==x
b) x/30*30==x

a.) a) , Integer.MAX_VALUE/30, .. 71582789. b)


, 30, , 15.
4-7.

(
33)?
print(Hello+!);

a.) Hello!
4-8.

Java

Rendered by www.RenderX.com

. 29 31

double x=2./0;
double y=-1/0.;
print(x+y);

a.) x POSITIVE_INFINITY, y
NEGATIVE_INFINITY. NaN.
4-9.

Java.
a.) new,
,
.
String .
, , newInstance()
Class.

4-10. ?
Point p1 = new Point(2, 3);
Point p2 = new Point(2, 3);
print(p1==p2);
p2=p1;
p1.x=3;
print(p1==p2);

a.) false.
, p1 p2
.
,
true.
4-11. x1 x2
(SomeClass2 x2)?
x1 instanceof SomeClass2
x1.getClass().getName().equals(x2.getClass().getName())

a.) . ( ) ,
,
x1 x2. instanceof
. s ,
, , . , x1
, - SomeClass2, x2 ,
SomeClass2, instanceof true,
false.
4-12. false?

Java

Rendered by www.RenderX.com

. 30 31

a) x.toString() instanceof String


b) (x+) instanceof String

a.) a) , x
, toString() ,
null.
. b) true.
4-13. x
?
x.getClass()==x

a.) , x
Class, Class.
y, null:
x=y.getClass().getClass()

Java

Rendered by www.RenderX.com

Java
5. .
20 2003
:
( Sun ) <vyazovick@itc.mipt.ru>
( Sun ) < gene@itc.mipt.ru>
Copyright 2003 Sun , , .

Java
(packages), .
Java .
, .
. ,
, ,
Sun.
,
.
.

Rendered by www.RenderX.com

ii

5. . ................................................................................................... 1
1. ......................................................................................................................... 1
2. ............................................................................................................................. 2
2.1. . . ........................................................... 2
2.2. ....................................................................................2
2.3. () ........................................................................... 3
3. ............................................................................................................................. 4
3.1. ................................................................................................... 5
3.2. ...................................................................5
3.3. ............................................................................................. 7
3.3.1. ..................................................................................... 8
3.3.2. - ......................................................................................9
3.3.3. ...................................................................12
3.4. ................................................................................14
4. ............................................................................................15
4.1. "" (Shadowing) ........................................................... 16
4.2. "" (Obscuring) .......................................................... 17
5. ...................................................................................... 17
6. .................................................................................................................... 20
7. ...................................................................................................20

Java

Rendered by www.RenderX.com

. 1 24

5. .
.
1. ........................................................................................................................ 1
2. .............................................................................................................................2
3. ............................................................................................................................ 4
4. ........................................................................................... 15
5. ......................................................................................17
6. ................................................................................................................... 20
7. .................................................................................................. 20

1.
(names) (declared)
"", "", "" ( -
, , ). , Java
:

(member) :

:
-

, ,
. , ,
, .
Java

Rendered by www.RenderX.com

. 2 24

, (packages) Java - ,
,
.
.
.

2.
2.1. . .
(simple), (
), (qualified),
, .
.
(, , ) (members).
, , ,
, .
(type).
, ,
. ,
, , , .
, Java - java.lang ( ,
lang, java).
, reflection,
. reflect, , , - java.lang.reflect.
, Object, String, Point.
,
, . , java.lang.Object,
java.lang.reflect.Method com.myfirm.MainClass. :
com, - myfirm,
myfirm - MainClass. com.myfirm -
, MainClass, MainClass - .
- com.myfirm.MainClass.
,
( ). ,
,
. . , toString(),
PI, InnerClass.
. , ref.toString(),
java.lang.Math.PI, OuterClass.InnerClass.
.

2.2.
, ,
(, ) . ,
Java

Rendered by www.RenderX.com

. 3 24

, - .
.
-, (declaration) .
,
.
-,
, ,
. :
country.getCity().getStreet();

getStreet , ,
,
getCity(). , country.getCity - .
, (label).
, , ,
.
num:
for (int
int n
while
if

num = 2; num <= 100; num++) {


= (int)Math.sqrt(num)+1;
(--n != 0) {
(num%n==0) {
continue num;

}
}
System.out.print(num+" ");
}

, 100:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

, num,
while for.
, , , ..
. , ,
, ,
.
- .

2.3. ()
,
, , ,
(scope). , ,

Java

Rendered by www.RenderX.com

. 4 24

, ,
, - .
,
class Point {
int x,y;
int getX() {
return x; //
}
}
class Test {
void main() {
Point p = new Point();
p.x=3; //
}
}

, x .
.
, , .
.
, , .

3.
Java (packages).
, .
, ,
, . -,
, " ". -,
. , ,
,
"" , . ,
. ,
, ,
, .

.
, ,
. ,
.

Java

Rendered by www.RenderX.com

. 5 24

3.1.
, (
). ,
.
.
, JDK 1.0 java : applet, awt, io, lang, net, util;
. java.awt image 46
.

. , Object java.lang
java.lang.Object, image java.awt - java.awt.image.

, , ,
,
. , space.sun, space.sun.ray, space.moon factory.store
"" ,
.

3.2.
.
, ,
.
java,
, , , applet, awt, io, lang, net, util.
, ,
Sun, Moon Test, space.sunsystem.
space,
, - sunsystem, .
, .java, -
.class. , sunsystem
:
Moon.java
Moon.class
Sun.java
Sun.class
Test.java
Test.class

,
space.sunsystem.Moon
space.sunsystem.Sun
space.sunsystem.Test
Java

Rendered by www.RenderX.com

. 6 24


space\sunsystem\Moon.java
space\sunsystem\Sun.java
space\sunsystem\Test.java

- .class-. ,
. () ( Windows \).
,
.
, Java space\sunsystem
Test, , -
. , Java,
, .
, , Java , ,
.
,
, .
, (
). ,
. ,
, . ,
, ,
Java.
Java SDK (, ..),
, - ,
, , , . ,
, -
, Java .
, .
,
, .
.
Java ,
classpath. , path
, Java-.
, .
1.1 ZIP JAR (Java ARchive) - ,
ZIP Java.
, classpath :
.;c:\java\classes;d:\lib\3Dengine.zip;d:\lib\fire.jar

""
. Java
Java

Rendered by www.RenderX.com

. 7 24

. ,
( ).
, . ,
.
, .
, ,
classpath , ,
, .
, - , Java
.
.
,
.
, , -, Java-, , , classpath.
,
. ,
. ,
.java-, ,
. ,
/ / .

3.3.
(complication unit) - .java-
. :

import-;

,
. , ,
( - ).
import- ,
"" . .
, .
" " ,
, ,
. , , ,
. , .class-
.
, ..
Java ,
.
3 .
Java

Rendered by www.RenderX.com

. 8 24

3.3.1.
- .
package, .
, ( ) java/lang/Object.java :
package java.lang;

lang, java, ,
Object, .
java.lang.Object.
,
. Java. , ,
.
, :
class Simple {
public static void main(String s[]) {
System.out.println("Hello!");
}
}

.
Java
, .
, ,
. .
,
. , ,
:

, :
package space.star;
class Sun {
}

, , Java-,
space star ( space.star)
Java.

Java

Rendered by www.RenderX.com

. 9 24

, -
. , ,
Java .
, java.lang java.io, java,
Java-, ,
.

3.3.2. -
, - ,
. ,
. ,
, .
(, JDK1.2
com.sun.image.codec.jpeg),
,
.
import-,
.
:

, , ,
. ,
, . ,
, ,
,- ,
. , ,
-
.
,
. , ,
.
.
, , import
. :
import java.net.URL;

,
URL java.net. ,
, .
, , .
,
.

Java

Rendered by www.RenderX.com

. 10 24

, ,
.
import java.awt.*;

, java.awt,
. , , .
,
. , .
:
//
import java.awt.image;

, java.awt.image
, , image.ImageFilter.
, , java.awt
image.
,
import java.awt.*;

java.awt.image, .
java.lang ,
, .
, -
.
.
- :
import java.awt.*;
import java.awt.Point;

, - ,
? - ?
,
. :

, ;

, , ,
;

, , .

, ,
, .

Java

Rendered by www.RenderX.com

. 11 24

:
//
package my_geom;
import java.awt.Point;
class Point {
}

, Point
java.awt.Point,
, , .
:
package my_geom;
class Point {
}

:
package my_geom;
import java.awt.Point;
class Line {
void main() {
System.out.println(new Point());
}
}

- , my_geom.Point
java.awt.Point, ? :
java.awt.Point[x=0,y=0]

, Point .
: my_geom.Point.
, ""
,
.
. " ",
, ""
,
.
( ) .

Java

Rendered by www.RenderX.com

. 12 24

:
package my_geom;
import java.awt.*;
class Line {
void main() {
System.out.println(new Point());
System.out.println(new Rectangle());
}
}

:
my_geom.Point@92d342
java.awt.Rectangle[x=0,y=0,width=0,height=0]

Point ,
java.awt. Rectangle,
, java.awt.
:
package my_geom;
import java.awt.*;
class Point {
}

,
.
,
. , ,
,
. ,
, , ,
.

3.3.3.

. ,
.
class, - interface.
, . :
package first;

Java

Rendered by www.RenderX.com

. 13 24

class FirstClass {
}
interface MyInterface {
}

- , .
, .
Java .
.
, public:
package second;
public class OpenClass {
}
public interface PublicInterface {
}

.
, .
Java 1.1 (inner) ,
.
,
, .
, , Java
.
,
, (, ,java), :

public, , , ;

, ,
.
, public ,
. -public ,
,
.
,
.

, , public . .
, space.sun.Size space\sun\Size.java,

Java

Rendered by www.RenderX.com

. 14 24

- Size.class .
Java.
, ,
. , :
package test;
/*
* Human,
*/
class Human {
String name;
Car car; //
}
/*
* Car,
*/
class Car {
String model;
Human driver; // ,
}

, Car , .
, .
.

3.4.
Java ,
, ,
, .
.
.
Java .
, -,
, , , ,
company.com, ,
: com.company.
, , , ..
, ASCII-
:

com, edu, gov, mil, net, org ( );

, , ru, su, de, uk .

Java,
:
Java

Rendered by www.RenderX.com

. 15 24

, ,
;

,
;

, .

, :
com.sun.image.codec.jpeg
org.omg.CORBA.ORBPackage
oracle.jdbc.driver.OracleDriver

, , , Java-
-, .
,
.

4.
,
.
,
.
- ,
. ,
. java.lang
lang.

.
( ) ,
. ,
,
.
- ,
. ,
.
, super
this, .
,
.

, . ,
.

Java

Rendered by www.RenderX.com

. 16 24

int x;
for (int i=0; i<10; i++) {
int t=5+i;
}
// t ,
// ,
//
// x ,
//

,
.

4.1. "" (Shadowing)


Human () age ().
setAge(), .
setAge() ,
age ( ).
, setAge() age=age,
, - . , ,
,
. ,
.
-, , - .
- , .
, .
.
,
"" (shadowing) .
, .
, .
this (
). this ,
. setAge() Human
this , .
:
class Human {
int age;//
void setAge(int age) {
this.age=age; // !
}
}

Java

Rendered by www.RenderX.com

. 17 24

, - ,
this
. ,
, -
.

4.2. "" (Obscuring)


,
, .
, :
import java.awt.*;
public class Obscuring {
static Point Test = new Point(3,2);
public static void main (String s[]) {
print(Test.x);
}
}
class Test {
static int x = -5;
}

main() Test Oscruing


, - Test.
x, java.awt.Point Test.
3, .
, , . ,
,
.
"" (obscuring).
,
Java.

5.
, Java,
, , ,
Java.
Java , .
:

Java

Rendered by www.RenderX.com

. 18 24

( );

-;

.;

.
.
, ,
. ,
.
.
java javax (Java eXtension) Sun
Java.
"" (obscuring)
, .
.
,
. , ,
, "".
, , :
Human
HighGreenOak
ArrayIndexOutOfBoundsException

( - , ,
).
,
. able:
Runnable
Serializable
Cloneable

"" (obscuring) ,
() ,
- .
,
. , ,
.
:

Java

Rendered by www.RenderX.com

. 19 24

,
get set . , size
getSize() setSize().

, , length(), , String.

, , is, ,
isVisible() .

, F, toF(), ,
toSting(), .

, , , ,
Java, , .
, , -
, ,
. , , name
Human size Planet.
"" (obscuring) .
, final.
, , .
, :
PI
MIN_VALUE
MAX_VALUE

,
:
COLOR_RED
COLOR_GREEN
COLOR_BLUE

, ,
. , , ,
. , ( cp
ColorPoint) (buf buffer).
:
byte b;
char c;
int i,j,k;
long l;
float f;
double d;
Object o;
String s;
Exception e; // , Java
Java

Rendered by www.RenderX.com

. 20 24

-
-.

6.
.
,
, , .
(members),
. (
) .
, Java
,
. ( ).

, , ,
Java-.
,
, .
, . ,
,
. -
. ,
( , ). ,
, ,

.

, , .
.

.

7.
5-1.

Java ? ?
a.) :

(member) :
-

Java

Rendered by www.RenderX.com

. 21 24

:
-

,
.
5-2.

, ,
?
MyClass
MyClass.name
MyClass.name.toString()
MyClass.name.toString().hashCode()

a.) MyClass . MyClass.name, MyClass.name.toString


. hashCode .
5-3.

?
a.) ,
.

5-4.

,
, test.first.Start,
c:\Java\programs\test\first\Start.java?
a.) ,
. ,
c:\Java>javac programs\test\first\Start.java

c:\Java\programs\test>javac first\Start.java

5-5.

Java
, ?
a.) JVM , ,
..
c:\Java\programs>java test.first.Start

Java

Rendered by www.RenderX.com

. 22 24

5-6.

, 2 ,
c:\ ?
a.) , classpath .

5-7.

.
, Point test.demo,
java.awt.Point
java.net?
a)
package test.demo;
import java.awt.Point;
import java.net.*;
b)
import java.awt.*;
import java.net.*;
package test.demo;
c)
package test.demo;
import java.net.*;
import java.awt.*;
d)
package test.demo.*
import java.net.*;
import java.awt.*;

a.) a) , java.awt.Point
Point, .
b) , . d) ,
( )
. c) .
5-8.

? , ?
class Box {
private int weight=0;
public int getWeight() {
return weight;
}
void setWieght(int weight) {
weight=weigth;
}

Java

Rendered by www.RenderX.com

. 23 24

a.) , setWeight()
.
,
. , ,
.
5-9.


?
public class flat{
private int floor_number;
private int r; //
public int rooms() {
retun r;
}
public int GetFloorNumber() {
return floor_number;
}
}

a.) :

, Flat.

floor_number ,
, floorNumber.

r ,
, , rooms roomsNumber

rooms , ,
, getRoomsNumber.

GetFloorNumber ,
getFloorNumber.

,
. - (,
),
,
.

Java

Rendered by www.RenderX.com

Java ()

Java

Rendered by www.RenderX.com

Java
6.
20 2003
:
( Sun ) <vyazovick@itc.mipt.ru>
( Sun ) < gene@itc.mipt.ru>
Copyright 2003 Sun , , .

, Java-
.
Java. ,
- ,
Java.
, ( ),
. main,
Java-,
, .

Rendered by www.RenderX.com

ii

6. ........................................................................................ 1
1. ........................................................................................................................ 1
2. .................................................................................................. 2
2.1. ........................................................... 2
2.2. Java.............................................................................. 5
3. ....................................................................................................... 9
3.1. .................................................................................................... 9
3.2. ...........................................................................................................10
3.3. ............................................................................................... 11
3.4. ........................................................................................... 12
3.5. ................................................................................. 16
3.6. ...................................................................................................22
4. ............................................................................. 24
4.1. main............................................................................................................ 24
4.2. ............................................................................................. 25
4.3. ....................................................................................... 27
5. .................................................................................................................... 28
6. ...................................................................................................28

Java

Rendered by www.RenderX.com

. 1 33

6.
.
1. ....................................................................................................................... 1
2. ................................................................................................. 2
2.1. ................................................................. 2
2.2. Java.................................................................................... 5

3. ...................................................................................................... 9
3.1. .......................................................................................................... 9
3.2. .................................................................................................................10
3.3. ..................................................................................................... 11
3.4. ................................................................................................. 12
3.5. ....................................................................................... 16
3.6. .........................................................................................................22

4. .............................................................................24
4.1. main..................................................................................................................24
4.2. ................................................................................................... 25
4.3. .............................................................................................27

5. ................................................................................................................... 28
6. .................................................................................................. 28

1.
,
Java - . ,
, .
.
-
. Java,
, .
.
Java.
. ,
.

Java

Rendered by www.RenderX.com

. 2 33

2.
,
, , . ,
: public, , private,
, .

, , .

2.1.
,
: , ""
. , Human () age ( ),
-
, ,
. age private.
, ,
.
- , , .
,
. , Human age ,
, public.
public class Human {
public int age;
}

, , ,
, ,
.
, ,
. int double,
, Human age, ,
, , ,
:
Human h = getHuman();
int i=h.age; // !!

-
.
, ( , )
. ,
, .
, public, ,

Java

Rendered by www.RenderX.com

. 3 33

(, , , )
.
, private,
, :
public class Human {
private int age;
// , age
public int getAge() {
return age;
}
// , age
public void setAge(int a) {
age=a;
}
}

,
, Human,
private , ,
,
.
:
Human h = getHuman();
int i=h.getAge(); //

, age:
public class Human {
// double
private /*int*/ double age;
//
public int getAge() {
return (int)Math.round(age);
}
public void setAge(int a) {
age=a;
}
// double
public double getExactAge() {
return age;
}
Java

Rendered by www.RenderX.com

. 4 33

public void setExactAge(double a) {


age=a;
}
}

, , ,
. , ,
.
.
Human h = getHuman();
int i=h.getAge(); //

, i .
.
, , ,
:
Human h = getHuman();
double d=h.getExactAge(); //

, ,
.
? ,
, (
, public). ,
, ,
, .

, :
(accessors) (getters) (setters). ,
. ,
,
, .
, , .
. ,
. ,
:
public void setAge(int a) {
(if a>=0) {
age=a;
}
}

Java

Rendered by www.RenderX.com

Java

. 5 33

age .
( ,
, , , ,
;
Java).
. ,
, , ,
. - ,
persistent storage ( , , )
/ . ,
, ,
, , ,
.
. ,
, ,
, .
,
.
, .
, - .
,
, , , , ,
.
, ,
, ,
, .
,
, . Java
2 (public private), 4 .
Java .

2.2. Java
,
.
.
Java :

( ) ;

(, , );

, ,
, .

Java

Rendered by www.RenderX.com

. 6 33

4 . :

public;

private;

protected;

3 ,
(default).

. ( )
- ,
. Java ,
,
, .
, protected . ,
,
.
,
. protected
,
-, .
protected ,
. , (
- ):
private
(none) default
protected
public


.
,
.

, ( ,
public, ,
).

( ) .
: public .
public, , .
public, :
, .

, ,
(, ).

. 4
. public.

Java

Rendered by www.RenderX.com

Java

. 7 33

4 .
private- -, .
, , .

( ),
, , .
.
.
:
public class Wheel {
private double radius;
public double getRadius() {
return radius;
}
}

radius , getRadius()
.
:
package first;
// Parent
public class Parent {
}
package first;
// Child Parent,
//
class Child extends Parent {
}
public class Provider {
public Parent getValue() {
return new Child();
}
}

getValue() Provider ,
first, public. ,
Child, .
:
package second;

Java

Rendered by www.RenderX.com

. 8 33

import first.*;
public class Test {
public static void main(String s[]) {
Provider pr = new Provider();
Parent p = pr.getValue();
System.out.println(p.getClass().getName());
// (Child)p - !
}
}

:
first.Child

, Test
Child, , Parent.
. , "" ,
.
:
public class Point {
private int x, y;
public boolean equals(Object o) {
if (o instanceof Point) {
Point p = (Point)o;
return p.x==x && p.y==y;
}
return false;
}
}

Point ,
. , - private.
equals() , ,
Point, (
intsanceof) .
, -
private- !
, , private
, ,
.
Java .

Java

Rendered by www.RenderX.com

. 9 33

3.
.
.

3.1.
.
. public, - .
final.
. . String , , final-.
class, Java-. ,
:
class A {}

, .
.
, (
), , .
, - .
extends,
( ) -final .
. extends ,
Object. extends Object .
class Parent {} // = class Parent extends Object {}
final class LastChild extends Parent {}
// class WrongChild extends LastChild {} // !!

final- .
A extends B, A
B.
A B :

A B;

C, B, A
C ( ).

.
, ,
:
Java

Rendered by www.RenderX.com

. 10 33

//
class A extends B
class B extends C
class C extends A


{}
{}
{} // !

implements,
( ,
) :
public final class String implements Serializable, Comparable {}

, .
, .
implements , ,
.
,
.

3.2.
(members) :

( );

, - - .
,
.
.
4 . ,
.
- , .
. , .
.
,
- ( Object - ,
)
. , ,
.

Java

Rendered by www.RenderX.com

. 11 33

, -
protected public. private- .
,
, - .
.

3.3.
.
3 , ,
.
final, ,
. final-
- :
final double PI=3.1415;

final- .
,
, :
final long creationTime=System.currentTimeMillis();

.
- transient volatile. .
.
:
int a;
int b=3, c=b+5, d;
Point p, p1=null, p2=new Point();

.
.
.
.
.
int y=x;
int x=3;

:
class Point {
int getX() {return x;}

Java

Rendered by www.RenderX.com

. 12 33

int y=getX();
int x=3;
public static void main (String s[]) {
Point p=new Point();
System.out.println(p.x+", "+p.y);
}
}

:
3, 0

, ,
:

0;

false;

, y
getX(), x, 0.
x 3.

3.4.
. :

( );

void;

( );

throws-.

.
3 .
.
, final, ,
. , final-,
private- final.
, native. , ,
Java. (C/C++, Fortran
..) (, DLL
Windows). JNI (Java Native Interface),
native-.
Java,
, .
Java,
, . , Java-
Java

Rendered by www.RenderX.com

. 13 33

, , .
JNI .

( , native-),
, , , -"",
Java- JNI, ,
.
, synchronized,
, .
( )
; , .
, void.
.
.
.
.
. ,
.
:
// void calc (double x, y); - !
void calc (double x, double y);

, .
. , ,
, .
final .
( ,
).
public void process(int x, final double y) {
x=x*x+Math.sqrt(x);
// y=Math.sin(x); - , .. y - final!
}

,
.
(signature) .
(, , ).
,
.
,
class Point {
void get() {}

Java

Rendered by www.RenderX.com

. 14 33

void get(int x) {}
void get(int x, double y) {}
void get(double x, int y) {}
}

.
:
void get() {}
int get() {}
void get(int x) {}
void get(int y) {}
public int get() {}
private int get() {}

, , ,
. , ,
.
, ,
:
//
class Test {
int get() {
return 5;
}
Point get() {
return new Point(3,5);
}
void print(int x) {
System.out.println("it's int! "+x);
}
void print(Point p) {
System.out.println("it's Point! "+p.x+", "+p.y);
}
public static void main (String s[]) {
Test t = new Test();
t.print(t.get()); // !
}
}

get()
. main,
, .
print() ( , ,

Java

Rendered by www.RenderX.com

. 15 33

), , ,
get(), .
, . ,
,
. ,
,
.
, ,
,
.
, ,
.
, throws-.
Java .
:
public final java.awt.Point createPositivePoint(int x, int y)
throws IllegalArgumentException
{
return (x>0 && y>0) ? new Point(x, y) : null;
}

, . ,
" ". native-
, .
, ,
.
,
:
public void empty() {}

, void,
return-.
, ,
. ,
:
//
public int get() {
if (condition) {
return 5;
}
}

Java

Rendered by www.RenderX.com

. 16 33

, return-,
.
:
public int get() {
if (condition) {
return 5;
} else {
return 3;
}
}

, , return,
(
" ").
( void)
return . ,
:
public void calculate(int x, int y) {
if (x<=0 || y<=0) {
return; // ,
}
... //
}

return ( / )
. , ,
.

3.5.
.
. , -,
( ). ,
. ,
. , -
, ,
. ,
:
public class Human {
private int age;
protected Human(int a) {
age=a;
}

Java

Rendered by www.RenderX.com

. 17 33

public Human(String name, Human mother, Human father) {


age=0;
}
}

,
, . throws-.
, -
.
, .

( ).
(, , - ,
, )
, . ,
, .
return- .
,
.
.
, ,

. -
,
super.
public class Parent {
private int x, y;
public Parent() {
x=y=0;
}
public Parent(int newx, int newy) {
x=newx;
y=newy;
}
}
public class Child extends Parent {
public Child() {
super();
}
public Child(int newx, int newy) {
super(newx, newy);

Java

Rendered by www.RenderX.com

. 18 33

}
}

, super,
. ,
. 2
,
( , , , ).
.
new, ,
, .
, , .
. ,

. , ,
Object, . (
, ), ,
JVM , .
.
, Object,
. ,

. , ,
new, .
, new
, .
:
public class GraphicElement {
private int x, y; //
public GraphicElement(int nx, int ny) {
super(); // Object
System.out.println("GraphicElement");
x=nx;
y=nx;
}
}
public class Square extends GraphicElement {
private int side;
public Square(int x, int y, int nside) {
super(x, y);
System.out.println("Square");
side=nside;
}
}
Java

Rendered by www.RenderX.com

. 19 33

public class SmallColorSquare extends Square {


private Color color;
public SmallColorSquare(int x, int y, Color c) {
super(x, y, 5);
System.out.println("SmallColorSquare");
color=c;
}
}

:
GraphicElement
Square
SmallColorSquare

super .
.
(super()).
, super
( ),
.
, , -, ,
. , .
, ,
, - ,
.
,
, . ,
. public-
, . ,
, ,
. ,
( , ),
:
/*
* .
*/
public class One {
//
// Object
// .
}
/*
Java

Rendered by www.RenderX.com

. 20 33

* .
*/
public class Two {
// Second.
// new Second() !
public Second(int x) {
}
}
/*
* .
*/
public class Three extends Two {
public Three() {
super(1); // super
}
public Three(int x) {
super(x); // super
}
}

,
super, this - ,
.
:
public class Vector {
private int vx, vy;
protected double length;
public Vector(int x, int y) {
super();
vx=x;
vy=y;
length=Math.sqrt(vx*vx+vy*vy);
}
public Vector(int x1, int y1, int x2, int y2) {
super();
vx=x2-x1;
vy=y2-y1;
length=Math.sqrt(vx*vx+vy*vy);
}
}

, ,
:

Java

Rendered by www.RenderX.com

. 21 33

public class Vector {


private int vx, vy;
protected double length;
public Vector(int x, int y) {
super();
vx=x;
vy=y;
length=Math.sqrt(vx*vx+vy*vy);
}
public Vector(int x1, int y1, int x2, int y2) {
this(x2-x1, y2-y1);
}
}

,
. ,
(, ),
- .
,
.
,
, . this
super, ( )
. , ,
, .
new Test(0) :
Test()
Test(int x)

.
private.
, .
private . :

private- ,
this,
- ;

, ,
Math;

Singleton,
,
-private .

Java

Rendered by www.RenderX.com

. 22 33

3.6.
,
. -
.
public class Test {
private int x, y, z;
//
{
x=3;
if (x>0)
y=4;
z=Math.max(x, y);
}
}

,
, (, ,
-).
- ,
, .
,
.
:

(
), ;


, ;

,
. .

. -, ,
,
.
-, final. -
. :

(
);

,
. ,
this, final-,

Java

Rendered by www.RenderX.com

. 23 33

this- super,
.

:
public class Test {
{
System.out.println("initializer");
}
int x, y=getY();
final int z;
{
System.out.println("initializer2");
}
private int getY() {
System.out.println("getY() "+z);
return z;
}
public Test() {
System.out.println("Test()");
z=3;
}
public Test(int x) {
this();
System.out.println("Test(int)");
// z=4; - ! final-
}
}

new Test() :
initializer
getY() 0
initializer2
Test()

, y getY(),
final- z, .
y 0, z
3, .
new Test(3) :
initializer
getY() 0
initializer2
Java

Rendered by www.RenderX.com

. 24 33

Test()
Test(int)

4.
Java.
, Java.

4.1. main
,
. , Java, . ,
, .
, C/C++, main().
:
public static void main(String[] args) {
}

static .
main(), . ,
C . Java
System.exit(), int.
main() .
, .
package test.first;
public class Test {
public static void main(String[] args) {
for (int i=0; i<args.length; i++) {
System.out.print(args[i]+" ");
}
System.out.println();
}
}

,
main(). , ,
(.class .java),
( ), .
, , .
Test.java,
test\first, :

Java

Rendered by www.RenderX.com

. 25 33

javac test\first\Test.java

:
java test.first.Test

, :
java test.first.Test Hello, World!

:
Hello, World!

4.2.
Java
.
-, - ?
, , .
, .
- ?
int x=3;
process(x);
print(x);

, :
public void process(int x) {
x=5;
}

?
, Java.
,
,
. process(), x,
.
5 . , 3,
.
-
:
public int double(int x) {
return x+x;
}
Java

Rendered by www.RenderX.com

. 26 33

public void test() {


int x=3;
x=double(x);
}

.
public void process(Point p) {
p.x=3;
}
public void test() {
Point p = new Point(1,2);
process(p);
print(p.x);
}

,
. process()
, , . ,
,
. 3.
Java .
, , :
public void process(Point p) {
p = new Point(4,5);
}
public void test() {
Point p = new Point(1,2);
process(p);
print(p.x);
}

process()
, p, ,
1. , ,
.
,
final. ( ,
) ,
final ,
. , final Point p p.x= 5
( p=new Point(5, 5)).

Java

Rendered by www.RenderX.com

. 27 33

4.3.
(overloading)
. ,
.
, ,
, - , Java
,
.
.
, , ,
,
. ,
Parent Child, Child Parent, :
void process(Parent p, Child c) {}
void process(Child c, Parent p) {}

, , .
process(new Child(), new Child());

, . ,
:
process(Object o) {}
process(String s) {}

:
process(new Object());
process(new Point(4,5));
process("abc");

, ,
. ,
String "", , Object.
, String Object,
. ,
, .
.
.
, .
, , ,
:
process((Parent)(new Child()), new Child());

Java

Rendered by www.RenderX.com

. 28 33

//
process(new Child(),(Parent)(new Child()));

null:
process((Parent)null, null);
//
process(null,(Parent)null);

5.
Java
.
.
.
,
.
,
, .
4 ,
.
. ,
.
.
. (members)
. , .
.
, .
, ,
. .
main,
. , ,
.
Java .

6.
6-1.

?
a.) public protected, (
).

6-2.

, ,
.
?

Java

Rendered by www.RenderX.com

. 29 33

a.) private.
, , .
.
.
6-3.

User .
e-mail , , , ,
, . ?
public class User {
public String login; // e-mail
private String password; //
}

a.) ,
.
login ,
. login
, login.
:
public class User {
private String login; // e-mail
private String password; //
public String getLogin(){
return login;
}
}

6-4.

?
public class Test {
private int id;
public Test(int i) {
id=i;
}
public static boolean test(Test t, int id) {
return t.id==id;
}
}

a.) . test Test, ,


id .
6-5.

? ?

Java

Rendered by www.RenderX.com

. 30 33

a.) ( ):
1. (public, abstract, final)
2. class
3. extends
4. implements

5.
( ):

6-6.

( )

,
?
a.) .
.

6-7.

? ?
a.) ( ):
1. ( public|private|protected
static, final, native, synchronized)
2. void,
3.
4.
5. throws
,
( void), (
, ).

6-8.

.
double float
. float
(byte), (int). double int long .
, ?
a.) , 4 :
byte round(float x) { ... }
int roundToInt(float x) { ... }

Java

Rendered by www.RenderX.com

. 31 33

int round(double x) { ... }


long roundToLong(double x) { ... }

, ,
,
.
, 2 3 ,
. .
, , , round(1f)
1 , , .
. float
int round((double)1f), 3
, .
6-9.

?
a.) , .
, .
(

), ,
.

6-10. ?
class Test
private
private
private

{
long id=getId();
String name=getName();
String login;

public Test(int domain) {


login=domain+ +name;
System.out.println(login);
}
private static long getId() {
int id = 3;
System.out.println(id);
return id;
}
private String getName() {
String name=name+getId();
System.out.println(name);
return name;
}
}

Java

Rendered by www.RenderX.com

. 32 33

a.) :
3
3
name3
5 name3

id ( 3 ).
name,
getId() ( 3), name3.
5 name3.
6-11. main?
a.)

public static void main(String[] args)

6-12. String,
?
a.) , String, , , .

Java

Rendered by www.RenderX.com

Java
7.
20 2003
:
( Sun ) <vyazovick@itc.mipt.ru>
( Sun ) < gene@itc.mipt.ru>
Copyright 2003 Sun , , .

. Java
, ,
.
.
, Java
,
.
, ,
.
, .
.

Rendered by www.RenderX.com

ii

7. ..................................................................................... 1
1. ........................................................................................................................ 1
2. .......................................................................................................... 2
2.1. .........................................................................3
2.2. ( ) ....................... 3
2.3. ( ) ........................... 7
2.4. .....................................................................................9
2.5. .......................................................................... 10
3. ............................................................................................ 10
3.1. ..........................................................................................11
3.2. ......................................................................................................12
3.3. .............................................................................................. 14
3.4. ............................................................................ 15
3.5. ........................................................................................15
3.5.1. ................................................................. 15
3.5.2. ..............................................................16
4. ............................................................................16
5. .................................................................................................................... 18
6. ...................................................................................................18

Java

Rendered by www.RenderX.com

. 1 22

7.
.
1. ....................................................................................................................... 1
2. ..........................................................................................................2
2.1. ...............................................................................3
2.2. ( ) ............................. 3
2.3. ( ) ................................. 7
2.4. ...........................................................................................9
2.5. ................................................................................ 10

3. ............................................................................................10
3.1. ............................................................................................... 11
3.2. ............................................................................................................12
3.3. ....................................................................................................14
3.4. .................................................................................. 15
3.5. ............................................................................................. 15
3.5.1. .......................................................................15
3.5.2. ....................................................................16

4. ........................................................................... 16
5. ................................................................................................................... 18
6. .................................................................................................. 18

1.
, Java , ,

.
, , .
:
long l=3;
l = 5+'A'+l;
print("l="+Math.round(l/2F));

Java

Rendered by www.RenderX.com

. 2 22

, ,
(conversion) :

3 , int.
long .

int char.
, 32
. ,
l 64 .

, long
float, - .
Math.round, ,
int.
, . ,
-
- ( int Integer),
toString(), .

,
, . ,
,
, .
:
byte b=1;
byte c=(byte)-b;
int i=c;

,
byte int.
, .
, .

2.
Java :

(identity);

(widening primitive);

(narrowing primitive);

(widening reference);

(narrowing reference);

(String);

(forbidden).

.
Java

Rendered by www.RenderX.com

. 3 22

2.1.
. Java
.
? ,
.
-, , Java
, . ,
boolean , .
. Java
, :
print(getCity().getStreet().getHouse().getFlat().getRoom());

getCity().
, City.
getStreet(). ,
, City.
(getHouse()), .
, .
,
, .
,
. , :
print((MyFlatImpl)(getCity().getStreet().getHouse().getFlat()));

2.2. ( )
,
.

? . ,
. , byte
( 1 ) int ( 4 ). ,
,
, .
, :
byte b=3;
int i=b;

Java

Rendered by www.RenderX.com

. 4 22

b byte
i ( , int) ,
.
19 :

byte short, int, long, float, double

short int, long, float, double

char int, long, float, double

int long, float, double

long float, double

float double

, char
(byte, short) , , short char .
, char .
, , -
. ,
int float long float double.
, ,
.
:
long l=111111111111L;
float f = l;
l = (long) f;
print(l);

:
111111110656

- - ,
. .
, int 127, byte
. Java
, .. ,
.
23 :

byte char

short byte, char

char byte, short

int byte, short, char

long byte, short, char, int

Java

Rendered by www.RenderX.com

( )

float byte, short, char, int, long

double byte, short, char, int, long, float

. 5 22

,
, .
:
print((byte)383);
print((byte)384);
print((byte)-384);

:
127
-128
-128

, ,
- (384 -384) .
, ,
.
char:
char c=40000;
print((short)c);

:
-25536

.
.
long,
long, int ( byte, short, char int).
,
.
, 3.84 3, -3.84 -3.
:

NaN, 0
(.. int long);


,
(.. int long);

, ,
(.. int
long), , ,

Java

Rendered by www.RenderX.com

. 6 22

.
,
.

, ,
int byte, short char.

:
float fmin = Float.NEGATIVE_INFINITY;
float fmax = Float.POSITIVE_INFINITY;
print("long: " + (long)fmin + ".." + (long)fmax);
print("int: " + (int)fmin + ".." + (int)fmax);
print("short: " + (short)fmin + ".." + (short)fmax);
print("char: " + (int)(char)fmin + ".." + (int)(char)fmax);
print("byte: " + (byte)fmin + ".." + (byte)fmax);

:
long: -9223372036854775808..9223372036854775807
int: -2147483648..2147483647
short: 0..-1
char: 0..65535
byte: 0..-1

long int -
.
(short, char, byte) ,
int, . ,
, . ,
1000..000 ( 32 int,
31 ). - 1111..111 (32 ).
0, 3
. ,
1. byte short -1,
char - , 65.535.
, char . ,
-
. 2 :
float f=2e9f;
print((int)(char)f);
print((int)(char)-f);

Java

Rendered by www.RenderX.com

( )

. 7 22

:
37888
27648

char
. , char int ,
, , .
, boolean
.

2.3. ( )
.
.
:
// Parent
class Parent {
int x;
}
// Child,
// Parent
class Child extends Parent {
int y;
}
//
// Parent - Child2
class Child2 extends Parent {
int z;
}

.
, .
3 3 . Parent
x, Parent
. Child y x,
Parent. , Child
Parent. :
Parent p = new Child();

, p x
. y , ,
p.y, , p Child
. ,
Java

Rendered by www.RenderX.com

. 8 22

Parent, y,
.
, Child2 z x,
Parent. , Child2
Parent.
, Parent
, Child Child2 -
.
.
, ..
. (Child,
Child2) (Parent) , .
, JVM
, ,
: , ,
.
Parent p1=new Child();
Parent p2=new Child2();

Parent , ,
. ,
.
,
. , , , y Child ,
, .
. Child, .
, .
.
,
, , , .
:

A B, A B (
Object);

null- .

:
Parent p=null;

null - ,
null-. ,
.
( )
.

Java

Rendered by www.RenderX.com

. 9 22

, , ,
. ,
Parent, , Child,
, , .
. Parent
Parent Child2, Child ,
y, Child.
,
. JVM .
, . - .
Parent p=new Child();
Child c=(Child)p; // .
Parent p2=new Child2();
Child c2=(Child)p2; // !

, ,
instanceof:
Parent p=new Child();
if (p instanceof Child) {
Child c = (Child)p;
}
Parent p2=new Child2();
if (p2 instanceof Child) {
Child c = (Child)p2;
}
Parent p3=new Parent();
if (p3 instanceof Child) {
Child c = (Child)p3;
}

. ,
. if ,
.
:

A B, B A (
Object );

( )
.

2.4.
. ,
.. String. ,
, boolean, ,
, .

Java

Rendered by www.RenderX.com

. 10 22

, :

.
, .
-,
toString().
, JVM
.

"true" "false" .

toString(). null,
"null".

null- "null".

2.5.
. ,
: ,
- ( ).
- boolean , boolean (
- ). , ,
, . ,
, Child
Child2 . , Child ,
Child .
, Child2.
. ,
, ,
.
.
,
.

3.
, , ,
.
:

(assignment).
- ,
.

.
. , .
.
.

Java

Rendered by www.RenderX.com

. 11 22

. ,
.
. .

(numeric promotion).
(). -
(promotion), ,
.

3.1.

. ,
. .
, .
, ,
:
//
//
//
Parent p = 3;
// -
Long l=5L;
//
// +
String s=true;

, (
), , :
int i=10;
long l=i;
Child c = new Child();
Parent p=c;

, ,
:
//
int i=10;
short s=i; // ! !
Java

Rendered by www.RenderX.com

. 12 22

Parent p = new Child();


Child c=p; // ! !

, :
int i=10;
short s=(int)i;
Parent p = new Child();
Child c=(Child)p;

.
,
:
byte b=1;
short s=2+3;
char c=(byte)5+'a';

byte
int, . short
int, int. ,
char 5,
byte, .
, .
byte, short char.
byte, short, char int,
, ,
, .
, :
byte b=(byte)1; //
short s=(short)(2+3); //
char c=(char)((byte)5+'a'); //
// ,
// 200 byte
byte b2=(byte)200;

3.2.
,
, .
, :
// long
void calculate(long l) {
...
}
Java

Rendered by www.RenderX.com

. 13 22

void main() {
calculate(5);
}

, int, long,
.
,
. , .
//
void calculate(long l) {
...
}
void main() {
calculate(new Long(5)); //
}

, ,
.
void calculate(int l) {
...
}
void main() {
long l=5;
// calculate(l); // ! .
calculate((int)l); //
}

, , ,
.
, ,
byte, short, char int byte,
short char. .
:
//
//
// (byte, int) (short, short)
int m(byte a, int b) { return a+b; }
int m(short a, short b) { return a-b; }
void main() {

Java

Rendered by www.RenderX.com

. 14 22

print(m(12, 2)); // !
}

, (int,
int), .
, ,
, , ,
.
, ,
.
long get() {
return 5;
}

return int, ,
, long.
, .
,
:
short get(Parent p) {
return 5+'A'; //
}
void main() {
long l = //
get(new Child()); //
}

3.3.
.
, ,
. ,
. :
(byte)5
(Parent)new Child()
(Flat)getCity().getStreet().getHouse().getFlat()

,
. ,
, .
. ,
. , null
.
- .
Java

Rendered by www.RenderX.com

. 15 22

Child c=new Child();


// Child2 c2=(Child2)c; //
Parent p=c; //
Child2 c2=(Child2)p; //

, , ,
. "" .

3.4.
.
, . String
, . ,
String.
, String .
,
" ".
:
int i=1;
double d=i/2.;
String s="text";
print("i="+i+", d="+d+", s="+s);

:
i=1, d=0.5, s=text

3.5.
, ,
() 32 64 .
,
.
.

3.5.1.
byte, short char int
.
:

+ -;

~;

<<, >>, >>>.

Java

Rendered by www.RenderX.com

. 16 22

, ,
. ,
5<<3L int. , int long.

.

3.5.2.
double
int, long, float, double .
, ,
:

double, double;

, float, float;

, long, long;

int.

+, -, *, /, %;

<, <=, >, >=, ==, !=;

&, |, ^;

? :.

4.
, ,
.
, : ,
, .
. ,
.
, .
.
, .
:
byte b=3;
char c='A'+3;
long m=b+c;
double d=m-3F;

Java

Rendered by www.RenderX.com

. 17 22

b byte
int. c char ,
,
int. l int
long. , d double,
, float.
. -, , , ,
. (
, ).
, null.
, , ,
.
, ?
- , , ,
, . ,
. , -
. . ,
,
- . .
: A ,
A .
Point p = new Point();

,
.
Parent p = new Child();

, Child Parent.
p, , ,
Child, ,
Parent. , Child newChildMethod(),
p.newChildMethod() .
, ,
- Parent.
, ,
:
((Child)p).newChildMethod();

Child.
JVM , , p
Child. . Child,
newChildMethod(), ,
.
Java

Rendered by www.RenderX.com

. 18 22

- Object
.
, ( , , )
, ,
.

null

-

Object

null

5.

Java.
, ,
, , .
Java,
. 7 ,
. 4
. ,
, ,
. ,

. .
Java .
,
. -, ,
. .
,
.
.
.

6.
7-1.

, ,
?
byte b=1;
long m=-b;
Object o==;

Java

Rendered by www.RenderX.com

. 19 22

print(m+o+m);

a.) . :

7-2.

: , int byte

:
byte int, int long

: String Object

: : Object String long String


( Long).

?
float f = -16777217;

a.) . 16777217 1000000000000000000000001


, 25 . float 24
( ), .

1000000000000000000000000, 16777216 .
, . (

.)
7-3.

? ,
?
byte b=100-100;
byte b=100+100;
byte b=100*100;

a.) 0,
byte, . 2 3
byte ( 127),
.
7-4.

x ?
x==-x

a.) :

int long. ,
int 2147483648

0.0 0.0
Java

Rendered by www.RenderX.com

. 20 22

7-5.

d ?
(short)d==(short)(int)d
(int)d==(int)(long)d

a.) , short,
int.
, ,
d, , int.
231-1,
, 32:
double d=3e9;
System.out.println((int)d);
System.out.println((int)(long)d);

:
2147483647
-1294967296

7-6.

?
Object o = (String)null;
String s = o;

a.) . null , 2
(Object) String.
:
String s = (String)o;

7-7.

Wolf Rabbit Animal.


?
Wolf w = new Wolf();
Animal a = (Animal)w;
Rabbit r = (Rabbit)a;

a.) ,
. ,
Wolf, .
Wolf
Rabbit ,
.
7-8.

Java

Rendered by www.RenderX.com

. 21 22

a.) .
7-9.

?
public int add(byte a, byte b) {
short x=(short)a;
char y=(char)b;
return x+y;
}

a.) :

: byte short

: byte char

:
: short char int

7-10. ?
char c=65;
print(c);
print(+c);
print(=+c);

a.) :
A
65
=A

char,
. ,
int.
char String,
.
7-11. ?
byte b=1+2;

a.) ,
, , byte.
int.
7-12. ?
Object o = 123;
Child c = new Child();
Parent p=(Parent)new Child();

Java

Rendered by www.RenderX.com

. 22 22

Child x=null;

a.) :

String

Child

Child

null

Java

Rendered by www.RenderX.com

Java
8. Java
20 2003
:
( Sun ) <vyazovick@itc.mipt.ru>
( Sun ) < gene@itc.mipt.ru>
Copyright 2003 Sun , , .


Java Java,
, , ,
. , Java
.
,
.
, .

Rendered by www.RenderX.com

ii

8. Java................................................................................. 1
1. .......................................................................................................................... 1
2. ....................................................................................................1
3. this super...........................................................................................5
4. abstract................................................................................................. 8
5. ...................................................................................................................10
5.1. ................................................................................... 10
5.2. ......................................................................................11
5.3. ................................................................................... 13
6. ................................................................................................................ 14
6.1. .......................................................................................................................15
6.2. .................................................................................................................. 17
6.3. ..................................................................................... 20
7. .................................................................................................................... 21
8. ...................................................................................................22

Java

Rendered by www.RenderX.com

. 1 27

8.
Java
.
1. ......................................................................................................................... 1
2. ...................................................................................................1
3. this super.......................................................................................... 5
4. abstract................................................................................................ 8
5. .................................................................................................................. 10
5.1. ......................................................................................... 10
5.2. ............................................................................................11
5.3. ......................................................................................... 13

6. ............................................................................................................... 14
6.1. .............................................................................................................................15
6.2. ........................................................................................................................ 17
6.3. ........................................................................................... 20

7. ................................................................................................................... 21
8. .................................................................................................. 22

1.
,
, .
Java,
- .

2.
,
. :
class Human {

Java

Rendered by www.RenderX.com

. 2 27

private String name;


}

name
Human, , -
.
. ,
( Human, ). ,
- ,
. " " " ".
static:
class Human {
public static int totalCount;
}

, ,
:
Humans.totalCount++; //

:
Human h = new Human();
h.totalCount=100;

. ,
h Human,
:
Human.totalCount=100;

, :
Human h = null;
h.totalCount+=10;

null, .
. ,
:
Human h1 = new Human(), h2 = new Human();
Human.totalCount=5;
h1.totalCount++;
System.out.println(h2.totalCount);

totalCount ,
6.

Java

Rendered by www.RenderX.com

. 3 27

, ,
.
.
class Human {
private static int totalCount;
public static int getTotalCount() {
return totalCount;
}
}

.
Human.getTotalCount();

,
:
Human h=null;
h.getTotalCount(); //
Human.getTotalCount(); //

,
,
.
,
. ,
main() , .
.
, .
.
static:
class Human {
static {
System.out.println("Class loaded");
}
}

,
.
,
, :
class Test {

Java

Rendered by www.RenderX.com

. 4 27

static int a;
static {
a=5;
// b=7; // !
}
static int b=a;
}

.
, (
), :
class Test {
static int b=Test.a;
static int a=3;
static {
System.out.println("a="+a+", b="+b);
}
}

, :
a=3, b=0

, b a, .. 0.
a 3.
final, ,
,
. , final, ,
-.

. -
. ,
, .
.
,
. , ,
, .
, . ,
, main() ,
. , , MyClass.staticMethod(),
MyClass .
Math , .
,
. .

Java

Rendered by www.RenderX.com

. 5 27

,
..
class Test {
public void process() {
}
public static void main(String s[]) {
// process(); - ! ?
Test test = new Test();
test.process(); //
}
}

3. this super
,
. .
, ,
. this
:
class Test {
public Object getThis() {
return this; // ,
}
public static void main(String s[]) {
Test t = new Test();
System.out.println(t.getThis()==t); //
}
}

:
true

, this ,
. , , ,
- .
class Human {
public static void register(Human h) {
System.out.println(h.name+" is registered.");
}
private String name;
Java

Rendered by www.RenderX.com

. 6 27

this super

public Human (String s) {


name = s;
register(this); //
}
public static void main(String s[]) {
new Human("John");
}
}

:
John is registered.

this "" :
class Human {
private String name;
public void setName(String name) {
this.name=name;
}
}

this , :
class Test {
// int b=a; !
int b=this.a;
int a=5;
{
System.out.println("a="+a+", b="+b);;
}
public static void main(String s[]) {
new Test();
}
}

:
a=5, b=0

, - b
a, .. , a 5.
, this
. super,
.

Java

Rendered by www.RenderX.com

. 7 27

super
. , (overriding)
.
,
.
class Parent {
public int getValue() {
return 5;
}
}
class Child extends Parent {
//
public int getValue() {
return 3;
}
public static void main(String s[]) {
Child c = new Child();
//
System.our.println(c.getValue());
}
}

,
. ,
3. , Child, getVaue()
5, .
,
. , ,
.
, - ,
. super.
:
class Parent {
public int getValue() {
return 5;
}
}
class Child extends Parent {
//
public int getValue() {
Java

Rendered by www.RenderX.com

. 8 27

abstract

//
return super.getValue()+1;
}
public static void main(String s[]) {
Child c = new Child();
System.our.println(c.getValue());
}
}

6.
super
, .. , .
, ,
.
this super , ..
, .

4. abstract
, - abstract.
, ,
, . ,
, .
. , ,
, . ,
- , , ..; - ,
.. . ,
, . ,
, , , (
paint()) -.
. ,
.
, , ,
.. ,
, , .. ,
,
, .
?
- , . paint()
.
, ,
.
.
, , .
Java

Rendered by www.RenderX.com

. 9 27

, ,
, .
:
//
abstract class Operation {
public abstract int calculate(int a, int b);
}
//
class Addition {
public int calculate(int a, int b) {
return a+b;
}
}
//
class Subtraction {
public int calculate(int a, int b) {
return a-b;
}
}
class Test {
public static void main(String s[]) {
Operation o1 = new Addition();
Operation o2 = new Subtraction();
o1.calculate(2, 3);
o2.calculate(3, 5);
}
}

, main()
.
- ,
. , ,
. ,
, . .
, ,
, .
abstract ,
. - (implements)
( ) ,
.
, abstract final. .
, private, native, static.
Java

Rendered by www.RenderX.com

. 10 27

.
abstract class Test {
public abstract int getX();
public abstract int getY();
pulic double getLength() {
return Math.sqrt(getX()*getX()+getY()*getY());
}
}

, getLength() .
,
Test, .
.
null ,
.

5.

. Java ,
,
. , ,
, ?
, ?
,
. ,
, ,
.
Java. ,
.

5.1.
.
. .
public, ,
,
. abstract ,
, ,
, .
interface .
extends ,
. ,

Java

Rendered by www.RenderX.com

. 11 27

, ,
.
. ,
A B, B A, C
. , , A ,
B.
.
public interface Drawble extends Colorable, Resizable {
}

, -
.
public final static,
, .
, .
public
int
int
int
int
}

interface Directions {
RIGTH=1;
LETFT=2;
UP=3;
DOWN=4;

public abstract,
.
public interface Moveable {
void moveRight();
void moveLeft();
void moveUp();
void moveDown();
}

, , .

5.2.
.
,
,
.
,
, . ,
, :
interface A {
Java

Rendered by www.RenderX.com

. 12 27

int getValue();
}
interface B {
double getValue();
}

, ,
. ,
.
, .
- :
interface A {
int value=3;
}
interface B {
double value=5.4;
}
class C implements A, B {
public static void main(String s[]) {
C c = new C();
// System.out.println(c.value); - !
System.out.println(((A)c).value);
System.out.println(((B)c).value);
}
}

, ,
, .
.
, implements ,
. ,
.
A B, A, ,
B -
- A, .
, C1 C2, C2 A1,
A1 A2, C1
A2.
, .
null , ,
. ,
Object, ,
Object.
Java

Rendered by www.RenderX.com

. 13 27

5.3.
- ,
, . ,
.
, - ,
, , .
, ,
, ,
.
.
. , .
,
, .
- . ,
,
.
,
. ,
, . ,
- , , ,
, - . , , ""
-.
(, consumeInsect(Insect))
. , ,
- -
, , - .
Java . InsectConsumer:
public interface InsectConsumer {
void consumeInsect(Insect i);
}

:
//
public class Sundew extends Plant implements InsectConsumer {
public void consumeInsect(Insect i) {
...
}
}
//
public class Swallow extends Bird implements InsectConsumer {
public void consumeInsect(Insect i) {
...

Java

Rendered by www.RenderX.com

. 14 27

}
}
//
public class AntEater extends Mammal implements InsectConsumer {
public void consumeInsect(Insect i) {
...
}
}

, ,
:
// , ,
class FeedWorker extends Worker {
//
// , ,
public void feedOnInsects(InsectConsumer consumer) {
...
consumer.consumeInsect(insect);
...
}
}


, . ,
,
, .
, ( )
( ).
.
, ,
.

6.
.
.
.

. ,
.

Java

Rendered by www.RenderX.com

. 15 27

6.1.
-, , .
, . , ,
. , Child
,
, ( ),
.
, :
Child c = new Child();
System.out.println(c.a);
Parent p = c;
System.out.println(p.a);

, Child,
, - Parent. :
3
2

- "" .
- "" (hiding). ,
"" (shadowing) "" (obscuring) .
, , .
:
class Child extends Parent {
int a=3; //
int b=((Parent)this).a; //
int c=super.a; //
}

b c , a.
super ,
. ,
, .
, b.
:
class Parent {
int x=0;
public void printX() {
System.out.println(x);
}

Java

Rendered by www.RenderX.com

. 16 27

}
class Child extends Parent {
int x=-1;
}

?
new Child().printX();

?
Child, . , Parent,
, , x
Parent. 0.
. , ,
, .
:
class Parent {
static int a=2;
}
class Child extends Parent {
static int a=3;
}

?
Child c = new Child();
System.out.println(c.a);
Parent p = c;
System.out.println(p.a);

,
. , .
, null. .
:
System.out.println(Child.a);
System.out.println(Parent.a);

:
3
2

. ,
. - (hiding)
Java

Rendered by www.RenderX.com

. 17 27

.
, .
:
class Parent {
static int a;
}
class Child extends Parent {
}

?
Child.a=10;
Parent.a=5;
System.out.println(Child.a);

a Child.
, :
5

, ,
.
, ,
. .
, ,
.

6.2.
(overriding) :
class Parent {
public int getValue() {
return 0;
}
}
class Child extends Parent {
public int getValue() {
return 1;
}
}

, :
Child c = new Child();
Java

Rendered by www.RenderX.com

. 18 27

System.out.println(c.getValue());
Parent p = c;
System.out.println(p.getValue());

:
1
1

, , 0
, Child.
- ,
. , ,
, -
super.
:
class Parent {
public int getValue() {
return 0;
}
public void print() {
System.out.println(getValue());
}
}
class Child extends Parent {
public int getValue() {
return 1;
}
}

?
Parent p = new Child();
p.print();

Parent print(), Parent.


getValue(), Parent 0.
,
.
, . Child,
getValue().
:
1

,
. ,
Java

Rendered by www.RenderX.com

. 19 27

(, null ,
),
, , . ,
.
, , ,
throws-. ( ) ,
. ,
.
.
class Parent {
protected int getValue() {
return 0;
}
}
class Child extends Parent {
/* ??? */ protected int getValue() {
return 1;
}
}

protected. ,
, (public)
( )? :
Parent p = new Child();
p.getValue();

Parent.
, . , Child,
. ,
, . ,
, protected public. protected-
public, public
.
private-, , ,

, ..
throws-,
.
, ,
(implements). ,
.
(),

Java

Rendered by www.RenderX.com

. 20 27

throws-. ,
.
. :
class Parent {
static public int getValue() {
return 0;
}
}
class Child extends Parent {
static public int getValue() {
return 1;
}
}

, :
Child c = new Child();
System.out.println(c.getValue());
Parent p = c;
System.out.println(p.getValue());

,
,
:
System.out.println(Child.getValue());
System.out.println(Parent.getValue());

:
1
0

, , , ,
.
, .

6.3.
, .
-, ,
. :

Java

Rendered by www.RenderX.com

. 21 27

, :
-

private-;

"" ( ,
);

( ).

-,
. , , .
,
.
, , .
:

null

null
, , :
-

( implements);
;
;
- ,

, Java ,
.
- , , ,
, , .
, ,
, ,
, .
, .
Java,
- ,
. Java
.

7.
Java. , -,
,
. , ,
, ,
.

.

Java

Rendered by www.RenderX.com

. 22 27

this super. this


, , .
, .
super ,
, .
.
, , . ,
abstract, ,
.
,
.
Java, .
, , final static.
, .
.
, .
, ,
.
.
, , ,
.
.

8.
8-1.

, , Java. ,
?

, ;

, -
;

.
a.) 1, 4, 6 ,

2, 3, 5 , ,
.

8-2.

x?

Java

Rendered by www.RenderX.com

. 23 27

public class Test {


static void perform() {
...
}
private Test x;
public static void main(String s[]) {
x.perform(); // ?
}
}

a.) , .
, , ,

, , ,
.
8-3.

?
public class Parent {
int x=2;
}
public class Child extends Parent {
int x=3;
void print(int x) {
System.out.println(x);
System.out.println(this.x);
System.out.println(super.x);
}
public static void main(String s[]) {
new Child().print(0);
}
}

a.) :
0
3
2

,
main, 0.
, Child, 3. ,

Java

Rendered by www.RenderX.com

. 24 27

,
Parent, 2.
8-4.

this?
a.) :

,
:

8-5.

perform()
super.perform()?
a.) , super.perform()
, , ,
.

8-6.


?
a.) , .

8-7.

,
?
a.) , , null, ,
-. ,
.

8-8.

,
?
a.) public final static.
public abstract.

8-9.

,
implements?
a.) , .
public abstract.

Java

Rendered by www.RenderX.com

. 25 27

8-10. - ,
?
a.) , ,
.
8-11. ?
a.) .
8-12. ?
public class Parent {
int x = 2;
public void print() {
System.out.println(x);
}
}
public class Child extends Parent {
int x = 3;
public static void main(String s[]) {
new Child().print();
}
}

a.) 2, Parent,
, .
8-13. ,
Child ?
public void print() {
System.out.println(x);
}

a.) , ,
Child,
3.
8-14. , , ?
public class Test {
public static void test(Test t) {
System.out.println(test +t);
}
public static void main(String s[]) {
Test t = null;
t.test(t);
Java

Rendered by www.RenderX.com

. 26 27

}
}

a.) , null
, .
test test null.
8-15. ? ? ,
?
a.) , .
null.
, -.
,
, .

Java

Rendered by www.RenderX.com

Java
9.
20 2003
:
( Sun ) <vyazovick@itc.mipt.ru>
( Sun ) < gene@itc.mipt.ru>
Copyright 2003 Sun , , .

Java.
,
.
Java ,
, .
. ,
Java ( ) .
,
.
Java,
,
.

Rendered by www.RenderX.com

ii

9. ..............................................................................................................1
1. .......................................................................................................................... 1
2. , Java.................................................................................... 1
2.1. ........................................................................................... 2
2.2. ...................................................................................... 4
2.3. .......................................................................................... 6
2.4. .........................................................................................................7
3. ............................................................................9
3.1. ArrayStoreException................................................................................ 10
3.2. , ........................................................... 11
4. ................................................................................................................ 12
4.1. ...................................................................................... 15
5. .................................................................................................................... 16
6. ...................................................................................................17

Java

Rendered by www.RenderX.com

. 1 21

9.
.
1. ......................................................................................................................... 1
2. , Java....................................................................................1
2.1. ................................................................................................. 2
2.2. ............................................................................................ 4
2.3. ................................................................................................ 6
2.4. ...............................................................................................................7

3. ........................................................................... 9
3.1. ArrayStoreException...................................................................................... 10
3.2. , .................................................................11

4. ................................................................................................................12
4.1. ............................................................................................ 15

5. ................................................................................................................... 16
6. .................................................................................................. 17

1.
. Java
, ,
. .
Java, , .

2. , Java
, , (arrays)
.
, - .
, , .
, .
n, ,
0 n-1. , ,
. (,
100 ), (,
100 Car).
Java

Rendered by www.RenderX.com

. 2 21

, Java

, Java char[] String


.
, .
, Java ( Java
, ), Object,
-.
. ,
.
,
- , , ..
.

2.1.
,
int
int a[];

, . ,
, .
:
int[] a;

.
:
int[] a[];

a " , int".
:
Point p, p1[], p2[][];

.
,
null ( ; ,
). ,
new,
.
int a[]=new int[5];
Point[] p = new Point[10];

, .
, ,
. ,
Java

Rendered by www.RenderX.com

. 3 21

, ,
.
int array[]=new int[5];
for (int i=0; i<5; i++) {
array[i]=i*i;
}
for (int j=0; j<6; j++) {
System.out.println(j+"*"+j+"="+array[j]);
}

:
0*0=0
1*1=1
2*2=4
3*3=9
4*4=16

,
. ,
, , ..
, , , :
int i[]=new int[5];
i[-2]=0; // !

.
,
, . ,
:
int i[]=new int[5];
...
i=new int[7]; // ,

,
.
.
,
length, . :
Point p[]=new Point[5];
for (int i=0; i<p.length; i++) {
p[i]=new Point(i, i);
}

Java

Rendered by www.RenderX.com

. 4 21

, Java

int.
byte, short char, int.
long .
, length int,
2^31-1, 2 .
, ,
Java, :

. null
, .

. null
-.

,
Object , , Object. ,
Object o = new int[4];

, Object,
:
Object arr[] = new Object[3];
arr[0]=new Object();
arr[1]=null;
arr[2]=arr; // !

2.2.
, , , ,
.
,
, 0.
boolean,
false.
for.
. ,
Point. new
Point, .
null.
:
Point p[]=new Point[5];
for (int i=0; i<p.length; i++) {
System.out.pritnln(p[i]);
}

null.
Java

Rendered by www.RenderX.com

. 5 21

, , .
, n n ,
( p[i])
.
, - .
new , ,
. ,
:
int i[]={1, 3, 5};
int j[]={}; // new int[0]

, .
,
.
, :
Point p=new Point(1,3);
Point arr[]={p, new Point(2,2), null, p};
//
String sarr[]={"aaa", "bbb", "cde"+"xyz"};

,
, , ,
.
:
public class Parent {
private String[] values;
protected Parent(String[] s) {
values=s;
}
}
public class Child extends Parent {
public Child(String firstName, String lastName) {
super(???); //
}
}

Child
. null,
.
new String[2], firstName lastName
. {firstName, lastName} ,
.
Java

Rendered by www.RenderX.com

. 6 21

, Java

:
new String[]{firstName, lastName}

, new
. .

2.3.
. ,
:
int i[][]=new int[3][5];

i ,
35. 15 ,
(0, 0) (2, 4).
:
int pithagor_table[][]=new int[5][5];
for (int i=0; i<5; i++) {
for (int j=0; j<5; j++) {
pithagor_table[i][j]=i*j;
System.out.print(pithagor_table[i][j]+ "\t");
}
System.out.println();
}

:
0
0
0
0
0

0
1
2
3
4

0
2
4
6
8

0
3
6
9
12

0
4
8
12
16

, .
, Java , ,
, , . ,
int[] " ", int[][] " ".
.
x, ,
x (, x[0][0]),
. x
, ,
.
, -
. ,
null.
Java

Rendered by www.RenderX.com

. 7 21

int x[][]=new int[3][5]; //


x[0]=new int[7];
x[1]=new int[0];
x[2]=null;

, x
. ,
null.
, new int[3][5].
: (1 ) 3 ,
5 (3 ). , 4 .
3 ( )
.
:
int x[][]=new int[3][];

- , null.
, , x.length
3 - . x[i].length
, i
x.length, x[i] null.
.
new
, .
,
. ,
null,
. ,
.
, .
, :
int i[][] = {{1,2}, null, {3}, {}};

4 . , -, 4, , 3 2, 1, 0 .
,
, .

2.4.
,
, .
- . ,
Java

Rendered by www.RenderX.com

. 8 21

, Java

,
, .
,
Class,
.
,
Element.
,
.
, . .., Element public-,
public. public.
final,
.
, , ..
,
.
.
Object. , .
Cloneable Serializable.
, .
public final length int.
clone() Cloneable.
:
[public] class A implements Cloneable, java.io.Serializable {
public final int length; //
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError(e.getMessage());
}
}
}

, , , ,
, Object, , toString(), hashCode()
.
:
// toString()
System.out.println(new int[3]);
System.out.println(new int[3][5]);
System.out.println(new String[2]);

Java

Rendered by www.RenderX.com

. 9 21

// hashCode()
System.out.println(new float[2].hashCode());

:
[I@26b249
[[I@82f0db
[Ljava.lang.String;@92d342
7051261

3.
, Java, ,
.
(
) .
, -
.
,
.
Object Cloneable Serializable.
3 , ,
. ,
. , ,
, ,
, .
, ,
, ,
.
. ,
, Child, ,
Parent.
Child c[] = new Child[3];
Parent p[] = c;

, : , A,
, B, A B.
// :
B b = (B) new A();
// :
B b[]=(B[]) new A[3];

Java

Rendered by www.RenderX.com

. 10 21

.
, Child[][] Parent[][],
(Child[] Parent[]) ( Child Parent
).
, ( ),
- .
, .
, ,
. ,
. ,
. , :
//
byte b[]={1, 2, 3};
int i[]=b;

, b[0] i[0] .

. ,
.
.
new.
, , .
,
, System.arrayCopy(),
.

3.1. ArrayStoreException
, ,
, .
:
Child c[] = new Child[5];
Parent p[]=c;
p[0]=new Parent();

.
. Parent
.
. ,
, .
"", .
, Child
Parent, .

Java

Rendered by www.RenderX.com

. 11 21

, ,
:
c[0].onlyChildMethod();

onlyChildMethod() Child.
, , c[0] ,
Child.
, ,

. , ,
,
. , , ArrayStoreException.
, -
?
. :
public void process(Parent[] p) {
if (p!=null && p.length>0) {
p[0]=new Parent();
}
}

,
if-.
:
process(new Child[3]));

ArrayStoreException.

3.2. ,
, ,
, .
, , , .

, null.
:

null;

, ;

, ,
.

Java

Rendered by www.RenderX.com

. 12 21


.
Object.
, , .
:

null

null

,
: -
A,
B , B
A.

Object

null
,

4.
, ,
, ,
. , , , x,
, x.clone(),
x != x.clone()

,
x.clone().getClass() == x.getClass()

, ,
x.equals(x.clone())

. clone()
, :

, , ,
(, private);

, ,
, ,
, ;

,
. - ,
;

Java

Rendered by www.RenderX.com

. 13 21

, ,
.

.
Object clone(). :
protected native Object clone() throws CloneNotSupportedException;

. .
-,
, ,
. ,
, ,
, .
clone()
Object. , native, ,
. ,
JVM, .
clone() ,
.
Object.clone(),
Cloneable. ,
, .
,
CloneNotSupportedException
.
Cloneable ,
, .
, .
, , , ,
. .
, Object Cloneable,
new Object().clone() .
clone() ,
super.clone().
:

public;

CloneNotSupportedException;

, Cloneable , ,
.
, ,
. :
Java

Rendered by www.RenderX.com

. 14 21

public class Test implements Cloneable {


Point p;
int height;
public Test(int x, int y, int z) {
p=new Point(x, y);
height=z;
}
public static void main(String s[]) {
Test t1=new Test(1, 2, 3), t2;
try {
t2=(Test) t1.clone();
} catch (CloneNotSupportedException e) {}
t1.p.x=-1;
t1.height=-1;
System.out.println("t2.p.x=" + t2.p.x + ", t2.height=" + t2.height);
}
}

:
t2.p.x=-1, t2.height=3

,
. .
,
Point. , ,
.
, clone() Test.
public Object clone() {
Test clone=null;
try {
clone=(Test) super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError(e.getMessage());
}
clone.p=(Point)clone.p.clone();
return clone;
}

, Object.clone()
Test, , ,
.
Object, .

Java

Rendered by www.RenderX.com

. 15 21

main :
public static void main(String s[]) {
Test t1=new Test(1, 2, 3);
Test t2=(Test) t1.clone();
t1.p.x=-1;
t1.height=-1;
System.out.println("t2.p.x=" + t2.p.x + ", t2.height=" + t2.height);
}

:
t2.p.x=1, t2.height=3

, .
"" Object.clone() ,

,
, .
, ,
Cloneable, . ,
.

4.1.
, .
, - , Object.clone() .
:
int a[]={1, 2, 3};
int b[]=(int[])a.clone();
a[0]=0;
System.out.println(b[0]);

, ,
, . :
int a[][]={{1, 2}, {3}};
int b[][]=(int[][]) a.clone();
if (...) {
// :
a[0]=new int[]{0};
System.out.println(b[0][0]);
} else {
// :
a[0][0]=0;

Java

Rendered by www.RenderX.com

. 16 21

System.out.println(b[0][0]);
}

, . ,
, 2 , 3 . ,
,
.
.
, ,
. 1.
,
. 0.
, if-else, ,
, , 1,
,
.
, Java ,
, .
,
.

5.
Java.
, .
, Java . ,
, , ,
, 0 .
, . ,
,
.
new, ,
, .
, .
(0, false, null).
Java . , ,
, .
.
, .
,
. .
, Object . ,
, .
.

Java

Rendered by www.RenderX.com

. 17 21

ArrayStoreException,
.

.
, , Java
, ,
Cloneable.
,
.

6.
9-1.

?
int x[], y[][];
byte[] a, b[][];
String s, s1[], s2={{}, {a, b}, null};

a.) :

9-2.

x int[], y int[][]. ,
.

a byte[], b byte[][][].
, .

s , s1 String[], s2 String[][].
s2, 3.
0, 2,
- null.

, , ,
?
int b[]=new int[5];
for (int i=1; i<=b.length(); i++) {
b[i]=Math.sqrt(i);
}

a.) , . -,
length(), length. -, 3-
double int
Math.sqrt .
,
.
,
5,

Java

Rendered by www.RenderX.com

. 18 21


, 4.
, , 1,
0.
9-3.

? ? ,
?
a.) . ,
,
.

9-4.

, ,
?
int x[][]=new int[2][3];

a.) :
new int[][]{{0, 0, 0}, {0, 0, 0}}

9-5.

? , ?
byte b[]={1, 2, 3};
Object o=b;
o=new String[]{, a, b};
String s[]=o;

a.) . 4 Object
String[]. :
String s[]=(String[])o;

9-6.

new int[3][4]? new


int[3][][]?
a.) 3 4
, 4 .
1 ,
null, 1 .

9-7.

? ?

?
a.) java.lang.Object.
2 java.lang.Cloneable java.io.Serializable.

Java

Rendered by www.RenderX.com

. 19 21

public final int length


public Object clone().
9-8.

, ?
a.) -,
.
-, , A ( , A[])
B[], , A B.
, A B ,
(
).

9-9.

,
int[][] byte[][] ,
.
?
a.) . ,
int[] byte[],
.

9-10. ArrayStoreException ?
public void setCars(Car c[]) {
c[0]=new Car();
}
public void setCars2(Car c[]) {
if (c[0] instanceof Car) {
c[0]=new Car();
}
}
public void setNumbers(int x[]) {
x[0]=0;
}

a.) setCars setCars2,


, - Car.
, , instanceof
true.
,
, .
9-11. ?
public class Point {
private int x, y;

Java

Rendered by www.RenderX.com

. 20 21

public Point(int nx, int ny) {


x=nx;
y=ny;
}
public Object clone() {
return new Point(x, y);
}
}

a.) , clone .
, Cloneable,
Object.clone(),
.
9-12.
JVM?
a.) .
9-13. ?
Point p1[][]={null, {new Point(1, 1)}};
Point p2[][] = (Point[][])p1.clone();
p2[0]= new Point[]{new Point(2, 2)};
System.out.println(p1[0][0]);

a.) ,
p2,
(p1) null. ,
p1[0][0] (NullPointerException).

Java

Rendered by www.RenderX.com

Java
10. .

20 2003
:
( Sun ) <vyazovick@itc.mipt.ru>
( Sun ) < gene@itc.mipt.ru>
Copyright 2003 Sun , , .

Java,
, ,
. ,
, , , , break
continue .
Java,
, .
, , .

, .

Rendered by www.RenderX.com

ii

10. ...........................................................................1
1. ..................................................................................... 2
2. .................................................. 2
3. .................................................................................. 3
4. ............................................................................................................ 6
5. .............................................................................................................................. 6
6. if ..................................................................................................................... 7
7. switch ............................................................................................................. 9
8. ....................................................................................................12
8.1. while ............................................................................................................ 13
8.2. do ................................................................................................................ 15
8.3. for ................................................................................................................ 15
9. break continue ........................................................................................18
9.1. continue .............................................................................................. 18
9.2. break ................................................................................................... 19
10. .................................................................................................. 20
11. return ..........................................................................................................23
12. synchronized ..............................................................................................23
13. . (Exceptions). ................................... 23
13.1. .....................................................................24
13.2. ............................................................ 25
13.2.1. try-catch ...............................................................................25
13.2.2. try-catch-finally ..................................................................... 26
13.3. throw ..................................................................... 29
13.4. ................................... 31
13.5. ..........................................34
13.6. ........................................................36
13.7. ...................................................................................................37
14. .................................................................................................................. 41
15. .................................................................................................42

Java

Rendered by www.RenderX.com

. 1 51

10.

.
1. .................................................................................... 2
2. ..................................................2
3. ................................................................................. 3
4. ........................................................................................................... 6
5. ............................................................................................................................. 6
6. if .................................................................................................................... 7
7. switch ............................................................................................................ 9
8. ................................................................................................... 12
8.1. while ..................................................................................................................13
8.2. do ...................................................................................................................... 15
8.3. for ......................................................................................................................15

9. break continue ....................................................................................... 18


9.1. continue .................................................................................................... 18
9.2. break ......................................................................................................... 19

10. ................................................................................................. 20
11. return .........................................................................................................23
12. synchronized ............................................................................................. 23
13. . (Exceptions). .................................. 23
14. ................................................................................................................. 41
15. ................................................................................................ 42

Java

Rendered by www.RenderX.com

. 2 51

1.

.
.
,
, ,
.
.
.

2.
,
( ).
,
brake
continue
return

(
, ).
, ,
. .
throw,
, (
) .
.

break ( )

break ( )

continue ( )

continue ( )

return ( )

return ( )

throw Exception,
Java.

().
, ..

.
Java

Rendered by www.RenderX.com

. 3 51

, ,
. (..
)
,
, (
, )

3.
,
.
, .
this
.
1. public class Test {
2.
static int x;
3.
public Test() {
4.
}
5.
public static void main(String[] args) {
6.
Test t = new Test();
7.
lbl: {
8.
int x = this.x;
9.
if ( x > 0) break lbl;
10.
}
11.
}
12. }

18 . int x = x;,
. (..
). int x = (x=2)x;
, .
() , .
- () ,
.
.
.
public class Test {
public Test() {
}
public static void main(String[] args) {
Test t = new Test();
int x;
lbl: {
Java

Rendered by www.RenderX.com

. 4 51

int x = 0;
System.out.println("X = " + x);
}
}
}

,
-. , .
public class Test { static int x = 5; public Test() { } public static void main(String[] args) { Test t =
new Test(); int x = 1; System.out.println("X = " + x); } }
X = 1. ,
, ,
.
.
public class Test {
static int x;
public Test() {
}
public static void main(String[] args) {
Test t = new Test();
t.test(5);
System.out.println("Member value x = " + x);
}
private void test(int x){
this.x = x + 5;
System.out.println("Local value x = " + x);
}
}

.
Local value x = 5
Member value x = 10

,

.
public class Test {
static int x = 5;
public Test() {
}
public static void main(String[] args) {
Test t = new Test();
{
int x = 1;
System.out.println("First block x = " + x);
Java

Rendered by www.RenderX.com

. 5 51

}
{
int x = 2;
System.out.println("Second block x =" + x);
}
System.out.print("For cycle x = ");
for(int x =0;x<5;x++){
System.out.print(" " + x);
}
}
}


:
First block x = 1
Second block x =2
For cycle x = 0 1 2 3 4

, .
,
.
.

public class Test {
static int x = 5;
public Test() {
}
public static void main(String[] args) {
Test t = new Test();
int x;
int y = 5;
if( y > 3) x = 1;
System.out.println(x);
}
}

, .. , x
. ( ,
if(y > 3) x = 1; )

Java

Rendered by www.RenderX.com

. 6 51

4.
; . ,
.
.

5.
.
break continue.
, .
.
public class Test {
static int x = 5;
static {
}
public Test() {
}
public static void main(String[] args) {
Test t = new Test();
int x = 1;
Lbl1:{
if(x == 0) break Lbl1;
}
Lbl2:{
if(x > 0) break Lbl1;
}
}
}

,
.
.
public class Test {
static int x = 5;
static {
}
public Test() {
}
public static void main(String[] args) {
Test t = new Test();
int L2 = 0;
Java

Rendered by www.RenderX.com

. 7 51

Test: for(int i = 0; i< 10;i++) {


test: for(int j = 0; j< 10;j++) {
if( i*j > 50) break Test;
}
}
}
private void test(){
;
}
}

,
, .
, ,
, . Java
, goto . (
) , , ,
.

6. if
, Java,
, .
:
if ( ) 1
else 2

,
. C,
,
, . Java
.
,
1, 2.
(else) . .. if(x = 5)
System.out.println("Five") .
if-else . . if else.
String test = "smb";
if( test.equals("value1"){
.
} else if (test.equals("value2"){

} else if (test.equals("value3"){

Java

Rendered by www.RenderX.com

. 8 51

if

} else {

, else if.
else ,
. else
if b, ,
. ,
.
:

int x = 5;
if( x < 4){
System.out.println(" 4");
} else if (x > 4){
System.out.println(" 4");
} else if (x == 5){
System.out.println(" 4");
} else{
System.out.println(" ");
}

" 4" .
,
.

int x = 0;
if(x) .

.

int x = 0;
if( x = 5) .

.
(short circuit)
.

if( null == stringVal || "" == stringVal )
System.out.println(" stringVal ")

Java

Rendered by www.RenderX.com

. 9 51

.
if( null == stringVal | "" == stringVal )
System.out.println(" stringVal ")

, stringVal,
(null) .
,
.

if( x = true)

, ,
. ( ,
)

if( true = x)

7. switch
switch() .
.
:
switch(int value){
case const1:

case const2:

case constn:

default:

}

default
switch byte, short, int,
char .
. case
long Long, String, Integer, Byte ..

Java

Rendered by www.RenderX.com

. 10 51

switch

switch
x case
. ,
,
case. , case, ,
switch.
case, default,
switch. default , case ,
switch .
case , switch ,
. , ,
, ,
break.
case ,
32 . ,
final static.
, break

switch(). .
default.

int x = 2;
switch(x){
case 1:
case 2:
System.out.println(" 1 2");
break;
case 2:
case 3
System.out.println(" 2 3");
break;
default:
System.out.println(" ");
}

1 2.
break, .
.
int x = 5;
switch(x){
case y:

break;
}
Java

Rendered by www.RenderX.com

. 11 51

switch() ,
.
float x = 1.0f;
int y = 4;
switch(x*y){
case 10:

break;
case 20:

break;
default:

.
. switch()
byte short, case
, .
:
byte x = 5;
switch(x){
case 1:

break;
case 132:

break;
default:

. case 132 ,
byte; default
switch case.
case

public class Test {


static int x = 5;
static {
}
public Test() {
}
public static void main(String[] args) {
Java

Rendered by www.RenderX.com

. 12 51

Test t = new Test();


int x = 5;
switch(x){
case 1:
System.out.println("One");
break;
case 2:
System.out.println("Two");
break;
default:
case 3:
System.out.println("Tree or other");
}
}
}

Tree or other

switch case .
..
switch(x){
case 1:
System.out.println("One");
break;
case 1:
System.out.println("Two");
break;
case 3:
System.out.println("Tree or other value");
}

.
switch default.
switch if else,
.. switch .

8.
Java .

while

do

for

Java

Rendered by www.RenderX.com

while

. 13 51

8.1. while
while
while( )
;

,
, .

continue, continue
. continue
while, .
while, .

break,

(
), while .


public class Test {
static int x = 5;
static {
}
public Test() {
}
public static void main(String[] args) {
Test t = new Test();
int x = 0;
while(x < 5){
x++;
if(x % 2 == 0) continue;
System.out.print(" " + x);
}
}
}


1 3 5

.. .
public class Test {

Java

Rendered by www.RenderX.com

. 14 51

static int x = 5;
static {
}
public Test() {
}
public static void main(String[] args) {
Test t = new Test();
int x = 0;
int y = 0;
lbl: while(y < 3){
y++;
while(x < 5){
x++;
if(x % 2 == 0) continue lbl;
System.out.println("x=" + x + " y="+y);
}
}
}
}


x=1 y=1
x=3 y=2
x=5 y=3

.. if(x % 2 == 0) continue lbl; x ,


y .
,
while(), . ..
, , ..
,
, while()
while()
int i = 0;
while( i++ < 5){
System.out.println("Counter is " + i);
}

, while(), ,
, . ..
, , while() .
boolean b = false;
while(b){

Java

Rendered by www.RenderX.com

do

. 15 51

System.out.println("Executed");
}

System.out.println("Executed"); .

8.2. do
do
do
;
while( )

while do, ,
. , do
.
.
, ,
, , .
while(). .
boolean b = false;
int counter = 0;
do{
counter++;
System.out.println("Counter is " + counter);
}while(b);
do
int counter = 0;
do{
counter ++;
System.out.println("Counter is " + counter);
}while(counter > 5);

do while.

8.3. for
, -
,
.
for.

Java

Rendered by www.RenderX.com

. 16 51

for :
for( ; ; )
;

- .
(,
)

-
loop(). ,
. while()
. ,
.

- ,
.
, .

for()
...
for(counter=0;counter<10;counter++){
System.out.println("Counter is " + counter);
}

, counter .
10 , 0 9.
:
for(int cnt = 0;cnt < 10; cnt++){
System.out.println("Counter is " + cnt);
}

.
, cnt .
.
:
for(int I = 0;int < 10;i+=){
System.out.println("Value i = " + i);
}
System.out.println("After loop i value = " + i);

.
for(byte x = 0; x < 256;x++){
Java

Rendered by www.RenderX.com

for

. 17 51

...
}

x = 127.
x , -128 .. 256
.
, ,
.

int counter = 10;


...
for(counter = 0;cnt > 0;counter++){
...
}
System.out.println("Counter is " + counter);

Counter is 0
.
int counter = 0;
for(;cnt < 1;counter++){
...
}
System.out.println("Counter is " + counter);

Counter is 1
for() .
for
for(;;){
...
}

, .
while(true){}. , ,
.
for().
.
for(i = 0, j = 0; i<5;i++, j+=2){
...
}

.
, for() ,

Java

Rendered by www.RenderX.com

. 18 51

break continue

.
.
for(int i = 0, long j = 0,i<10; i++, j += 50) //

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

//


...
int j = 0;
for(int = 7, j = 0 ;i < 10; i++,j+=10)
...

9. break continue
.
goto, Java
. break continue

9.1. continue
continue while, do, for.
continue,
()
.
...
int x = (int)(Math.random()*10);
int arr[10] = {.}
for(int cnt=0;cnt<10;cnt++){
if(arr[cnt] == x) continue;
...
}

, arr x,
continue, ,
.
, cnt ,
. continue
, .

Java

Rendered by www.RenderX.com

break

. 19 51

1. public class Test {


2. public Test() {
3. }
4. public static void main(String[] args) {
5. Test t = new Test();
6.
for(int j=0; j < 10; j++){
7.
if(i* % 2 == 0) continue;
8.
System.out.print("i=" + i);
9.
}
10.
}
11. }


1 3 5 7 9

7
. ..
.

9.2. break
, continue, ,
, .
1. public class Test {
2.
public Test() {
3.
}
4.
public static void main(String[] args) {
5.
Test t = new Test();
6.
int [] x = {1,2,4,0,8};
7.
int y = 8;
8.
for(int cnt=0;cnt < x.length;cnt++){
9.
if(0 == x[cnt]) break;
10.
System.out.println("y/x = " + y/x[cnt]);
11.
}
12.
}
13. }


y/x = 8
y/x = 4
y/x = 2

, ..
0, 9 for
.
Java

Rendered by www.RenderX.com

. 20 51

break . continue,
, break
.

10.
, .
.
break continue , Java
,
. do, while, for.
- , .

int array[][] = {.};


for(int i=0;i<5;i++){
for(j=0;j<4; j++){
...
if(array[i][j] == caseValue) break;
...
}
}

, j,
i . ,
,

int array[][] = {.};


outerLoop: for(int i=0;i<5;i++){
for(j=0;j<4; j++){

if(array[i][j] == caseValue) break outerLoop;

}
}

continue .
, continue ,
break. ..
.
.

Java

Rendered by www.RenderX.com

. 21 51

int array[][] = {.};


outerLoop: for(int i=0;i<5;i++){
for(j=0;j<4; j++){

if(array[i][j] == caseValue) continue outerLoop;

}
}

int array[][] = {.};


for(int i=0;i<5;i++){
for(j=0;j<4; j++){

if(array[i][j] == caseValue) break;

}
}


break continue .
break ,
- goto. continue ( )
. .. .
lbl:{

if( val > maxVal) break lbl;

continue .
if, lbl , ..
(), .
, goto JAVA ,
. ,
, .
, .
1.
2. public class Test {
Java

Rendered by www.RenderX.com

. 22 51

3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18. }

public Test() {
}
public static void main(String[] args) {
Test t = new Test();
t.test();
}
void test(){
Test:{
test: for(int i =0;true;i++){
if(i % 2 == 0) continue test;
if(i > 10) break Test;
System.out.print(i + " ");
}
}
}

, ,

.
, ,
, .
- .
, . ..

lbl: {

System.out.println("Block 1");

lbl: {

System.out.println("Block 2");


lbl:{

lbl:{

Java

Rendered by www.RenderX.com

. 23 51

11. return

. return
( ) .
retun try catch finally
return , . ,

void. void, return
, , .
return .
return (x*y +10) /11;

,
.
, return, .
, return ,
return , . ..
, .
return.

12. synchronized

, 12,
.

13. .
(Exceptions).
.
, . ,
/ .
, ,
,
.

int statusCode = someAction();


if (statusCode){

}else{
Java

Rendered by www.RenderX.com

. 24 51

statusCode = anotherAction();
if(statusCode){

}
}

Java -
.
try{
someAction();
anotherAction()
}catch(Exception e){

}

, ,
.

13.1.
.

.
, , , null,
, (class-) , ..
, -
.

throw.
,
.

.
(
), stop() thread).
,
. (
stop()), ,
.

, Java .
, ,
. , Java
, ,
. ,

( , ),
Java

Rendered by www.RenderX.com

try-catch

. 25 51

( ,
, , , .).
.
.
JVM, ,
.
, (
).

. ,
, . ,
, - ,
- .
.
.
,
, catch ( ),
, Throwable (.
),
. catch
. .

, .

, , ;

, ,
( , new);

, ,
, .

.
, ..
, Throwable .

13.2.
13.2.1. try-catch
.
try{

}catch(SomeExceptionClass e){

}catch(AnotherExceptionClass e){

}
Java

Rendered by www.RenderX.com

. 26 51

. (Exceptions).

.
try.
, , ,
catch try.
try ,
.

,
catch.
catch ( ).
, try
()
catch try. catch
, try .

,
, catch, try .

/
,
try{}catch(){}. catch()
.

13.2.2. try-catch-finally
finally ,
- .
: try
, finally. , finally
, try .
finally, try
.

catch, ,
catch .
-

catch , finally

finally , try
.

finally , try
.

catch , finally

, finally , try
, ,
catch

finally , try
, , finally

Java

Rendered by www.RenderX.com

try-catch-finally

. 27 51

catch ,
. finally. ,
-

finally , try
try.

finally , try ,
finally

try , finally.

finally , try

finally , try ,
.

, finally,
.
, , ,
.
try-catch-finally.
try{
byte [] buffer = new byte[128];
FileInputStream fis = new FileInputStream("file.txt");
while(fis.read(buffer) > 0){

}
}catch(IOException es){

}finally{
fis.flush();
fis.close();
}

, flush()
, .. / close() ,
.

, ,
. , finally,
,
, .
try-catch-finally
catch finally. ,
try{
...
}finally{

Java

Rendered by www.RenderX.com

. 28 51

. (Exceptions).

...
}

. finally
,
.
finally.
try{

}catch(Exception e){

System.exit(0);
}finally{

finally ..
.
return:
try{

return 0;
}
catch(MyException ex){

System.out.println("Exception");
return -1;
}
finally{

System.out.println("Finally");
}

.
finally
0
Finally
MyException, finally
-1.

Exception
Finally

Java

Rendered by www.RenderX.com

try-catch-finally

. 29 51

, finally
.
, Exception,
, finally
.
, ,
,
. ,
,
.
( main()),
Java .

13.3. throw
,
Java, .
throw.

.
public int calculate(int theValue){
if( theValue < 0){
throw new Exception(" ");
}
}

, ,
, ,
throw .
, .. .
,

(..
, try {}
catch(UserException ue){})

.
throws,
,
. ..

.
public int calculate(int theValue) throws Exception{
if( theValue < 0){
throw new Exception("Some descriptive info");
Java

Rendered by www.RenderX.com

. 30 51

. (Exceptions).

}
}

..
throw, ,
Throwable. (
new, )
, ,
.
throw .

try{

}catch(IOException ex){

//

//
throw ex;
}

.
, throw try catch.
try{

throw new IOException();

}catch(Exception e){

, try
, try catch., ..
, ...
, cacth
, try
catch , .. ,
if. , catch
, .. ,
.
try{
Java

Rendered by www.RenderX.com

. 31 51

throw new IOException();

}catch(Exception e){
;
}

try .

13.4.

(checked) (unchecked).
, java.lang.Exception . ..
-
.
, java.lang.RunTimeException, ,
.
,
(, - .),
, . ,
,

. ( , .. catch(){}
,
) ,
java.lang.Exception ( ) .
, ,
(, java.lang.IndexOfBoundException,
java.lang.ArifmeticException
). , ,
try{} catch()
.
, Error, .

, .
StackOverflowError, OutOfMemoryError.

Java

Rendered by www.RenderX.com

. 32 51

. (Exceptions).

,
try{} catch() , . ..
,
( ),
try{}
catch(java.lang.IndexOfBoundException ex) { }.
, ,
throws .
(Error),
. , , ,
Java. , ,
..

Java

Rendered by www.RenderX.com

. 33 51

.
.
.
(,
),
. ,
, .
,
.
, .
(checked)
.
, catch
try. ,
catch
.
java.lang.Exception
try{

}
catch(Exception e){

java.lang.Throwable,
- ,

try{

}
catch(Throwable e){

. ..
catch ,
.

catch, ,
.
try{

}
catch(Exception e){

Java

Rendered by www.RenderX.com

. 34 51

}
catch(IOException ioe){

}
catch(UserExcetion ue){

(
Exception) catch.
. ,
UnreachableCodeException ( - ).

try{

}
catch(UserExcetion ue){

}
catch(IOException ioe){

}
catch(Exception e){

.
, (,
AnotherUserException), catch(Exception e){}
catch, try-catch
.

13.5.
, .
,
ajav.lang.Throwable. ( Throwable)
.
public class UserException extends Exception{
public UserException(){
super();
}
public UserException(String descry){
super(descr);
}
}
Java

Rendered by www.RenderX.com

. 35 51

:
throw new UserException(" ");

. assert,
. JAVA
.
public class AssertionException extends RuntimeException{
public AssertionException(){
super("Asertion Exception");
}
public AssertionException(String descr){
super(descr);
}
}
public class Assertion {
public static Boolean ASSERTION_ON = true;
private Assertion(){};
public static void assert(boolean flag)
throws AssertionException{
if(ASSERTION_ON && flag){
throw new AssertionException()
}
}
public static void assert(boolean flag,Sring msg)
throws AssertionException{
if(ASSERTION_ON && flag){
throw new AssertionException(msg)
}
}
}

,
,
.

Assertion.assert(x <= xMinValue,"X too large");

, x
AssertionException. ..
Java

Rendered by www.RenderX.com

. 36 51

, try{} catch() . ,
, (
, -) .
try{

// Assertion

}cacth(AssertionException ae){
System.err.println(ae);
}

13.6.
,
,
.
public class BaseClass{
public void method () throws IOException{
...
}
}
public class LegalOne extends BaseClass{
public void method () throws IOException{
...
}
}
public class LegalTwo extends BaseClass{
public void method () {
...
}
}
public class LegalTree extends BaseClass{
public void method ()
throws EOFException,MalformedURLException
...
}
}
public class IllegalOne extends BaseClass{
public void method ()
throws IOException,IllegalAccessException
...
Java

Rendered by www.RenderX.com

. 37 51

}
}
public class IllegalTwo extends BaseClass{
public void method () {
...
throw new Exception();
}
}


LegalOne , .. method()
.
LegalTwo , .. method()
. (
)
LegalTree , .. method()
. ( ,
)
IlegalOne , .. method()
. (IllegalAccessException IOException)
IlegalTwo , method() ,
throws.

13.7.
,
.
.
import java.io.*;
public class Test

public Test() {
}
public static void main(String[] args) {
Test test = new Test();
try {
test.doFileInput("bogus.file");
}
catch (IOException ex) {
System.out.println("Second exception hadle starck trace");
ex.printStackTrace();
}
}

Java

Rendered by www.RenderX.com

. 38 51

. (Exceptions).

private String doFileInput(String fileName)


throws FileNotFoundException,IOException{
String retStr = "";
java.io.FileInputStream fis = null;
try {
fis = new java.io.FileInputStream(fileName);
}
catch (FileNotFoundException ex) {
System.out.println("First exception hadle starck trace");
ex.printStackTrace();
throw ex;
}
return retStr;
}
}

.
java.io.FileNotFoundException: bogus.file (The system cannot find the file
specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:64)
at experiment.Test.doFileInput(Test.java:33)
at experiment.Test.main(Test.java:21)
First exception hadle starck trace
java.io.FileNotFoundException: bogus.file (The system cannot find the file
specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:64)
at experiment.Test.doFileInput(Test.java:33)
at experiment.Test.main(Test.java:21)
Second exception hadle starck trace

Exception,
. ..
, ,
.
.
import java.io.*;
public class Test

public Test() {
}
public static void main(String[] args) {
Test test = new Test();
try {
test.doFileInput();
Java

Rendered by www.RenderX.com

. 39 51

}
catch (IOException ex) {
System.out.println("Exception hash code " + ex.hashCode());
ex.printStackTrace();
}
}
private String doFileInput() throws FileNotFoundException,IOException{
String retStr = "";
java.io.FileInputStream fis = null;
try {
fis = new java.io.FileInputStream("bogus.file");
}
catch (FileNotFoundException ex) {
System.out.println("Exception hash code " + ex.hashCode());
ex.printStackTrace();
fis = new java.io.FileInputStream("anotherBogus.file");
throw ex;
}
return retStr;
}
}
java.io.FileNotFoundException: bogus.file (The system cannot find the file
specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:64)
at experiment.Test.doFileInput(Test.java:33)
at experiment.Test.main(Test.java:21)
Exception hash code 3214658
java.io.FileNotFoundException: (The system cannot find the path specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:64)
at experiment.Test.doFileInput(Test.java:38)
at experiment.Test.main(Test.java:21)
Exception hash code 6129586

, , , ,
.
,
,
,
. ,
,
try{} catch().
, .

Java

Rendered by www.RenderX.com

. 40 51

. (Exceptions).

import java.io.*;
public class Test

public Test() {
}
public static void main(String[] args) {
Test test = new Test();
try {
test.doFileInput();
}
catch (IOException ex) {
System.out.println("Exception hash code " + ex.hashCode());
ex.printStackTrace();
}
}
private String doFileInput() throws FileNotFoundException,IOException{
String retStr = "";
java.io.FileInputStream fis = null;
try {
fis = new java.io.FileInputStream("bogus.file");
}
catch (FileNotFoundException ex) {
try {
System.out.println("Exception hash code " + ex.hashCode());
ex.printStackTrace();
fis = new java.io.FileInputStream("");
}
catch (FileNotFoundException ex2) {
}
throw ex;
}
return retStr;
}
}
java.io.FileNotFoundException: bogus.file (The system cannot find the file
specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:64)
at experiment.Test.doFileInput(Test.java:24)
at experiment.Test.main(Test.java:12)
Exception hash code 3214658
java.io.FileNotFoundException: bogus.file (The system cannot find the file
specified)
Java

Rendered by www.RenderX.com

. 41 51

at
at
at
at

java.io.FileInputStream.open(Native Method)
java.io.FileInputStream.<init>(FileInputStream.java:64)
experiment.Test.doFileInput(Test.java:24)
experiment.Test.main(Test.java:12)

Exception hash code 3214658

14.
.

while(), do(), for().


.
for() while()
. .
do ,
.
for .
.
.
.

.
for
.
for .
, .
continue while
do. for
.
break . for
,
.
Break continue ,
.
.

if() ()
else if()
switch .
byte,short,char,int.
case

case ,
, case
brake
Java

Rendered by www.RenderX.com

. 42 51

case, default (
)


try, ,
try.
.
catch try, catch
,
. , ,
,
.
finally , -
.

finally
,
try ,
, (
). System.err
.

throw new
XXXException()
java.lang.Exception ,
java.lang.RuntimeException
, ,
try{} catch(){}

throws, RuntimeException Error
( throws
), ,

(overridden) ,

.

15.
10-1. Hello World!
, ,
.
1. public class Test {
2.
public Test() {
3.
}
4.
public static void main(String[] args) {

Java

Rendered by www.RenderX.com

. 43 51

5.
Test test = new Test();
6.
String [] arr = {"H","e","l","l","o","
","w","o","r","l","d","!"};
7.
String result = "";
8.
int i= 0;
9.
for(;;;){
10.
result += arr[i++];
11.
}
12.
System.out.println(result);
13.
}
14. }

a 9 for(i = 0; i < arr.length;){

b 9 for(int int i = 0; i < arr.length;){

c 9 for(i = 0; i < arr.length;i++){

d 9 for(i = 1; i <= arr.length;i++){


a.) a
b i main
,
( for) .

.
, ,
.
c , i
, ..
.
d .
0,
, ,
IndexOfBoundException

10-2.
1. public class Test {
2.
public Test() {
3.
}
4.
5.
public static void main(String[] args) {
6.
Test test = new Test();
7.
int i = 5;
8.
while(i = 5){
9.
System.out.println(i++);
10.
}
11.
}
12. }
Java

Rendered by www.RenderX.com

. 44 51

a 8

b 01234

c 43210

d ,
a.) a. while
. ,
, .. .

10-3. .
private void say(int digit){
switch(x){
case 1: System.out.print("ONE");
break;
case 2: System.out.print("TWO");
case 3: System.out.print("TREE");
default:System.out.pritn("Unknown value")
}
}

a digit = 1 ONE

b digit = 0 TWO TREE

c digit = 2 TWO Unknown value

d digit = 3 TREE Unknown value


a.) a,d.
.
digit = 0 Unknown value.

case
default.
digit = 1 ONE

case 1:
. break
switch
digit = 2 TWO TREE Unknown value

Java

Rendered by www.RenderX.com

. 45 51

case 2:
TWO. .. break,
switch , TREE Unknown value
digit = 3

TREE Unknown value

case
3: TREE,
break ,
default.
digit = 4 Unknown value

case ,
default.
10-4.
.
1. public class Test {
2.
public Test() {
3.
}
4.
public static void main(String[] args) {
5.
int i,j;
6.
lab: for(i = 0; i < 6; i++){
7.
for (j = 3; j > 1; j--){
8.
if(i == j){
9.
System.out.println(" " + j);
10.
break lab;
11.
}
12.
}
13.
}
14.
}
15. }

1. 2345
2. 234
3. 3
4. 2
a.) d
if , i j
2. 2
break. .. break ,
(, j), i
(), .. .
Java

Rendered by www.RenderX.com

. 46 51

10-5.
1. public class Test {
2.
float fVal = 0.0f;
3.
public Test() {
4.
}
5.
public static void main(String[] args) {
6.
Test t = new Test();
7.
String testVal = "0.123";
8.
System.out.println("Was returned " + t.testParse(testVal) + "
with value " + t.fVal);
9.
}
10.
private boolean testParse(String val){
11.
try {
12.
fVal = Float.parseFloat(val);
13.
return true;
14.
}
15.
catch (NumberFormatException ex) {
16.
System.out.println("Test.testParse() Bad number -> " + val);
17.
fVal = Float.NaN;
18.
} finally{
19.
System.out.println("Finally part executed");
20.
}
21.
return false;
22.
}
23. }

1. testVal=0.123; Finally part executed Was returned true with value 0.123
2. testVal = 0,123; Finally part executed Was returned false with value 0.123
3. testVal = null; Finally part executed NullPointer
4. testVal = 0.123; Finally part executed Was returned false with value null
a.) a,c
b , return 13.
d .. 12
, ,
,
.
10-6. .
StringIndexOutOfBoundsException ArrayIndexOutOfBoundsException
java.lang.Object
|
+--java.lang.Throwable

Java

Rendered by www.RenderX.com

. 47 51

|
+--java.lang.Exception
|
+--java.lang.RuntimeException
|
+--java.lang.IndexOutOfBoundsException
|
+--java.lang.StringIndexOutOfBoundsException
|
+--java.lang.ArrayIndexOutOfBoundsException

, testSomValue
, try catch.
?

a testSomValue throws StringIndexOutOfBoundsException, ArrayIndexOutOfBoundsException

b testSomeValue IndexOutOfBoundsException, StringIndexOutOfBoundsException, ArrayIndexOutOfBoundsException .

c throws StringIndexOutOfBoundsException,
ArrayIndexOutOfBoundsException,
,
.

d testSomeValue

a.) b,d
b , StringIndexOutOfBoundsException,
ArrayIndexOutOfBoundsException IndexOutOfBoundsException. ,
.
d , StringIndexOutOfBoundsException, ArrayIndexOutOfBoundsException RuntimeException,
throws

a ..
RuntimeException, throws ,
.
c , 1.
throws StringIndexOutOfBoundsException, ArrayIndexOutOfBoundsException catch.

10-7. .
.

Java

Rendered by www.RenderX.com

. 48 51

Exception
|
+--LengthException
|
+--TooLongException
|
+--TooShortException
class BaseMeasurer{
public BaseMeasurer(){
}
int measureLength(Dimension d) throws LengthException{
}
}
class DerivedMeasurer extends BaseMeasurer{
public BaseMeasurer(){
}
XXX {
}
}

13 ,

a int measureLength(Dimension d) throws LengthException

b int measureLength(Dimension d) throws Exception

c int measureLength(Dimension d) throws TooLongException

d int measureLength(Dimension d)
a.) a,c,d
a , ..
, .
c , ..
,

d , .. .
b ..
.

10-8. .
Exception
|
Java

Rendered by www.RenderX.com

. 49 51

+--LengthException
|
+--TooLongException
|
+--TooShortException
1. class TooShortException extends Exception{
2.
public TooShortException(String description){
3.
super(description);
4.
}
5. }
6.
7. class Measurer{
8.
public Measurer(){
9.
super();
10.
}
11.
12.
int measureLength(Dimension d) throws LengthException{
13.
XXX
14.
}
15. }

13 .
?

a new TooShortException(Shhhhort);

b throws new TooShortException(Shhhhort);

c throw new TooShortException(Shhhhort);

d throw TooShortException(Shhhhort);
a.) c.
.
a .. TooShortException,
(..
throw)
b .. throw throws
d .. ,

10-9.
1. public class Test {
2.
3.
public Test() {
4.
}
5.
public static void main(String[] args) {
6.
Test t = new Test();

Java

Rendered by www.RenderX.com

. 50 51

7.
XXX
8.
}
9.
private int check(String x,int n){
10.
if( n ==0 )return n;
11.
else if(n == 1){
12.
if ( x != null) return 5;
13.
}
14.
else if ( n == 2 && x != null){
15.
if(x.equals("YES")) return 3;
16.
else if ( x.equals("NO")) return 4;
17.
}
18.
return -1;
19.
}
20. }

7 check,
?

a t.check(ANY,1) 14.

b t.check(NO,2) 4.

c t.check(YES,1) 3

d else 14 if 11.
a.) b,d
a , .. n=1 x = null
5 12.
c , n = 1, 15, 16
, 3 .

10-10. switchcase
1. public class Test {
2.
public Test() {
3.
}
4.
public static void main(String[] args) {
5.
Test t = new Test();
6.
XXX
7.
}
8.
9.
private String check(int n){
10.
String retStr = "x";
11.
if (n < 3) n--;
12.
switch(n){
13.
case 1:
14.
return "one";
15.
case 2:
16.
n = 3;
17.
case 3:
Java

Rendered by www.RenderX.com

. 51 51

18.
break;
19.
case 4:
20.
default:
21.
return retStr;
22.
}
23.
return "Result " + n;
24.
}
25. }

6 check,
?

a t.check(1) one

b t.check(2) Result 3

c t.check(3) Result 3

d t.check(4) X

e t.check(5) X
a.) c,d,e.
.
n=1 11 n .. 0
switch case default
n=2 11 n .. 1
case 1 one
n=3 if 11 .. n
case 3,
switch Result 3
n=4 if 11 .. n
case 4
X
n=5 if 11 .. n
default
X

Java

Rendered by www.RenderX.com

Java ()

Java

Rendered by www.RenderX.com

Java
11. java.awt
20 2003
:
( Sun ) <vyazovick@itc.mipt.ru>
( Sun ) < gene@itc.mipt.ru>
Copyright 2003 Sun , , .

java.awt ....

Rendered by www.RenderX.com

ii

11. java.awt...................................................................................................1
1. .......................................................................................................................... 2
2. ............................................................................................................................2
2.1. HTML <Applet> .................................................................................................3
2.2. ............................................................................................ 5
2.3. .................................................................................................... 5
2.4. .................................................................................................5
2.5. ..........................................................................6
2.6. ............................................................................................................7
2.7. .....................................................7
2.8. Graphics......................................................................... 7
2.9. ......................................................................................................................... 8
2.9.1. Color..................................................................................... 9
2.10. ................................................................................................................. 9
2.10.1. .......................................................................... 10
2.10.2. : FontMetrics............................................. 11
2.10.3. FontMetrics....................................................................... 11
2.10.4. ...............................................................................12
3. ............................................................................................................. 12
4. .................................................................................................. 13
5. ................................................................................................23
6. ................................................................................................................................ 26
7. ...............................................................................................................................27
8. ....................................................................................................... 28
8.1. "" Java............................................................................. 32
8.2. "" ...................... 33
9. .................................................................................................................... 34
10. .................................................................................................35

Java

Rendered by www.RenderX.com

. 1 38

11. java.awt
.
1. ......................................................................................................................... 2
2. ........................................................................................................................... 2
2.1. HTML <Applet> .......................................................................................................3
2.2. ..................................................................................................5
2.3. .......................................................................................................... 5
2.4. .......................................................................................................5
2.5. ................................................................................6
2.6. ................................................................................................................. 7
2.7. ...........................................................7
2.8. Graphics............................................................................... 7
2.9. ............................................................................................................................... 8
2.9.1. Color........................................................................................... 9
2.10. .......................................................................................................................9
2.10.1. ................................................................................ 10
2.10.2. : FontMetrics................................................... 11
2.10.3. FontMetrics.............................................................................11
2.10.4. .....................................................................................12

3. ............................................................................................................ 12
4. ................................................................................................. 13
5. ............................................................................................... 23
6. ............................................................................................................................... 26
7. .............................................................................................................................. 27
8. ...................................................................................................... 28
8.1. "" Java................................................................................... 32
8.2. "" ............................ 33

9. ................................................................................................................... 34
10. ................................................................................................ 35

Java

Rendered by www.RenderX.com

. 2 38

1.
,
,
, , ,
.
. ,
- ,
. ,
, ""
-
. Java Abstraction Window
Toolkit (AWT) .
AWT .

2.
(applets) - , Internet,
,
, HTML. ,
.
HelloWorld,
:
import java.awt.*;
import java.applet.*;
public class HelloWorldApplet extends Applet {
public void paint(Graphics g) {
g.drawString("Hello World!", 20, 20);
}
}

,
java.applet java.awt. paint,
Applet. ,
Graphics.
. drawString,
Graphics, (20,20) "Hello World".
, ,
html-.
<applet code="HelloWorldApplet" width=200 height=40>
</applet>

Java

Rendered by www.RenderX.com

HTML <Applet>

. 3 38

html-,
appletviewer
. .

2.1. HTML <Applet>


<applet> HTML-,
appletviewer. appletviewer <applet>
,
. <APPLET> :
<APPLET
CODE = appletFile
OBJECT = appletSerialFile
WIDTH = pixels
HEIGHT = pixels
[ARCHIVE = jarFiles]
[CODEBASE = codebaseURL]
[ALT = alternateText]
[NAME = appletInstanceName]
[ALIGN = alignment]
[VSPACE = pixels]
[HSPACE = pixels]
>
[< PARAM NAME = AttributeNamel VALUE = AttributeValuel >]
[< PARAM NAME = AttributeName2 VALUE = AttributeValue2 >]
[HTML-, Java]
</APPLET>

CODE = appletClassFile
CODE - , ,
. codebase,
, , CODEBASE. Java
1.1 OBJECT.

OBJECT = appletClassSerialFile
, ,
.
init(), start().
CODE, OBJECT, .

WIDTH = pixels
HEIGHT = pixels
WIDTH HEIGHT - ,
.

ARCHIVE = jarFiles
jar- ( ),
Web-.
Java

Rendered by www.RenderX.com

. 4 38

, , , .
JAR,
TAR Unix:
c:\> jar cf soundmap.jar *.class image.gif sound.wav

, jar- .
(Lotus JavaBeans, Borland JBuilder)
jar-.

CODEBASE = codebaseURL
CODEBASE - , URL ,
,
( CODE). ,
HTML-. CODEBASE
, HTML-.

ALT = alternateAppletText
ALT - , ,
( ,
) ,
<applet> , .
, HTML-, <applet> </applet>
, .

NAME = appletInstanceName
NAME - ,
. ,
. ,
MyApplet Applet "Duke", :
MyApplet a = getAppletContext().getApplet("Duke"); ,
,
, .

ALIGN = alignment
ALIGN - , .
, IMG, - LEFT, RIGHT, TOP, TEXTTOP, MIDDLE, ABSMIDDLE, BASELINE, BOTTOM, ABSBOTTOM.

VSPACE = pixels
HSPACE = pixels

(VSPACE), (HSPACE).
, IMG.

PARAM NAME = appletAttribute1 VALUE = value1


HTML-
. , getParameter(),
.

Java

Rendered by www.RenderX.com

. 5 38

2.2.
getParameter(String)
getParameter String,
. - ,
- .
getParameter
:
<applet code=Testing width=40 height=40>
<param name=fontName value=Univers>
<param name=fontSize value=14>
<param name=leading value=2>
<param name=accountEnabled value=true>

, :
String
String
String
String

FontName = getParameter("fontName");
FontSize = Integer.parseInt(getParameter("fontSize"));
Leading = Float.valueOf(getParameter("leading"));
PaidUp = Boolean.valueOf(getParameter("accountEnabled"));

2.3.

getDocumentBase getCodeBase
, ,
. Java ,
HTML-, ( - getDocumentBase), ,
class- ( - getCodeBase).

AppletContext showDocument
AppletContext ,
. showDocument ,
.

2.4.
:
. , ,
:
System.out.println("Hello there, welcome to Java");

,
, . Netscape
Java Options, "Show Java Console".

Java

Rendered by www.RenderX.com

. 6 38

showStatus pletviewer
Java. .

2.5.
, Applet, ,
.

init
init . .

start
start init.
, .
, init - , start
HTML-, , .
, , WWW-,
, start.

paint
paint . AWT
, , ,
. , ,
, paint.

update
update Applet
, paint. paint
,
update - , ,
. , update.
update, paint,
AWT, update.

stop
stop , HTML-,
. stop .
,
. ,
, start.

destroy
destroy , (, Netscape) ,
.
, .

Java

Rendered by www.RenderX.com

. 7 38

2.6.
HelloWorldApplet. paint,
. Applet
, .
, update .
update repaint.
repaint
repaint . ,
, update. ,
, update .
AWT, update .
,
repaint(time) - , .
repaint(time)
repaint, (
repaint).
repaint(x, y, w, h)
,
, .
repaint(time, x, , w, h)
- .

2.7.

, ,
. size,
Dimension. Dimension,
width height:
Dimension d = size();
System.out.println(d. width + "," + d.height);

2.8. Graphics
Graphics .
, .
drawRect, drawOval, fillRect fillOval : int x, int y, int
width int height. ,
width height .

drawLine
drawline(int x1, int 1, int 2, int 2)
Java

Rendered by www.RenderX.com

. 8 38

(1,1) (2,2).
1 .
.

drawArc fillArc
drawArc fillArc :
drawArc(int x, int , int width, int height, int startAngle, int sweepAngle)

(fillArc ) ,
(x,y,width, height), startAngle
sweepAngle. 3 ,
(, 90 12 ,
180 - 9 , ).

drawPolygon fillPolygon
:
drawPolygon(int[], int[], int)
fillPolygon(int[], int[], int)

drawPolygon ( ),
, , -
. drawPolygon .
, ,
.
Java Graphics.

2.9.
AWT ,
. , , Java ,
. ,
- , , ,
.
Color.black - - black, white, red,
green, blue, cyan, yellow, magenta, orange, pink, gray, darkGray lightGray.
.

Color(int, int, int)


0
255 , .

Color(int)
- ,
, . 16-23,
- 8-15, - 0-7.

Java

Rendered by www.RenderX.com

. 9 38

Color(float, float, float)


, Color(float, float, float),
float ( 0.0 1.0) ,
.

2.9.1. Color

HSBtoRGB(float, float, float)


RGBtoHSB(int, int, int, float[])
HSBtoRGB , , (HSB),
RGB,
Color(int). RGBtoHSB ,
, float HSB,
.
HSB (Hue-Saturation-Brightness, --)
Red-Green-Blue .
(
0.0 1.0, , , , , , , , ).
( 0.0 1.0) - ,
. - 0.0 1.0,
, - .

getRed(), getGreen(), getBlue()



.

getRGB()
,
,
red = Oxff & (getRGB() >> 16);
green = Oxff & (getRGB() >> 8);
blue = Oxff & getRGB();

Graphics:

setPaintMode() setXORMode(Color)
paint -
, . XOR
, XOR
( ) ( ).

2.10.
AWT

Java

Rendered by www.RenderX.com

. 10 38

. , Java
.
/*
* <applet code="WhatFontsAreHere" width=100 height=40>
* </applet>
*
*/
import java.applet.*;
import java.awt.*;
public class WhatFontsAreHere extends Applet {
public void init() {
String fontList[];
// :
// Toolkit.getDefaultToolkit().getFontList()
fontList = GraphicsEnvironment.getLocalGraphicsEnvironment().
getAvailableFontFamilyNames();
for (int i=0; i < fontList.length; i++) {
System.out.println(i + ": " + fontList[i]);
}
}
}

drawString
drawString(String, x, ).
. (,)
, ,
. , ,
,
FontMetrics.

2.10.1.
Font ,
:
Font StrongFont = new Font("Helvetica", Font.BOLD|Font.ITALIC, 24);

: Dialog, Helvetica, TimesRoman,


Courier Symbol.
. - Font.PLAIN, Font.BOLD Font.ITALIC,
, .
.

getFamily getName

Java

Rendered by www.RenderX.com

. 11 38

getFamily .
getName .

getSize
, .

getStyle
, .
Font: - PLAIN,
BOLD ITALIC.

isBold, isItalic, isPlain


true , - (bold),
(italic) (plain), .

2.10.2. : FontMetrics
Java , FontMetrics
.
- , :

(height) - .
(baseline) - ,
( (descent)).
(ascent) - .
(descent) - .

2.10.3. FontMetrics
FontMetrics:
stringWidth
.
bytesWidth, charsWidth
.
getAscent, getDescent, getHeight
, .
. -
g .
..
getMaxAscent getMaxDescent

.

Java

Rendered by www.RenderX.com

. 12 38

2.10.4.
FontMetrics ,
, ,
.
/*
* <applet code="HelloWorld" width=200 height=100>
* </applet>
*
*/
import java.applet.*;
import java.awt.*;
public class HelloWorld extends Applet {
final Font f = new Font("Helvetica", Font.BOLD, 18);
public void paint(Graphics g) {
Dimension d = this.size();
g.setColor(Color.white);
g.fillRect(0,0,d.width,d.height);
g.setColor(Color.black);
g.setFont(f);
drawCenteredString("Hello World!", d.width, d.height, g);
g.drawRect(0,0,d.width-1,d.height-1);
}
public void drawCenteredString(String s, int w, int h, Graphics g) {
FontMetrics fm = g.getFontMetrics();
int x = (w - fm.stringWidth(s)) / 2;
int y = (fm.getAscent() + (h - (fm.getAscent() + fm.getDescent()))/2);
g.drawString(s, x, y);
}
}

3.
, Graphics Fonts AWT,
.

Component - ,
- , ,
, / , ,
,

Java

Rendered by www.RenderX.com

. 13 38

, ( 100 ).
Component.

Container
Container - Component,
, ,
. Container

LayoutManager, .

Panel
Panel - Container.
, . Panel ,
.
add Panel . ,
- ,
setLocation, setSize setBounds Component.
Panel - Applet.
, Applet, paint update
Panel. , Panel,
AWT,
Panel .

4.
Canvas
Canvas ,
. Canvas
. , ,
"" - ,
.
Canvas GrayCanvas,
.
, .
/* <applet code = "PanelDemo"
width=300
height=300>
</applet>
*/
import java.awt.*;
import java.applet.*;
class GrayCanvas extends Canvas {
Color gray;
public GrayCanvas(float g) {

Java

Rendered by www.RenderX.com

. 14 38

gray = new Color(g, g, g);


}
public void paint(Graphics g) {
Dimension size = size();
g.setColor(gray);
g.fillRect(0, 0, size.width, size.height);
g.setColor(Color.black);
g.drawRect(0, 0, size.width-1, size.height-1);
}
}
public class PanelDemo extends Applet {
static final int n = 4;
public void init() {
setLayout(null);
int width = Integer.parseInt(getParameter("width"));
int height = Integer.parseInt(getParameter("height"));
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
float g = (i * n + j) / (float) (n * n);
Canvas = new GrayCanvas(g);
add(c);
c.setSize(width / n, height / n);
c.setLocation(i * width / n, j * height / n);
}
}
}
}

Canvas ,
size, Dimension.
, Canvas resize
move. ,
.
setLayout(null).
Label
Label , , String
- , . ,
, Component.
Java

Rendered by www.RenderX.com

. 15 38

getFont/setFont getForeground/setForeground.
setText. Label LEFT, RIGHT CENTER. , ,
- .
/* <applet code = "LabelDemo" width=100 height=100>
</applet>
*/
import java.awt.*;
import java.applet.*;
public class LabelDemo extends Applet {
public void init() {
setLayout(null);
int width = Integer.parseInt(getParameter("width"));
int height = Integer.parseInt(getParameter("height"));
Label left = new Label("Left", Label.LEFT);
Label right = new Label("Right", Label.RIGHT);
Label center = new Label("Center", Label.CENTER);
add(left);
add(right);
add(center);
left.setBounds(0, 0, width, height / 3);
right.setBounds(0, height / 3, width, height / 3);
center.setBounds(0, 2 * height / 3, width, height / 3);
}
}

, Label,
reshape. ,
- 1/3 . , :

Button
- ,
Label ( ).
, ,
. ,
.
/* <applet code = "ButtonDemo" width=100 height=100>
</applet>
*/
import java.awt.*;
Java

Rendered by www.RenderX.com

. 16 38

import java.applet.*;
public class ButtonDemo extends Applet {
public void init() {
setLayout(null);
int width = Integer.parseInt(getParameter("width"));
int height = Integer.parseInt(getParameter("height"));
Button yes = new Button("Yes");
Button no = new Button("No");
Button maybe = new Button("Undecided");
add(yes);
add(no);
add(maybe);
yes.setBounds(0, 0, width, height / 3);
no.setBounds(0, height / 3, width, height / 3);
maybe.setBounds(0, 2 * height / 3, width, height / 3);
}
}

Checkbox
Checkbox .
Checkbox ,
.
getState setState.
Checkbox,
.
/* <applet code = "CheckBoxDemo" width=120 height=100>
</applet>
*/
import java.awt.*;
import java.applet.*;
public class CheckboxDemo extends Applet {
public void init() {
setLayout(null);
int width = Integer.parseInt(getParameter("width"));
int height = Integer.parseInt(getParameter("height"));
Checkbox win95 = new Checkbox("Windows 95/98", null, true);
Checkbox Solaris = new Checkbox("Solaris 2.5");
Checkbox mac = new Checkbox("MacOS 7.5");
Java

Rendered by www.RenderX.com

. 17 38

add(win95);
add(solaris);
add(mac);
win95.setBounds(0, 0, width, height / 3);
Solaris.setBounds(0, height / 3, width, height / 3);
mac.setBounds(0, 2 * height / 3, width, height / 3);
}
}

CheckboxGroup
Checkbox ( null)
Checkbox.
CheckboxGroup,
Checkbox,
( ).
, ,
Checkbox - getCheckboxGroup setCheckboxGroup.
getCurrent setCurrent
Checkbox. ,
,
.
/* <applet code = "CheckboxGroupDemo" width=120 height=100>
</applet>
*/
import java.awt.*;
import java.applet.*;
public class CheckboxGroupDemo extends Applet {
public void init() {
setLayout(null);
int width = Integer.parseInt(getParameter("width"));
int height = Integer.parseInt(getParameter("height"));
CheckboxGroup g = new CheckboxGroup();
Checkbox win95 = new Checkbox("Windows 95/98", g, true);
Checkbox solaris = new Checkbox("Solaris 2.5", g, false);
Checkbox mac = new Checkbox("MacOS 7.5", g, false);
add(win95);
add(solaris);
add(mac);
win95.setBounds(0, 0, width, height / 3);
solaris.setBounds(0, height / 3, width, height / 3);
Java

Rendered by www.RenderX.com

. 18 38

mac.setBounds(0, 2 * height / 3, width, height / 3);


}
}

- , , :

Choice
Choice ()
( ComboBox Windows). Choice
, ,
, ,
. - , ,
. ,
Choice. countItems
. , ,
select, ( ),
, . ,
getSelectedItem getSelectedIndex , , -
. ,
Choice.
/* <applet code = "ChoiceDemo" width=200 height=100>
</applet>
*/
import java.awt.*;
import java.applet.*;
public class ChoiceDemo extends Applet {
public void init() {
setLayout(null);
int width = Integer.parseInt(getParameter("width"));
int height = Integer.parseInt(getParameter("height"));
Choice os = new Choice();
Choice browser = new Choice();
os.addItem("Windows 95/98");
os.addItem("Solaris 2.5");
os.addItem("MacOS 7.5");
browser.addItem("Netscape Navigator 3.0");
browser.addItem("Netscape Communicator 4.5");
browser.addItem("Internet Explorer 3.0");
browser.addItem("Mosaic 3.0");
browser.addItem("Lynx 2.4");
browser.select("Netscape Communicator 4.5");
add(os);
Java

Rendered by www.RenderX.com

. 19 38

add(browser);
os.setBounds(0, 0, width, height / 2);
browser.setBounds(0, height / 2, width, height / 2);
}
}

List
List
( ListBox Windows).
, , .
/* <applet code = "ListDemo" width=200 height=100>
</applet>
*/
import java.awt.*;
import java.applet.*;
public class ListDemo extends Applet {
public void init() { setLayout(null);
int width = Integer.parseInt(getParameter("width"));
int height = Integer.parseInt(getParameter("height"));
List os = new List(0, true);
List browser = new List(0, false);
os.addItem("Windows 95/98");
os.addItem("Solaris 2.5");
os.addItem("MacOS 7.5");
browser.addItem("Netscape Navigator 3.0");
browser.addItem("Netscape Communicator 4.5");
browser.addItem("lnternet Explorer 4.0");
browser.addItem("Mosaic 3.0");
browser.addItem("Lynx 2.4");
browser.select(1);
add(os);
add(browser);
os.setBounds(0, 0, width, height / 2);
browser.setBounds(0, height / 2, width, height / 2);
}
}

Java

Rendered by www.RenderX.com

. 20 38

, ,
:

Scrollbar
Scrollbar ( )
.
, , .
, , ,
.
, ,
.
Scrollbar -
VERTICAL HORIZONTAL. ,
,
, .

getValue setValue. , getMinimum getMaximum,
. ,
, .
/* <applet code = "ScrollbarDemo" width=200 height=100>
</applet>
*/
import java.awt.*;
import java.applet.*;
public class ScrollbarDemo extends Applet {
public void init() {
setLayout(null);
int width = Integer.parseInt(getParameter("width"));
int height = Integer. parseInt(getParameter("height"));
Scrollbar hs = new Scrollbar(Scrollbar.HORIZONTAL, 50, width / 10, 0,
100);
Scrollbar vs = new Scrollbar(Scrollbar.VERTICAL, 50, height / 2, 0,
100);
add(hs);
add(vs);
int thickness = 16;
hs.setBounds(0, height - thickness, width - thickness, thickness);
vs.setBounds(width - thickness, 0, thickness, height - thickness);
}
}

Java

Rendered by www.RenderX.com

. 21 38

, , :

TextField
TextField .
.
"" TextField setEditable, isEditable
, .
getText setText. select
, , .
selectAll.
setEchoChar ,
. , TextField ,
echoCharIsSet, , -,
getEchoChar. ,
.
/* <applet code = "TextFieldDemo" width=200 height=100>
</applet>
*/
import java.awt.*;
import java.applet.*;
public class TextFieldDemo extends Applet {
public void init() {
setLayout(null);
int width = Integer.parseInt(getParameter("width"));
int height = Integer.parseInt(getParameter("height"));
Label namep = new Label("Name : ", Label.RIGHT);
Label passp = new Label("Password : ", Label.RIGHT);
TextField name = new TextField(8);
TextField pass = new TextField(8);
pass.setEchoChar('*');
add(namep);
add(name);
add(passp);
add(pass);
int space = 25;
int w1 = width / 3;
namep.setBounds(0, (height - space) / 2, w1, space);
name.setBounds(w1, (height - space) / 2, w1, space);
passp.setBounds(0, (height + space) / 2, w1, space);
pass.setBounds(w1, (height + space) / 2, w1, space);

Java

Rendered by www.RenderX.com

. 22 38

}
}

TextArea
. AWT
, TextArea.
TextArea String
. , ,
. ,
TextArea: appendText String ;
insertText ;
rplaceText - , ,
-. ,
TextArea .
/* <applet code = "TextAreaDemo" width=200 height=100>
</applet>
*/
import java.awt.*;
import java.applet.*;
public class TextAreaDemo extends Applet {
public void init() {
setLayout(null);
int width = Integer.parseInt(getParameter("width"));
int height = Integer.parseInt(getParameter("height"));
String val = "Java, whose original name\n"+
"was Oak, was developed as a part\n"+
"of the Green project at Sun.\n";
System.out.println(val);
TextArea text = new TextArea(val, 80, 40);
add(text);
text.setBounds(0, 0, width, height);
}
}

Java

Rendered by www.RenderX.com

. 23 38

5.
Layout
, , "".
setLayout(null).

. AWT
(layout managers).
LayoutManager
, LayoutManager, ,
String. ,
Panel, .
Panel, minimumLayoutSize
preferredLayoutSize. , ,
preferredSize minimumSize.

, .
,
.
Java - ,
.
FlowLayout
FlowLayout ,
, , .
,
. , ,
.
FlowLayout. ,
, LEFT, RIGHT CENTER
. - CENTER,
- 5 .
, Panel Label.
Panel FlowLayout RIGHT.
/* <applet code = "FlowLayoutDemo" width=200 height=100>
</applet>
<applet code = "FlowLayoutDemo" width=250 height=100>
</applet>
*/
import java.awt.*;
import java.applet.*;
import java.util.*;
public class FlowLayoutDemo extends Applet {
public void init() {

Java

Rendered by www.RenderX.com

. 24 38

setLayout(new FlowLayout(FlowLayout.RIGHT, 10, 3));


int width = Integer.parseInt(getParameter("width"));
int height = Integer.parseInt(getParameter("height"));
String val = "Data is not information " +
"is not knowledge is not wisdom.";
StringTokenizer st = new StringTokenizer(val);
while (st.hasMoreTokens()) {
add(new Button(st.nextToken()));
}
}
}

( 200 250
) , , Label
, :

BorderLayout
BorderLayout ,
,
,
, .
-: String.North, String.South, String.East String.West
, a Center - . BorderLayout
.
/* <applet code = "BorderLayoutDemo" width=300 height=200>
</applet>
*/
import java.awt.*;
import java.applet.*;
import java.util.*;
public class BorderLayoutDemo extends Applet {
public void init() {
setLayout(new BorderLayout());
int width = Integer.parseInt(getParameter("width"));
int height = Integer.parseInt(getParameter("height"));
add("North", new Button("This is across the top"));
add("South", new Label("The footer message might go here"));
add("East", new Button("Left"));
add("West", new Button("Right"));
String msg = "The origins of Java go back to 1990,\n"+
"when the World Wide Web was\n"+
Java

Rendered by www.RenderX.com

. 25 38

"barely a glimmer in a British\n"+


"programmer's eye.\n\n"+
"-- The Java Saga, by David Bank";
add("Center", new TextArea(msg));
}
}

GridLayout
GridLayout .
. ,
GridLayout 44, 15 16 ,
. , , , -
"".
/* <applet code = "GridLayoutDemo" width=200 height=200>
</applet>
*/
import java.awt.*;
import java.applet.*;
public class GridLayoutDemo extends Applet {
static final int n = 4;
public void init() {
setLayout(new GridLayout(n, n));
setFont(new Font("Helvetica", Font.BOLD, 24));
int width = Integer.parseInt(getParameter("width"));
int height = Integer.parseInt(getParameter("height"));
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int k = i * n + j;
if (k > 0)
add(new Button("" + k));
}
}
}
}

Java

Rendered by www.RenderX.com

. 26 38

- :

,
( , "" Windows), AWT-
, Windows
.
Insets
Insets , Panel ,
,
. , Panel,
Insets , Insets
, , , .
public Insets insets() {
return new Insets(10, 10, 10, 10);
}

CardLayout
CardLayout .
,
, . ,
.
, ,
.

6.
Window
Window Panel ,
.
Window, Frame.
Frame
Frame - , .
Frame ,
. / Frame,
show hide. ,
Frame TextArea.
/* <applet code = "FrameDemo" width=200 height=200>
</applet>
Java

Rendered by www.RenderX.com

. 27 38

*/
import java.awt.*;
import java.applet.*;
public class FrameDemo extends Applet {
public void init() {
int width = Integer.parseInt(getParameter("width"));
int height = Integer.parseInt(getParameter("height"));
Frame f = new Frame("Demo Frame");
f.setSize(width, height);
f.setLayout(new FlowLayout(FlowLayout.LEFT));
f.add(new Label("
..."));
f.add(new Label(" ,
"));
f.add(new Label(" , - ."));
f.add(new Label("- (George Gilder), Forbes ASAP"));
f.show();
}
}

7.
. MenuBar
Menu. , ,
- MenuItem. Menu - MenuItem,
Menu ,
. , .
/* <applet code = "MenuDemo" width=200 height=200>
</applet>
*/
import java.awt.*;
import java.applet. *;
Java

Rendered by www.RenderX.com

. 28 38

public class MenuDemo extends Applet {


public void init() {
int width = Integer.parseInt(getParameter("width"));
int height = Integer.parseInt(getParameter("height"));
Frame f = new Frame("Demo Frame");
f.setSize(width, height);
MenuBar mbar = new MenuBar();
f.setMenuBar(mbar);
Menu file = new Menu("File");
file.add(new MenuItem("New... "));
file.add(new MenuItem("0pen..."));
file.add(new MenuItem("Close"));
file.add(new MenuItem("-"));
file.add(new MenuItem("Quit..."));
mbar.add(file);
Menu edit = new Menu("Edit");
edit.add(new MenuItem("Cut"));
edit.add(new MenuItem("Copy"));
edit.add(new Menultem("Paste"));
edit.add(new MenuItem("-"));
Menu sub = new Menu("Special");
sub.add(new MenuItem("First"));
sub.add(new MenuItem("Second"));
sub.add(new MenuItem("Third"));
edit.add(sub);
edit.add(new CheckBoxMenuItem("Debug"));
edit.add(new CheckBoxMenuItem("Testing"));
mbar.add(edit);
f.show();
}
}

8.
AWT , ,
(callback). GUI- ,
Java

Rendered by www.RenderX.com

. 29 38

( ,
..). C++,
( ,
). Java (
). ,
.
GUI-, .
, GUI- ,
.
Java AWT, JavaBeans API.
Java.
java.util.EventObject. AWT,
, java.awt.AWTEvent.
AWT (, MouseEvent tionEvent)
java.awt.event.
,
getSource(), AWT
, getID().
, ,
. , FocusEvent :
FocusEvent.FOCUS_GAINED FocusEvent.FOCUS_LOST.
, . , MouseEvent
getX(), getY() getClickCount (). , ,
getModifiers() getWhen().
Java .
, . ,
( ), ,
, ,
, .
( ,
),
, .

( EventObject).
, .
,
. ,
ActionEvent ActionListener. java.awt.event

(, MouseEvent :
MouseListener MouseMotionListener).
java.util.EventListener.
, -,
.
. ,
, MouseEvent, , ,
Java

Rendered by www.RenderX.com

. 30 38

.
. ,
,
, .
,
. 6 java.awt.event
, , ,
.
1. , Java

ActionEvent

ActionListener

actionPerformed()

AdjustmentEvent

AdjustmentListener

adjustmentValueChanged()

ComponentEvent

ComponentListener

componentHidden()
componentMoved()
componentResized()
componentShown()

ContainerEvent

ContainerListener

componentAdded()
componentRemoved()

FocusEvent

FocusListener

focusGained()
focusLost ()

ItemEvent

ItemListener

itemStateChanged()

KeyEvent

KeyListener

keyPressed()
keyReleased()
keyTyped()

MouseEvent

MouseListener

mouseClicked()
mouseEntered()
mouseExited()
mousePressed()
mouseReleased()

MouseMotionEvent

MouseMotionListener

mouseDragged()
mouseMoved()

TextEvent

TextListener

textValueChanged()

WindowEvent

WindowListener

windowActivated()
windowClosed()
windowClosing()
windowDeactivated()
windowDeiconified()
windowlconified()
windowOpened()

, ,
java.awt.event -,
.
, -,
.
, ,
, . , , ,
Listener Adapter: MouseAdapter, WindowAdapter ..
-,
,
.
Java

Rendered by www.RenderX.com

. 31 38

. AWT
- .
: X,
addXListener () removeXListener() .
Java ,
. ,
. , API Button ,
ActionEvent. 7
AWT , .
2. AWT Java1.1

Button

ActionEvent

CheckBox

ItemEvent

CheckBoxMenuItem

ItemEvent

Choice

ItemEvent

Component

ComponentEvent

,
,

FocusEvent

KeyEvent

MouseEvent


,
,
,

Container

ContainerEvent

List

ActionEvent

ItemEvent

MenuItem

ActionEvent

Scrollbar

AdjustmentEvent

TextComponent

TextEvent

TextField

ActionEvent

Window

WindowEvent

, ,
,

Java

Rendered by www.RenderX.com

. 32 38

8.1. "" Java


, Java.
MouseListener MouseMotionListener,
addMouseListener() addMouseMotionListener().
/* <applet code = "Scribble2" width=200 height=200>
* </applet>
*/
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Scribble2 extends Applet implements
MouseListener, MouseMotionListener {
private int last_x, last_y;
public void init() {
// ,
// MouseListener MouseMotionListener
// , .
// ,
// .
this.addMouseListener(this) ;
this.addMouseMotionListener(this);
}
// MouseListener.
// .
public void mousePressed(MouseEvent e) {
last_x = e.getX();
last_y = e.getY();
}
// MouseMotionListener.
// .
public void mouseDragged(MouseEvent e) {
Graphics g = this.getGraphics();
int x = e.getX(), y = e.getY();
g.drawLine(last_x, last_y, x, y);
last_x = x; last_y = y;
}
// , MouseListener.
public void mouseReleased(MouseEvent e) {;}
public void mouseClicked(MouseEvent e) {;}
public void mouseEntered(MouseEvent e) {;}
public void mouseExited(MouseEvent e) {;}

Java

Rendered by www.RenderX.com

""

. 33 38

// MouseMotionListener.
public void mouseMoved(MouseEvent e) {;}
}

- :

8.2. ""
Java ,
Java: . ,
,
. .
, - Clear.
ActionListener,
.
/* <applet code = "Scribble3" width=200 height=200>
* </applet>
*/
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Scribble3 extends Applet {
int last_x, last_y;
public void init() {
// , MouseListener.
this.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
last_x = e.getX(); last_y = e.getY();
}
});
// , MouseMotionListener.
this.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
Graphics g = getGraphics();
int x = e.getX(), y= e.getY();
g.setColor(Color.black);
g.drawLine(last_x, last_y, x, y);
last_x = x; last_y = y;
}

Java

Rendered by www.RenderX.com

. 34 38

});
// Clear.
Button b = new Button("Clear");
// ,
// , .
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//
Graphics g = getGraphics();
g.setColor(getBackground());
g.fillRect(0, 0, getSize().width, getSize().height);
}
});
// .
this.add(b);
}
}

, 3 : Scribble3$1,2,3.

9.
(GUI)
Java, AWT.
, ,
HTML-. -,
, . ,
,
. -, ,
, main.
, Java Graphics,
, .
AWT,
Component .
Container, . Component
Java

Rendered by www.RenderX.com

. 35 38

( . controls),
Container .

(Layout managers).
Container Window,
. Dialog
Frame. Dialog FileDialog.
MenuComponent .
, ,
, , . 11

GUI-.

10.
11-1. Applet?
a.) java.awt.Panel
11-2. init ? start?
a.) init .
start ,
.
11-3. paint, update, repaint?
a.) paint ,

update (background)
, paint
repaint ,
update
11-4. Color, ?
a.) new Color(0,0,255). Color.blue
11-5. Java ?
a.) , ( ), (, ,
).
11-6. FontMetrics?
a.) ,
,
,
Java

Rendered by www.RenderX.com

. 36 38

.
.

FontMetrics
, , .
11-7. -,
1010.
a.) public class SquareComponent extends Canvas {
public void paint(Graphics g) {
g.drawRect(getWidth()-5, getHeight()-5, 10, 10);
}
}

11-8. AWT (check-box)? - (radio-button)?


a.) Checkbox:
Checkbox chbox = new Checkbox();

-
Checkbox CheckboxGroup:
CheckboxGroup group = new CheckboxGroup();
Checkbox rb1 = new Checkbox(" 1",group, true);
Checkbox rb2 = new Checkbox(" 2",group, false);

11-9. List Choice?


a.) List , Choise .
List (
multiselect), Choice .
11-10. ?
?
a.) .

,
, , .
:

constraints,


..)

Java

Rendered by www.RenderX.com

. 37 38

11-11. Dialog Frame?


a.) , Frame
, Dialog Frame. Dialog
. Frame . Dialog
.
11-12. ,
, ?
a.) . -,
Listener-,
. ,
add<>Listener, .
11-13. , ?
a.) , add<>Listener
.

Java

Rendered by www.RenderX.com

Java ()

Java

Rendered by www.RenderX.com

Java
12. .

20 2003
:
( Sun ) <vyazovick@itc.mipt.ru>
( Sun ) < gene@itc.mipt.ru>
Copyright 2003 Sun , , .

Java.

.
- , ,
, .
, , Java.

, , , . ,
, .

Rendered by www.RenderX.com

ii

12. . ............................................................. 1
1. .......................................................................................................................... 1
2. ........................................................................................... 2
3. ....................................................................... 4
3.1. Thread........................................................................................................... 4
3.2. Runnable.............................................................................................. 5
3.3. ..........................................................................................5
3.4. -.......................................................................................................... 8
4. .............................................................................................................. 11
4.1. ......................................................................... 13
4.2. volatile............................................................................................ 14
4.3. ............................................................................................................ 15
5. wait(), notify(), notifyAll() Object............................................................19
6. ...................................................................................................21

Java

Rendered by www.RenderX.com

. 1 24

12. .

.
1. ......................................................................................................................... 1
2. .......................................................................................... 2
3. ...................................................................... 4
3.1. Thread................................................................................................................. 4
3.2. Runnable.................................................................................................... 5
3.3. ................................................................................................5
3.4. -................................................................................................................ 8

4. ..............................................................................................................11
4.1. ............................................................................... 13
4.2. volatile..................................................................................................14
4.3. ..................................................................................................................15

5. wait(), notify(), notifyAll() Object........................................................... 19


6. .................................................................................................. 21

1.
,
, .
, Java , ..
(threads) .
,
.
Java,
.

, ,
.
,
, , . Java

Java

Rendered by www.RenderX.com

. 2 24

synchronized.
.
wait(), notify(), notifyAll() Object.

2.
,
, .
,
.
, .
.
-
,
?
(time-slicing). .
,
.
.
,
. ,
( ),
. , Windows
, .
.
-
?
,
. , ,
. ,
,
() . , ,
, , .
, .
, ,
, .
, ,
.
, ,
.
- , .
,
.
.
Java

Rendered by www.RenderX.com

. 3 24

,
.
- , -
. time-slicing, -
, , , , , , ,
, , .
,
.
Java ,
.
,
. - ,
. ,
, , ( ..) . ,
.
, ,
, ,
- . , ,
,
. ,
, , 2 , ,
2 ,
.
(, ),
,
, .
-
. , , ,
, , ,
2 . , ,
, - ( ).
()
( ,
), . ,
,
.
(priority) . Java
. , .
, -
. -
,
.
,
. ,

Java

Rendered by www.RenderX.com

. 4 24

.
,
.
. ,
,
. ,
.
, ,
. , Java
() . - ,
, , .
, garbage collector' .
(daemon),
. ,
-.
, Java.

3.
3.1. Thread
Java Thread. ,

run(). ,
public class MyThread extends Thread {
public void run() {
// ,
long sum=0;
for (int i=0; i<1000; i++) {
sum+=i;
}
System.out.println(sum);
}
}

run() , .
, -,
start(), ,
run().
MyThread t = new MyThread();
t.start();

Java

Rendered by www.RenderX.com

Runnable

. 5 24

:
499500

run() ( , return)
. , .
,
.

3.2. Runnable
. Java
, Thread
. , ,
run().
.
Runnable, -
void run(). , , :
public class MyRunnable implements Runnable {
public void run() {
// ,
long sum=0;
for (int i=0; i<1000; i++) {
sum+=i;
}
System.out.println(sum);
}
}

:
Runnable r = new MyRunnable();
Thread t = new Thread(r);
t.start();

, , run(),
,
MyThread, . ,
.
, Runnable Thread,
Thread.start().

3.3.
, Java . Thread
getPriority() setPriority(), :

Java

Rendered by www.RenderX.com

. 6 24

MIN_PRIORITY
MAX_PRIORITY
NORM_PRIORITY

, ,
( ) .
:
public class ThreadTest implements Runnable {
public void run() {
double calc;
for (int i=0; i<50000; i++) {
calc=Math.sin(i*i);
if (i%10000==0) {
System.out.println(getName()+" counts " + i/10000);
}
}
}
public String getName() {
return Thread.currentThread().getName();
}
public static void main(String s[]) {
//
Thread t[] = new Thread[3];
for (int i=0; i<t.length; i++) {
t[i]=new Thread(new ThreadTest(), "Thread "+i);
}
//
for (int i=0; i<t.length; i++) {
t[i].start();
System.out.println(t[i].getName()+" started");
}
}
}

Thread:

getName()
, Thread .
Runnable . ,
. .
, Java "Thread-"
( ) getName().
setName().

Java

Rendered by www.RenderX.com

. 7 24

currentThread()

Thread, .

:
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread

0
1
2
0
1
2
0
1
2
0
2
1
2
0
1
2
0
1

started
started
started
counts 0
counts 0
counts 0
counts 1
counts 1
counts 1
counts 2
counts 2
counts 2
counts 3
counts 3
counts 3
counts 4
counts 4
counts 4

, ,
. , ,
. , ,
.
,
, . main()
public static void main(String s[]) {
//
Thread t[] = new Thread[3];
for (int i=0; i<t.length; i++) {
t[i]=new Thread(new ThreadTest(), "Thread "+i);
t[i].setPriority(Thread.MIN_PRIORITY +
(Thread.MAX_PRIORITY-Thread.MIN_PRIORITY)/t.length*i);
}
//
for (int i=0; i<t.length; i++) {
t[i].start();
System.out.println(t[i].getName()+" started");
}
}

Java

Rendered by www.RenderX.com

. 8 24


. ,
1, - 10, - 5.
, ,
3.
:
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread

0
1
2
2
2
2
2
2
0
1
1
1
1
1
0
0
0
0

started
started
started
counts 0
counts 1
counts 2
counts 3
counts 4
counts 0
counts 0
counts 1
counts 2
counts 3
counts 4
counts 1
counts 2
counts 3
counts 4

, , . ,
, . ,
(Thread 0)
, (Thread 1).
, ,
. ,
.
( 500.000 , 50.000,
1000 , 10.000), ,
,
.

3.4. -
- ,
.
setDaemon() isDaemon().
:
public class ThreadTest implements Runnable {

Java

Rendered by www.RenderX.com

. 9 24

// ,
// ThreadTest
public final static ThreadGroup GROUP =
new ThreadGroup("Daemon demo");
// ,
//
private int start;
public ThreadTest(int s) {
start = (s%2==0)? s: s+1;
new Thread(GROUP, this, "Thread "+start).start();
}
public void run() {
//
for (int i=start; i>0; i--) {
try {
Thread.sleep(300);
} catch (InterruptedException e) {}
//
//
if (start>2 && i==start/2) {
new ThreadTest(i);
}
}
}
public static void main(String s[]) {
new ThreadTest(16);
new DaemonDemo();
}
}
public class DaemonDemo extends Thread {
public DaemonDemo() {
super("Daemon demo thread");
setDaemon(true);
start();
}
public void run() {
Thread threads[]=new Thread[10];
while (true) {
//
//
int count=ThreadTest.GROUP.activeCount();
if (threads.length<count) threads =
Java

Rendered by www.RenderX.com

. 10 24

new Thread[count+10];
count=ThreadTest.GROUP.enumerate(threads);
//
for (int i=0; i<count; i++) {
System.out.print(threads[i].getName()+", ");
}
System.out.println();
try {
Thread.sleep(300);
} catch (InterruptedException e) {}
}
}
}

. ThreadTest
, . run()
.
.
. main()
16. , , 8,
4, 2.
- DaemonDemo.
ThreadTest
.
:
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread

16,
16,
16,
16,
16,
16,
16,
16,
16,
16, Thread 8,
16, Thread 8,
16, Thread 8,
16, Thread 8,
16, Thread 8,
16, Thread 8, Thread 4,
16, Thread 8, Thread 4,
8, Thread 4,
4, Thread 2,
2,

, - run(),
-- .
Java

Rendered by www.RenderX.com

. 11 24

,
:

ThreadGroup
, ThreadGroup.
. ,
, , .
activeCount() enumerate()
.

sleep()
Thread
. ,
InterruptedException. ,
. ,
sleep(), ,
, interrupt()
. , sleep() InterruptedException.

sleep() yield() .
,
.
, ,
.

4.
,
,
.
, .
, ,
.
:
public class ThreadTest

private int a=1, b=2;


public void one() {
a=b;
}
public void two() {
b=a;
}
public static void main(String s[]) {
int a11=0, a22=0, a12=0;

Java

Rendered by www.RenderX.com

. 12 24

for (int i=0; i<1000; i++) {


final ThreadTest o = new ThreadTest();
// ,
//
new Thread() {
public void run() {
o.one();
}
}.start();
// ,
//
new Thread() {
public void run() {
o.two();
}
}.start();
//
try {
Thread.sleep(100);
} catch (InterruptedException e) {}
//
if (o.a==1 && o.b==1) a11++;
if (o.a==2 && o.b==2) a22++;
if (o.a!=o.b) a12++;
}
System.out.println(a11+" "+a22+" "+a12);
}
}


, one() two().
a b , . ,
1 2 , , ,
, . ,
, . :
135 864 1

, 1.
2.
. ,
1 2 . ,
, !
, 10.000, ,
:
Java

Rendered by www.RenderX.com

. 13 24

494 9498 8

,
:
0 3 997

, .
, ,
, .
,
Thread.sleep().
, ,
.
Java
.

4.1.
(main storage),
.
, .
,
, .
(working memory),
.
, :

use -

assign -

read -

load - , ,

store -

write - ,
store

, - ,
.
.
, , use assign
. ,
/ . .
Java

Rendered by www.RenderX.com

. 14 24

read,
load.
, .. ,
.
store, write.
, ..
, .
,
,
(, ,
..).
:

, , ..

, ,
, ..


. , , ,

.

.
,
.
, ,
.

4.2. volatile
volatile.
.
use volatile , ,
load,
- load use. ,
.
, store volatile ,
, assign,
- assign store.
,
.
, volatile ,

.

Java

Rendered by www.RenderX.com

. 15 24

.
,
, ,
.
64- double long.
32- ,
,
. , ,
. volatile
.

4.3.
(lock),
- (lock) (unlock).
. ,
unlock, ,
, .
lock unlock
. lock, ,
. ,
unlock .
, - .
, , ,
- . ,
- ,
unlock.
Java- , ,
synchronized. -
synchronized- .
.
Synchronized- :
synchronized (ref) {
...
}

, ,
, ref (
null). ,
, lock.
.
, unlock, .

Java

Rendered by www.RenderX.com

. 16 24

:
public class ThreadTest

implements Runnable {

private static ThreadTest shared = new ThreadTest();


public void process() {
for (int i=0; i<3; i++) {
System.out.println (Thread.currentThread().
getName()+" "+i);
Thread.yield();
}
}
public void run() {
shared.process();
}
public static void main(String s[]) {
for (int i=0; i<3; i++) {
new Thread(new ThreadTest(),
"Thread-"+i).start();
}
}
}

,
. :
Thread-0
Thread-1
Thread-2
Thread-0
Thread-2
Thread-0
Thread-1
Thread-2
Thread-1

0
0
0
1
1
2
1
2
2

, .
synchronized-:
public void run() {
synchronized (shared) {
shared.process();
}
}

Java

Rendered by www.RenderX.com

. 17 24

:
Thread-0
Thread-0
Thread-0
Thread-1
Thread-1
Thread-1
Thread-2
Thread-2
Thread-2

0
1
2
0
1
2
0
1
2

Synchronized- . ,
, .
.
, synchronized-, process()
.
static synchronized .
Class, , .
deadlock , .
, ,
,
.
:
public class DeadlockDemo {
// -
public final static Object one=new Object(), two=new Object();
public static void main(String s[]) {
// ,
// one two
Thread t1 = new Thread() {
public void run() {
//
synchronized(one) {
Thread.yield();
//
synchronized (two) {
System.out.println("Success!");
}
}
}
};
Thread t2 = new Thread() {
Java

Rendered by www.RenderX.com

. 18 24

public void run() {


//
synchronized(two) {
Thread.yield();
//
synchronized (one) {
System.out.println("Success!");
}
}
}
};
//
t1.start();
t2.start();
}
}

, .
, yield() . ,
,
. , "",
. ,
. " ", deadlock.
,
. ,
. (
yield()) (
), ( ""),
(-
), .
Java deadlock.
,
. ,
. ,
(
, ), .

. , ,
sleep(..), ,

, deadlock.
,
.

Java

Rendered by www.RenderX.com

. 19 24

5. wait(), notify(), notifyAll() Object


, Object,
Java.
Java synchronized ,
wait-set, .
wait() wait-set.
,
notifyAll(), wait-set. notify()
, .
.

. , synchronized-
,
. :
public class WaitThread implements Runnable {
private Object shared;
public WaitThread(Object o) {
shared=o;
}
public void run() {
synchronized (shared) {
try {
shared.wait();
} catch (InterruptedException e) {}
System.out.println("after wait");
}
}
public static void main(String s[]) {
Object o = new Object();
WaitThread w = new WaitThread(o);
new Thread(w).start();
try {
Thread.sleep(100);
} catch (InterruptedException e) {} System.out.println("before notify");
synchronized (o) {
o.notifyAll();
}
}
}

Java

Rendered by www.RenderX.com

. 20 24

wait(), notify(), notifyAll() Object

:
before notify
after wait

, wait(), sleep(), InterruptedException, interrupt().


:
public class ThreadTest implements Runnable {
final static private Object shared=new Object();
private int type;
public ThreadTest(int i) {
type=i;
}
public void run() {
if (type==1 || type==2) {
synchronized (shared) {
try {
shared.wait();
} catch (InterruptedException e) {}
System.out.println("Thread "+type+
" after wait()");
}
} else {
synchronized (shared) {
shared.notifyAll();
System.out.println("Thread "+type+
" after notifyAll()");
}
}
}
public static void main(String s[]) {
ThreadTest w1 = new ThreadTest(1);
new Thread(w1).start();
try {
Thread.sleep(100);
} catch (InterruptedException e) {}
ThreadTest w2 = new ThreadTest(2);
new Thread(w2).start();
try {
Thread.sleep(100);
} catch (InterruptedException e) {}

Java

Rendered by www.RenderX.com

. 21 24

ThreadTest w3 = new ThreadTest(3);


new Thread(w3).start();
}
}

:
Thread 3 after notifyAll()
Thread 1 after wait()
Thread 2 after wait()

, . -, 1,
wait() .
2. 3.
. 1 synchronized, shared. ,
2 synchronized-, 3.
, "" 1 2?
, ,
wait(), . , notifyAll().
, wait-set .
,
synchronized-!
, notifyAll() .
.
synchronized- ,
. - ,
wait(), notifyAll().
.
wait() , -,
.
.

6.
12-1.
?
a.)
. ,
.
, ,
. time-slicing.
12-2. ?

Java

Rendered by www.RenderX.com

. 22 24

a.) :


(, ,
), ,
, ,
.

,
(, , ,
, ..),
,
.


, .
,
.

12-3. ?
a.) , , ,
.

,
, .
12-4. -?
a.) - . -
, ,
-.
12-5. ,
?
a.) -,
.
12-6. Java Thread?
a.) Thread ,
(, ,
..).
12-7. Runnable
,
Thread?
a.) ,
Thread .
.
12-8. Java? ?
Java

Rendered by www.RenderX.com

. 23 24

a.) JVM ,
, .
. ,
, ,
.
. ,
, .
12-9. synchronized-,
, ? ?
a.) , synchronized . synchronized-
, .
12-10. synchronized, ?
a.) ,
.
12-11. static synchronized ?
a.) synchronized ,
, Class,
. , ,
static synchronized
.
12-12. wait InterruptedException, notify notifyAll
?
a.) wait ,
, interrupt(),
InterruptedException.
notify notifyAll .
12-13. wait,
notify? notifyAll?
a.) wait
,
,
. - ,
wait.
12-14. ?
public abstract class Test implements Runnable {
private Object lock = new Object();
public void lock() {
synchronized (lock) {
Java

Rendered by www.RenderX.com

. 24 24

try {
lock.wait();
System.out.println(1);
} catch (InterruptedException e) {
}
}
}
public void unlock() {
synchronized (lock) {
lock.notify();
System.out.println(2);
}
}
public static void main(String s[]) {
new Thread(new Test() {
public void run() {
lock();
}
}).start();
new Thread(new Test() {
public void run() {
unlock();
}
}).start();
}
}

a.) 2,
,
wait. notify,
( lock),
.

Java

Rendered by www.RenderX.com

Java
13. java.lang.
20 2003
:
( Sun ) <vyazovick@itc.mipt.ru>
( Sun ) < gene@itc.mipt.ru>
Copyright 2003 Sun , , .

Java java.lang.
Object Class, - , Math,
String StringBuffer, System, Runtime .
,
.

Rendered by www.RenderX.com

ii

13. java.lang................................................................................................. 1
1. .......................................................................................................................... 2
2. Object................................................................................................................................ 3
3. Class................................................................................................................................. 7
4. Wrapper Classes...............................................................................................................9
4.1. Integer.................................................................................................................... 10
4.2. Character................................................................................................................12
4.3. Boolean.................................................................................................................. 13
4.4. Void........................................................................................................................ 13
5. Math................................................................................................................................ 13
6. ............................................................................................................................ 15
6.1. String...................................................................................................................... 15
6.2. StringBuffer............................................................................................................ 18
7. ........................................................................................................ 20
7.1. ClassLoader........................................................................................................... 21
7.2. SecurityManager - ........................................................ 22
7.3. System................................................................................................................... 23
7.4. Runtime.................................................................................................................. 24
7.5. Process.................................................................................................................. 24
8. ........................................................................................................25
8.1. Runnable ............................................................................................................... 25
8.2. Thread ................................................................................................................... 25
8.3. ThreadGroup.......................................................................................................... 28
9. ....................................................................................................................28
10. .................................................................................................................. 28
11. .................................................................................................29

Java

Rendered by www.RenderX.com

. 1 33

13. java.lang.
.
1. ......................................................................................................................... 2
2. Object............................................................................................................................... 3
3. Class.................................................................................................................................7
4. Wrapper Classes.............................................................................................................. 9
4.1. Integer.......................................................................................................................... 10
4.2. Character......................................................................................................................12
4.3. Boolean........................................................................................................................ 13
4.4. Void.............................................................................................................................. 13

5. Math................................................................................................................................13
6. ............................................................................................................................15
6.1. String............................................................................................................................ 15
6.2. StringBuffer.................................................................................................................. 18

7. ........................................................................................................20
7.1. ClassLoader................................................................................................................. 21
7.2. SecurityManager - .............................................................. 22
7.3. System......................................................................................................................... 23
7.4. Runtime........................................................................................................................ 24
7.5. Process........................................................................................................................ 24

8. ....................................................................................................... 25
8.1. Runnable ..................................................................................................................... 25
8.2. Thread ......................................................................................................................... 25
8.3. ThreadGroup................................................................................................................ 28

9. ................................................................................................................... 28
10. ................................................................................................................. 28
11. ................................................................................................ 29

Java

Rendered by www.RenderX.com

. 2 33

1.
java.lang , - -
, Java API. Java
( ) -
import java.lang.*;.
:
Object - .
, Object. , ,
.
Class - Java.
String -
StringBuffer - ()
Number - , -
Java
Character - char
Boolean- boolean
Math -
Throwable - , . ,
, , catch,
Throwable
Thread - Java. Java

ThreadGroup - ,
.
. ,
.
System -
Runtime -
Process - , Runtime
ClassLoader -
SecurityManager -

Compiler - Just-in-Time
:
Cloneable - ,
JVM (Object.clone())

Java

Rendered by www.RenderX.com

. 3 33

Runnable - Thread,
run(), .
Comparable - (, ) ,
.

2. Object
Object . ,
Java.
:
1.0) public boolean equals(Object obj) - , .
= = , equals()
, .
Object , true ,
, ,
:
public boolean equals(Object obj) {
return (this == obj);
}

- , ,
. , -
( Integer), true,
int , ,
- Integer.
equals() (,
false, , , - true) - , ,
, :
:
1. : x, x.equals(x) true
2. : x y, x.equals(y) true
, y.equals(x) true
3. : x, y z, x.equals(y) true
y.equals(z) true, x.equals(z) true
4. : x y,
x.equals(y) (
true false)
5. null x, x.equals(null)
false
:
package demo.lang;
Java

Rendered by www.RenderX.com

. 4 33

Object

public class Rectangle {


public int sideA;
public int sideB;
public Rectangle(int x, int y) {
super();
sideA = x;
sideB = y;
}
public boolean equals(Object obj) {
if(!(obj instanceof Rectangle)) return false;
Rectangle ref = (Rectangle)obj;
return (((this.sideA==ref.sideA)&&(this.sideB==ref.sideB))||
(this.sideA==ref.sideB)&&(this.sideB==ref.sideA));
}
public static void main(String[] args) {
Rectangle r1 = new Rectangle(10,20);
Rectangle r2 = new Rectangle(10,10);
Rectangle r3 = new Rectangle(20,10);
System.out.println("r1.equals(r1) == " + r1.equals(r1));
System.out.println("r1.equals(r2) == " + r1.equals(r2));
System.out.println("r1.equals(r3) == " + r1.equals(r3));
System.out.println("r2.equals(r3) == " + r2.equals(r3));
System.out.println("r1.equals(null) == " + r1.equals(null));
}
}

, , :
r1.equals(r1) == true
r1.equals(r2) == false
r1.equals(r3) == true
r2.equals(r3) == false
r1.equals(null) == false

equals() Retangle ,
, (
).
1.1) public int hashCode() - - (hash code) . - -
,
. Hashtable
(- ,
, -)
,
-, ,
.
, x.equals(y) true, - x y ,

Java

Rendered by www.RenderX.com

. 5 33

x.hashCode() y.hashCode() .
Hashtable , equals()
, ,
:
a) , , hashCode(),
int ,
, equals().
,

b) , equals(Object) true,
hashCode()

c) , equals(Object) false,
- , . -

-.
Object hashCode()
,
, .
1.2) public String toString() - . Object
:
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

, -.
-
.
, . , ,
:
package demo.lang;
public class Book {
private String title;
private String author;
private int pagesNumber;
public Book(String title, String author, int pagesNumber) {
super();
this.title = title;
this.author = author;
this.pagesNumber = pagesNumber;
}
public static void main(String[] args) {

Java

Rendered by www.RenderX.com

. 6 33

Object

Book book = new Book("Java2", "Sun", 1000);


System.out.println("object is: " + book);
}
public String toString(){
return "Book: " + title + " ( " + author + ", " + pagesNumber + " pages )";
}
}

, :
object is: Book: Java2 ( Sun, 1000 pages )

, book,
toString() ( "+" ,
String, toString()).
1.3) wait(), notify(), notifyAll() - .
final -.
1.4) protected void finalize() throws Throwable - Java-
, garbage collection ( ) , .
, finaliuze()
. ,
,
.
, finalize().
Object - .
-
, ..
1.5) protected native Object clone() throws CloneNotSupportedException -
. , ,
Cloneable. , ,
- ,
. Object clone() ,
. " " ,
, - clone() .
, :
package demo.lang;
public class BookStorage implements Cloneable{
public Book[] books;
public BookStorage() {
books = new Book[2];
books[0] = new Book("Essential java", "Sun", 500);
books[1] = new Book("Professional Java", "Sun", 1000);
}
}
Java

Rendered by www.RenderX.com

. 7 33

:
BookStorage storage1 = new BookStorage();
try{
BookStorage storage2 = (BookStorage)storage1.clone();
storage2.books[2] = new Book("Java 2 Enterprise", "Sun", 2000);
System.out.println("storage1.books[1] = " + storage1.books[1]);
}catch(CloneNotSupportedException e){
e.printStackTrace();
}

storage1 - books.
, clone()
, : storage1 storage2.
, , ,
, ,
clone(). ,
:
protected Object clone() throws CloneNotSupportedException{
BookStorage result = (BookStorage)super.clone();
result.books = (Book[])books.clone();
return result;
}

BookStorage, books.
, .
1.6) public final native Class getClass() - Class,
.
.

3. Class
Java Class.
, , ..
Class
Java- defineClass()
. Class
forName():
2.1) public static Class forName(String name, boolean initialize, ClassLoader loader)
Class, ,
name ( ),
. loader
null, ,
. , initialize true
.

Java

Rendered by www.RenderX.com

. 8 33

Class

forName(),
:
public static Class forName(String className)
, , .
2.2) public Object newInstance() ,
Class. ,
. ,
InstantiationException. , Class
, - .
2.3) , , ,
Class:
getMethods(), getFields(), getConstructors(),getDeclaredMethods() ..
, , , .
Java
(reflection). ,
java.lang.reflection.

. :
package demo.lang;
interface Vehicle {
void go();
}
class Automobile implements Vehicle {
public void go() {
System.out.println("Automobile go!");
}
}
class Truck implements Vehicle {
public Truck(int i) {
super();
}
public void go() {
System.out.println("Truck go!");
}
}
public class VehicleStarter {
public static void main(String[] args) {
Vehicle vehicle;
String[] vehicleNames = {"demo.lang.Automobile", "demo.lang.Truck",
"demo.lang.Tank"};
for(int i=0; i<vehicleNames.length; i++){
try{
String name = vehicleNames[i];
System.out.println("look for clas for: " + name);
Class aClass = Class.forName(name);
Java

Rendered by www.RenderX.com

. 9 33

System.out.println("creating vehicle...");
vehicle = (Vehicle)aClass.newInstance();
System.out.println("create vehicle: " + vehicle.getClass());
vehicle.go();
}catch(ClassNotFoundException e){
System.out.println("Exception: " + e.toString());
}catch(InstantiationException e){
System.out.println("Exception: " + e.toString());
}catch(Throwable th){
System.out.println("Another problem: " + th.toString());
}
}
}
}

, :
look for clas for: demo.lang.Automobile
creating vehicle...
create vehicle: class demo.lang.Automobile
Automobile go!
look for clas for: demo.lang.Truck
creating vehicle...
Instantiation exception: java.lang.InstantiationException
look for clas for: demo.lang.Tank
Class not found: java.lang.ClassNotFoundException: demo.lang.Tank

, Automobile ,
Vehicle. Truck ,
, , , java.lang.InstantiationException. - java.lang.Tank ,
Class, , java.lang.ClassNotFoundException.

4. Wrapper Classes
,
. , , ,
- .
-.
Java . ( ,
), final
- . - ( Void)
Serializable, ( Void) -
. - TYPE -
Class, .
-
,
.
Java

Rendered by www.RenderX.com

. 10 33

Wrapper Classes

1 :
-

Byte

byte

Short

short

Character

char

Integer

int

Long

long

Float

float

Double

double

Boolean

boolean

- Byte, Short, Integer, Long, Float, Double


- Number. , (
) - byte, short, int, long, float double.
- Comparable. Number
java.io.Serializable, -
.
- equals(Object),
.
- (new Integer(1)).equals(new Byte(1))
false, , - .
, , equals() ,
, () , - false.
jdk1.3.1 Integer equals() :

public boolean equals(java.lang.Object obj) {


if(obj instanceof java.lang.Integer)
return value == ((java.lang.Integer)obj).intValue();
else
return false;
}

-.

4.1. Integer
.
public static int parseInt(String s) - int ,

public static int parseInt(String s, int radix) - int ,
radix
NumberFormatException, ,
, .
, :
public static Integer valueOf(String s) public static Integer valueOf(String s,int radix)
Java

Rendered by www.RenderX.com

Integer

. 11 33

,
-.
Integer
Integer(String s) - , ,
,
Integer(int i) - , - ,
,
NumberFormatException

pubic static String toString(int i) - int


, int ,
:
pubic static String toOctalString(int i) -
pubic static String toBinaryString(int i) -
pubic static String toHexString(int i) - .
:
Integer.MIN_VALUE - int
Integer.MAX_VALUE - int .
, ,
- .
public int intValue();
Integer. -
: Byte, Short, Long
, : byte, short, long.
:
public static void main(String[] args) {
int i = 1;
byte b = 1;
String value = "1000";
Integer iObj = new Integer(i);
Byte bObj = new Byte(b);
System.out.println("while i==b is " + (i==b));
System.out.println("iObj.equals(bObj) is " + iObj.equals(bObj));
Long lObj = new Long(value);
System.out.println("lObj = " + lObj.toString());
Long sum = new Long(lObj.longValue() + iObj.byteValue() +
bObj.shortValue());
System.out.println("The sum = " + sum.doubleValue());
}

Java

Rendered by www.RenderX.com

. 12 33

Wrapper Classes

. , ,
:
while i==b is true
iObj.equals(bObj) is false
lObj = 1000
The sum = 1002.0

- : Float Double -
,
:
NEGATIVE_INFINITY -
POSITIVE_INFINITY -
NaN - (, ..)
, MIN_VALUE -
, ( > 0) ,
, ,
-.
- ,
Java:

4.2. Character
Comparable.
- , char .
equals(), hashCode(), toString() ,
:
public char charValue() - char
public int compareTo(Character anotherCharacter) - char
, return this.value - anotherCharacter.value;
-, Comparable, compareTo()
Object:
public int compareTo(Object o) - Character,
compareTo((Character)o),
ClassCastException - - Character Character.
Character ,
. . - ,
char - , ,
, Java, ..
:
public static boolean isDigit(char c) - , char

Java

Rendered by www.RenderX.com

Boolean

. 13 33

public static boolean isLetter(char c) - , char


public static boolean isDigitOrLetter(char c) - , char
public static boolean isIdentifierStart(char c) - ,
, JAVA
,
.

4.3. Boolean
- boolean.
java.io.Serializable -.
booleanValue().

4.4. Void
-, , java.io.Serializable.
. ,
. Class,
void. TYPE.
-,

-
, c String, Character,
char

- equals()

-
xxxxValue() ( intValue())

- -, ..

5. Math
Math ,
, . - (Utility class).

- .
, final.
, :
public static final double Matht.PI -
Java

Rendered by www.RenderX.com

. 14 33

Math

public static final double Matht.E - e.


, double.
, double,
.

2 .
static double

abs(double a)


double

static float

abs(float a)


byte

static int

abs(int a)


int (1)

static long

abs(long a)


long

static double

acos(double a)


0 PI

static double

asin(double a)


-PI/2 PI/2

static double

atan(double a)


-PI/2 PI/2

static double

ceil(double a)


a. (2)

static double

floor(double a)


a. (2)

static double

cos(double a)

(3)

static double

IEEEremainder(double a, double b)

a/b
IEEE 754 (* .
)

static double

sin(double a)

(3)

static double

tan(double a)

(3)

static double

exp(double a)

e a

static double

log(double a)

static double

max(double a, double b)


double (4)

static float

max(float a, float b)


double (4)

static long

max(long a, long b)


long (4)

static int

max(int a, int b)


int (4)

static double

min(double a, double b)


double (4)

static float

min(float a, float b)


double (4)

static long

min(long a, long b)


long (4)

static int

min(int a, int b)


int (4)

static double

pow(double a, double b)

static double

random()


0.0 1.0

static double

rint(double a)

int , a

Java

Rendered by www.RenderX.com

String

. 15 33

static long

round(double a)

long
. (5)

static long

round(double a)

long
. (6)

static double

sqrt(double a)

static double

toDegrees(double angrad)

static double

toRadians(double angdeg)

,
1. abs int,
byte, short, char.
2. .
3. round double, long,
float, int.
4. 3 .

6.
6.1. String
Java .
. ,
. String
. -
- :
String abc = "abc";

. , .
String s = new String("immutable");

, .
, .
, String.
JAVA , ,
, . ,
- , .. ,
( ) .
. ..
,
. , -

Java

Rendered by www.RenderX.com

. 16 33

, ,
String .
String equals()
.

public class Test {
public Test() {
}
public static void main(String[] args) {
Test t = new Test();
String s1 = "Hello world !!!";
String s2 = "Hello world !!!";
System.out.println("String`s equally = " + (s1.equals(s2)));
System.out.println("Strings are the same = " + (s1==s2));
}
}


String`s equally = true
Strings are the same = true


public class Test {
public Test() {
}
public static void main(String[] args) {
Test t = new Test();
String s1 = "Hello world !!!";
String s2 = new String("Hello world !!!");
System.out.println("String`s equally = " + (s1.equals(s2)));
System.out.println("Strings are the same = " + (s1==s2));
}
}


String`s equally = true
Strings are the same = false

,
s1 s2 . ,
, , ,
, ,
, .

Java

Rendered by www.RenderX.com

String

. 17 33
, ,
. , ,
String , intern()

public class Test {


public static void main(String[] args) {
Test t = new Test();
String s1 = "Hello world!!!";
String s2 = new String("Hello world!!!").intern();
System.out.println("String`s equally = " + (s1.equals(s2)));
System.out.println("Strings are the same = " + (s1==s2));
}
}

String`s equally = true


Strings are the same = true
,
. , ,
, , equals() ==,
.

JAVA +.
. String
public String concat(String s);

s.
, .
- String
, String.
String. , String
, String
.

public class Test {


public static void main(String[] args) {
Test t = new Test();
String s = "prefix";
System.out.println("String before = " + s);
t.perform(s);
System.out.println("String after =" + s);
}
private void perform(String s){
System.out.println(s + " suffix");
}
}
String before = prefix
prefix suffix
String after =prefix
Java

Rendered by www.RenderX.com

. 18 33

, s .

.
public class Test {
public static void main(String[] args) {
Test t = new Test();
String s = " prefix !";
System.out.println(s);
s = s.trim();
System.out.println(s);
s = s.concat(" suffix");
System.out.println(s);
}
}
prefix !
prefix !
prefix ! suffix

, .
. trim concat
- , s, -.
, UNICODE .
(/,
..).
( )
byte[] getBytes(); - ,
. ( )
byte[] getBytes(String encoding); - ,
encoding;
( )
-.
String(byte[] bytes); -
;
String(byte[] bytes,String enc); -
.

6.2. StringBuffer
,
String. char[] ,
String, , , .
StringBuffer
StringBuffer () - StringBuffer

Java

Rendered by www.RenderX.com

StringBuffer

. 19 33

StringBuffer(String s) - String
StringBuffer (int capacity) - StringBuffer c
. , ,
, ,
, ,
.
StringBuffer
:
public class Test {
public static void main(String[] args) {
Test t = new Test();
String s = new String("ssssss");
StringBuffer sb = new StringBuffer("bbbbbb");
s.concat("-aaa");
sb.append("-aaa");
System.out.println(s);
System.out.println(sb);
}
}

:
ssssss
bbbbbb-aaa

, String ,
StringBuffer .
, StringBuffer - :
public StringBuffer append(String str) - str
;
public StringBuffer insert(int offset, String str) - , offset
( offset )
, ,
Java String.
, ,
String.valueOf(), ,
.
, - ,
. , . :
:
abcdef

Java

Rendered by www.RenderX.com

. 20 33

StringBuffer,
String StringBuffer.

public class Test {


public static void main(String[] args) {
Test t = new Test();
StringBuffer sb = new StringBuffer("aaa");
System.out.println("Before = " + sb);
t.doTest(sb);
System.out.println("After = " + sb);
}
void doTest(StringBuffer theSb){
theSb.append("-bbb");
}
}

:
Before = aaa
After = aaa-bbb

.. , doTest,
theSB, , sb. ,
String +, .. + String
,
String, .
String, String.valueOf().

System.out.println("1" + 5) 15
System.out.println(1+ 5) 6

7.
, , ,

ClassLoader - . ,

SecurityManager - . ,
.
System - , ,
. Runtime.

Java

Rendered by www.RenderX.com

ClassLoader

. 21 33

Runtime - .
Runtime.
Process - , Runtime

7.1. ClassLoader
, .
, .
: "class file", .
Class ClassLoader,
.
, ,
ClassLoader. , ,
. , .
defineClass() Class.
, newInstance()
Class. , ,
, . ,
, loadClass .
, ,
, :
class NetworkClassLoader extends ClassLoader {
String host;
int port;
public NetworkClassLoader(String host, int port) {
this.host = host;
this.port = port;
}
public Class findClass(String className) {
byte[] bytes = loadClassData(className);
return defineClass(className, bytes, 0, bytes.length)
}
private byte[] loadClassData(String className) {
byte[] result = null;
// open connection, load the class data
return result;
}
}

,
findClass() loadClassData() . ,
, , defineClass()
. ,
.

Java

Rendered by www.RenderX.com

. 22 33

, ,
, :
try{
ClassLoader loader = new NetworkClassLoader(host, port);
Object main = loader.loadClass("Main").newInstance();
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch(InstantiationException e){
e.printStackTrace();
}catch(IllegalAccessException e){
e.printStackTrace();
}

- ClassNotFoundException,
, -
- InstantiationException, , ,
(
), IllegalAccessException.

7.2. SecurityManager -

, ,
.
SecurityManager ,
check . Java
.
:
SecurityManager security = System.getSecurityManager();
if(security != null){
security.checkX();
}

X - - : Access, Read, Write, Connect, Delete, Exec, Listen


.
- SecurityException,
( checkTopLevelWindow,
boolean ).
, setSecurityManager() System. , ,
getSecurityManager().
, -
. .

Java

Rendered by www.RenderX.com

System

. 23 33

7.3. System
.
. , ,
, ;
; ;
.
, ,
System.out. (,
.., , PrintStream):
public static void main(String[] args) {
System.out.println("Study Java");
try{
PrintStream print = new PrintStream(new
FileOutputStream("d:\\file2.txt"));
System.setOut(print);
System.out.println("Study well");
}catch(FileNotFoundException e){
e.printStackTrace();
}
}

,
Study Java

"d:\file2.txt"
Study well

System.in
System.setIn(InputStream) System.err - System.setErr(PrintStream).
System
:
public static void runFinalizersOnExit(boolean value) - ,
finalize() ( ),

public static native long currentTimeMillis() - .
, 1- 1970
public static String getProperty(String key) - key.
, ,

public static java.util.Properties getProperties() - java.util.Properties,


.

Java

Rendered by www.RenderX.com

. 24 33

7.4. Runtime
Java Runtime.
, Java .
Runtime
- Runtime.getRuntime().
:
public void exit(int status) - status
(
- , try-catch-finally
finally )
public native void gc() -
public native long freeMemory() - .
, Runtime gc()
public native long totalMemory() - ,
Java . ,
Java . -,
, -
Java .
public void loadLibrary(String libname) - .
: , native
, , :
static { System.loadLibrary("LibFile"); }

, ,
native - .
- - ,
.
public void load(String filename) -
. , - load(),
, ,
native .
public void runFinalization() - finalize() ,

public Process exec(String command) - ,
. Process
.

7.5. Process
exec() Runtime -
. Process
.

Java

Rendered by www.RenderX.com

Runnable

. 25 33

Process - , ,
. , Process :
public InputStream getInputStream() - ( Piped
, )
getErrorStream(), getOutputStream() - , getInputStream(), ,
-
public void destroy() - . , ,
.
public int exitValue() - . ,
0 - .
public int waitFor() - ,
, Process.
.
Java Process -
, .
,
Process Java.
, -
Java ,
.

8.
Java .
,
. ,
Runnable, Thread, ThreadGroup.

8.1. Runnable
Runnable - , : run().
, , ,
. ,
.

8.2. Thread
.
,
:
a) , Runnable,
run(). Thread, .
, Thread start().

Java

Rendered by www.RenderX.com

. 26 33

:
public static void main(String[] args) {
class RunCode implements Runnable{
public void run(){
System.out.println("RunCode.run() begins");
System.out.println("RunCode.run() ends");
}
}
Runnable run = new RunCode();
Thread thread = new Thread(run);
thread.start();
System.out.println("main finish");
}

:
RunCode.run() begins
main finish
RunCode.run() ends

- "main finish"
, . , run()
RunCode . -
,
, run(),
. -
run()
RunCode.
b) , Thread. run() ,
.
, start().
, :
public static void main(String[] args) {
class RunCode extends Thread{
public void run(){
System.out.println("RunCode.run() begins");
System.out.println("RunCode.run() ends");
}
}
Thread thread = new RunCode();
thread.start();
System.out.println("main finish");
}

Java

Rendered by www.RenderX.com

Thread

. 27 33


. Thread Runnable,
Runnable,
Thread ( this).
, , Thread :
public void start() -
public final void join() - ,
, , Thread

public static void yield() - , ,
( ),

public static void sleep(long millis) - , ,


"" millis , .
, , .
millis ,
( Java-).
, millis
.
, , deprecated,
. : suspend()- , resume() -
( suspend()), stop() -
stop(), , Thread,
ThreadDeath. , ThreadDeath
Error. , ,
, top-level
, - .
(,
..), ,
-
. ThreadDeath Error, Exception, -
Exception, , , ,
.
Thread , :
Name - String,

Daemon -
daemon
Priority - . Thread ,
- MIN_PRIORITY
MAX_PRIORITY , - NORM_PRIORITY .
, ,
, start() Thread.
Java

Rendered by www.RenderX.com

. 28 33

, , , -
, . , ,
- isAlive() - , isInterrupted()
- .

8.3. ThreadGroup
, ""
, .
, .
ThreadGroup.
. ,
, , , ,
ThreadGroup, , .

9.
.
,
Throwable. , ,
. Throwable,
- : Error, Exception, RuntimeException
java.lang.

10.
,
java.lang. , java.lang
Java ,
Java.
java.lang:
Object, Class , ;
- (Wrapper ) ,
Java
; -;
Math , ,
;
String StringBuffer ;
System, Runtime, Process, ClassLoader, SecurityManager ,
(System, Runtime, Process),
JVM (ClassLoader) (SecurityManager);
Thread, ThreadGroup, Runnable ,
Java;
Throwable, Error, Exception, RuntimeException .
Java

Rendered by www.RenderX.com

. 29 33

11.
13-1. :
1.

2.

String s1 = abc;
String s2 = new String(abc);
boolean result = (s1==s2);

String s1 = new String(abc);


String s2 = new String(abc);
boolean result = (s1.equals(s2));

a.) result false,


true. s1 s2, ,
, , .
s1 s2 , s2
new,
. s2 , s1 (
String s2 = abc;), s1 s2
, Java
, .
.
13-2. equals()?
a.) equals()
:
1. a) : x, x.equals(x)
true
2. b) : x y,
x.equals(y) true , y.equals(x)
true
3. c) : x, y z,
x.equals(y) true y.equals(z) true,
x.equals(z) true
4. d) : x y,
x.equals(y)
( true false)
5. e) null x, x.equals(null)
false
13-3. ,
hashCode()? Object?

Java

Rendered by www.RenderX.com

. 30 33

a.) hashCode()
:
1. a) ,
hashCode(), int ,
,
equals().

,
2. b) , equals(Object)
true, hashCode()

3. c) , equals(Object)
false, - ,
. -

-.
Object hashCode() ,
.
hashCode() Object ,
equals().
13-4. equals(), , ,
,
-?
a.) , hashCode(), : ,
equals(Object) true, hashCode()
.
, equals() ,
-,
, hashCode()
, ,
equals() true.
13-5. Object equals(), toString(), hashCode() ?
a.) Object equals(), toString() hashCode()
:
equals() true,
toString() , :
, @, ,
hashCode(),
hashCode() native , ,
.

Java

Rendered by www.RenderX.com

. 31 33

13-6. ?
a.) Object.clone(),
, ,
Cloneable. ,
clone() ,
.
13-7. newInstance()
Class ?
a.) ,
Class.
. ,
, ,
.
13-8. Java -?
: (new Integer(1)).equals(new Byte(1)) ?
a.) - Java byte,
short, char, int, long, float, double, boolean (
void).
(new Integer(1)).equals(new Byte(1)) false,
equals() - ,
,
false.
13-9. - void?
a.) , -,
java.io.Serializable. .
, .
13-10. Math?
? ?
a.) Math public final. ,
Math . ,
private
Math (, Math
).
.
13-11. String Java?
a.) -,
, . -,
String +.
, String final, String-
. String

Java

Rendered by www.RenderX.com

. 32 33

, ,
.
13-12. ?
a.) String ,
StringBuffer ,
.
13-13. , ,
java.lang?
a.) java.lang.Thread,
.

java.lang.ThreadGroup. ,
Thread, Runnable.
13-14. java.lang ?
a.) java.lang Throwable,
Error, Exception, RuntimeException.

Java

Rendered by www.RenderX.com

Java
14. java.util
20 2003
:
( Sun ) <vyazovick@itc.mipt.ru>
( Sun ) < gene@itc.mipt.ru>
Copyright 2003 Sun , , .

java.util,
. ,
.
, .
Java2.
, ,
.

Rendered by www.RenderX.com

ii

14. java.util ...................................................................................................1


1. ........................................................................................................................ 2
2. ......................................................................................... 2
2.1. Date............................................................................................................... 2
2.2. Calendar GregorianCalendar...................................................................2
2.3. TimeZone...................................................................................................... 6
2.4. SimpleTimeZone .......................................................................................... 8
3. Observer Observable.....................................................................10
4. ...................................................................................................................... 11
4.1. ..........................................................................................................12
4.1.1. Collection...................................................................................12
4.1.2. Set ........................................................................................... 12
4.1.3. List ........................................................................................... 12
4.1.4. Map ..........................................................................................13
4.1.5. SortedSet .................................................................................13
4.1.6. SortedMap ............................................................................... 13
4.1.7. Iterator ..................................................................................... 13
4.2. A ...................... 14
4.3. ............................................................................ 16
4.4. Collections................................................................................................... 22
5. Properties............................................................................................................. 23
6. Comparator................................................................................................. 25
7. Arrays................................................................................................................... 25
8. StringTokenizer.................................................................................................... 26
9. BitSet.................................................................................................................... 26
10. Random.............................................................................................................. 27
11. .................................................................................................................28
11.1. Locale........................................................................................................ 28
11.2. ResourceBundle........................................................................................ 30
12. .................................................................................................................. 37
13. .................................................................................................38

Java

Rendered by www.RenderX.com

. 1 42

14. java.util
.
1. ....................................................................................................................... 2
2. .........................................................................................2
2.1. Date..................................................................................................................... 2
2.2. Calendar GregorianCalendar.........................................................................2
2.3. TimeZone............................................................................................................ 6
2.4. SimpleTimeZone ................................................................................................ 8

3. Observer Observable.................................................................... 10
4. ......................................................................................................................11
4.1. ................................................................................................................12
4.1.1. Collection.........................................................................................12
4.1.2. Set ................................................................................................. 12
4.1.3. List .................................................................................................12
4.1.4. Map ............................................................................................... 13
4.1.5. SortedSet ...................................................................................... 13
4.1.6. SortedMap .....................................................................................13
4.1.7. Iterator ........................................................................................... 13
4.2. A ............................ 14
4.3. .................................................................................. 16
4.4. Collections......................................................................................................... 22

5. Properties............................................................................................................ 23
6. Comparator.................................................................................................25
7. Arrays.................................................................................................................. 25
8. StringTokenizer....................................................................................................26
9. BitSet................................................................................................................... 26
10. Random............................................................................................................. 27
11. ................................................................................................................ 28
11.1. Locale.............................................................................................................. 28
11.2. ResourceBundle.............................................................................................. 30
Java

Rendered by www.RenderX.com

. 2 42

12. ................................................................................................................. 37
13. ................................................................................................ 38

1.
Java .
java.util.

2.
2.1. Date
Date -
, ..

Calendar. Date java.sql
Date.
Date

Date() Date(long date)


long
1 1970, 00:00:00 .
(..
). new Date(System.currentTimeMillis); Date
setTime(long time), , .
after(Date date), before(Date date)
.
compareTo(Date anotherDate) int -1
, 1 0 . toString()
,
SimpleDateFormat java.text

2.2. Calendar GregorianCalendar


Calendar. Calendar
.
.
- GregorianCalendar.
getInstance(), Gregorian. Calendar
Date .
, .
Calendar ""
, .. , , ..

Java

Rendered by www.RenderX.com

Calendar GregorianCalendar

. 3 42

,
. ..
YEAR = 1970, MONTH = JANUARY, DATE = 1 ..
, ""
get(int filed), set(int filed, int value), add(int field, int amount), roll(int field, inr amount),
int filed .
Calendar, int.
.
set(int field,int value)
- .
, .
get(), getTime()
TimeInMillis(). .. ,
. .
. , .
.
set,
.
public class Test {
public Test() {
}
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR,2002);
cal.set(Calendar.MONTH,Calendar.AUGUST);
cal.set(Calendar.DAY_OF_MONTH,31);
System.out.println(" Initialy set date:
"
sdf.format(cal.getTime()));
cal.set(Calendar.MONTH,Calendar.SEPTEMBER);
System.out.println(" Date with month changed : "
sdf.format(cal.getTime()));
cal.set(Calendar.DAY_OF_MONTH,30);
System.out.println(" Date with day changed :
"
sdf.format(cal.getTime()));

MMMM dd HH:mm:ss");

}
}
Initialy set date:
2002 August 31 22:57:47
Date with month changed : 2002 October 01 22:57:47
Date with day changed :
2002 October 30 22:57:47

Java

Rendered by www.RenderX.com

. 4 42

, ,
. .. 30 ,
1 , , 30 ,
.
, ,
.
public class Test {
public Test() {
}
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMMM dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR,2002);
cal.set(Calendar.MONTH,Calendar.AUGUST);
cal.set(Calendar.DAY_OF_MONTH,31);
System.out.println(" Initialy set date:
" +
sdf.format(cal.getTime()));
cal.set(Calendar.MONTH,Calendar.SEPTEMBER);
cal.set(Calendar.DAY_OF_MONTH,30);
System.out.println(" Date with day and month changed :
" +
sdf.format(cal.getTime()));
}
}
Initialy set date:
Date with day and month changed :

2002 August 31 23:03:51


2002 September 30 23:03:51

add(int field,int delta)


.
set(f, get(f) + delta)
add .
1. ,
,
.
2. ,
, , , ,
"".
public class Test {
public Test() {
}

Java

Rendered by www.RenderX.com

Calendar GregorianCalendar

. 5 42

public static void main(String[] args) {


SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMMM dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR,2002);
cal.set(Calendar.MONTH,Calendar.AUGUST);
cal.set(Calendar.DAY_OF_MONTH,31);
cal.set(Calendar.HOUR_OF_DAY,19);
cal.set(Calendar.MINUTE,30);
cal.set(Calendar.SECOND,00);
System.out.println("Current date: " + sdf.format(cal.getTime()));
cal.add(Calendar.SECOND,75);
System.out.println("Current date: " + sdf.format(cal.getTime()));
cal.add(Calendar.MONTH,1);
System.out.println("Current date: " + sdf.format(cal.getTime()));
}
}
Current date: 2002 August 31 19:30:00
Rule 1: 2002 August 31 19:31:15
Rule 2: 2002 September 30 19:31:15

roll(int field,int delta)



. , roll
public class Test {
public Test() {
}
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMMM dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR,2002);
cal.set(Calendar.MONTH,Calendar.AUGUST);
cal.set(Calendar.DAY_OF_MONTH,31);
cal.set(Calendar.HOUR_OF_DAY,19);
cal.set(Calendar.MINUTE,30);
cal.set(Calendar.SECOND,00);
System.out.println("Current date: " + sdf.format(cal.getTime()));
cal.roll(Calendar.SECOND,75);
System.out.println("Rule 1: " + sdf.format(cal.getTime()));
cal.roll(Calendar.MONTH,1);
System.out.println("Rule 2: " + sdf.format(cal.getTime()));
}
}
Current date: 2002 August 31 19:30:00

Java

Rendered by www.RenderX.com

. 6 42

Rule 1: 2002 August 31 19:30:15


Rule 2: 2002 September 30 19:30:15

, 1 ,
add, 2 .

2.3. TimeZone
TimeZone Calendar
DateFormat. ,
. getDefault(),
TimeZone
JVM. ,
TimeZone ,
getTimeZone(String ID), ,
, TimeZone.

getTimeZone. String[] getAvailableIds()
getTimeZone.

( ) String[] getAvailableIds(int offset);


. getTimeZone().
, getDisplayName(),
"GMT-8:00".
public class Test {
public Test() {
}
public static void main(String[] args) {
Test test = new Test();
TimeZone tz = TimeZone.getDefault();
int rawOffset = tz.getRawOffset();
System.out.println("Current TimeZone" + tz.getDisplayName() +
tz.getID() + "\n\n");
// Dispaly all available TimeZones
System.out.println("All Available TimeZones \n");
String[] idArr = tz.getAvailableIDs();
for(int cnt=0;cnt < idArr.length;cnt++){
tz = TimeZone.getTimeZone(idArr[cnt]);
System.out.println(test.padr(tz.getDisplayName() + tz.getID(),64)

Java

Rendered by www.RenderX.com

TimeZone

. 7 42

+ " raw offset=" + tz.getRawOffset() + ";hour offset=(" + tz.getRawOffset()/


(1000 * 60 * 60 ) + ")");
}
// Dispaly all available TimeZones same as for Moscow
System.out.println("\n\n TimeZones same as for Moscow \n");
idArr = tz.getAvailableIDs(rawOffset);
for(int cnt=0;cnt < idArr.length;cnt++){
tz = TimeZone.getTimeZone(idArr[cnt]);
System.out.println(test.padr(tz.getDisplayName()+ tz.getID(),64)
+ " raw offset=" + tz.getRawOffset() + ";hour offset=(" + tz.getRawOffset()/
(1000 * 60 * 60 ) + ")");
}
}
String padr(String str,int len){
if(len - str.length() > 0){
char[] buf = new char[len - str.length()];
Arrays.fill(buf,' ');
return str + new String(buf);
}else{
return str.substring(0,len);
}
}
}
Current TimeZone Moscow Standard TimeEurope/Moscow
All Available TimeZones

XXX
TimeZones same as for Moscow
Eastern African
Eastern African
Eastern African
Eastern African
Eastern African
Eastern African
Eastern African
Eastern African
Arabia Standard
Arabia Standard
Arabia Standard
Arabia Standard
Arabia Standard

TimeAfrica/Addis_Aba
TimeAfrica/Asmera
TimeAfrica/Dar_es_Sa
TimeAfrica/Djibouti
TimeAfrica/Kampala
TimeAfrica/Khartoum
TimeAfrica/Mogadishu
TimeAfrica/Nairobi
TimeAsia/Aden
TimeAsia/Baghdad
TimeAsia/Bahrain
TimeAsia/Kuwait
TimeAsia/Qatar

raw
raw
raw
raw
raw
raw
raw
raw
raw
raw
raw
raw
raw

offset=10800000;hour
offset=10800000;hour
offset=10800000;hour
offset=10800000;hour
offset=10800000;hour
offset=10800000;hour
offset=10800000;hour
offset=10800000;hour
offset=10800000;hour
offset=10800000;hour
offset=10800000;hour
offset=10800000;hour
offset=10800000;hour

offset=(3)
offset=(3)
offset=(3)
offset=(3)
offset=(3)
offset=(3)
offset=(3)
offset=(3)
offset=(3)
offset=(3)
offset=(3)
offset=(3)
offset=(3)

Java

Rendered by www.RenderX.com

. 8 42

Arabia Standard
Eastern African
Moscow Standard
Eastern African
Eastern African
Eastern African

TimeAsia/Riyadh
TimeEAT
TimeEurope/Moscow
TimeIndian/Antananar
TimeIndian/Comoro
TimeIndian/Mayotte

raw
raw
raw
raw
raw
raw

offset=10800000;hour
offset=10800000;hour
offset=10800000;hour
offset=10800000;hour
offset=10800000;hour
offset=10800000;hour

offset=(3)
offset=(3)
offset=(3)
offset=(3)
offset=(3)
offset=(3)

2.4. SimpleTimeZone
SimpleTimeZone TimeZone
.

.
TimeZone . ,
, -
.
SimpleTimeZone . ,
) ,
.
public SimpleTimeZone(int rawOffset,
String ID,
int startMonth,
int startDay,
int startDayOfWeek,
int startTime,
int endMonth,
int endDay,
int endDayOfWeek,
int endTime)

rawOffset -
ID - . (. .)
startMonth -
startDay - *
startDayOfWeek - *
startTime - ( )
endMonth -
endDay - *
endDayOfWeek - *
endTime - ( )
.
Calendar, Calendar.JANUARY
Java

Rendered by www.RenderX.com

SimpleTimeZone

. 9 42


. 2
, - 3
.

startDay 1 ,
startDayOfWeek startMonth ( )

startDay -1, ,
startDayOfWeek startMonth ( )

startDayOfWeek 0, startDay
startMonth


. ,
23 startDayOfWeek= -MONDAY, startMonth=FEBRUARY, startDay=23

- ,
. ,
23
startDayOfWeek=- -SATURDAY, startMonth=FEBRUARY, startDay=-23


.
public class Test {
public Test() {
}
public static void main(String[] args) {
Test test = new Test();
SimpleTimeZone stz = new SimpleTimeZone(
TimeZone.getDefault().getRawOffset()
,TimeZone.getDefault().getID()
,Calendar.MARCH
,-1
,Calendar.SUNDAY
,test.getTime(2,0,0,0)
,Calendar.OCTOBER
,-1
,Calendar.SUNDAY
,test.getTime(3,0,0,0)
);
System.out.println(stz.toString());
}
int getTime(int hour,int min,int sec,int ms){
return hour * 3600000 + min * 60000 + sec * 1000 + ms;

Java

Rendered by www.RenderX.com

. 10 42

Observer Observable

}
}
java.util.SimpleTimeZone[id=Europe/Moscow,offset=10800000,dstSavings=3600000,useDaylight=true,startYear=
0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=
2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=10800000,endTimeMode=0]

3. Observer Observable
Observable update(Observable o, Object arg),
.
Observer MVC
(model-view-controller), , ,
. ,
, - .
.
Observable.
- ,
notifyObservers, update
.
update .
.
addObserver(Observer o);
deleteObserver(Observer o). notifyObservers, setChanged, ,
.
.
public class TestObservable extends java.util.Observable {
private String name = "";
public TestObservable(String name) {
this.name = name;
}
public void modify(){
setChanged();
}
public String getName(){
return name;
}
}
public class TestObserver implements java.util.Observer{
private String name = "";

Java

Rendered by www.RenderX.com

. 11 42

public TestObserver(String name) {


this.name = name;
}
public void update(java.util.Observable o,Object arg){
String str = "Called update of " + name;
str += " from " + ((TestObservable)o).getName();
str += " with argument " + (String)arg;
System.out.println(str);
}
}
public class Test {
public Test() {
}
public static void main(String[] args) {
Test test = new Test();
TestObservable to = new TestObservable("Observable");
TestObserver o1 = new TestObserver("Observer 1");
TestObserver o2 = new TestObserver("Observer 2");
to.addObserver(o1);
to.addObserver(o2);
to.modify();
to.notifyObservers("Notify argument");
}
}

.
Called update of Observer 2 from Observable with argument Notify argument
Called update of Observer 1 from Observable with argument Notify argument

Observer , .. Java
, Observer
. , ,
, Observer, .

4.

, .
. , ,
, .
().
. Java ,

Hashtable Vector. JDK 1.2
.
Java

Rendered by www.RenderX.com

. 12 42

, .
, , ,
.
, .
-. ,
, ,
.
, ,
. (
), , .
.
-
, java.util

4.1.
4.1.1. Collection
-.
- ,
, .
Collection, (null) .
AbstractCollection, ,

Collection.

4.1.2. Set
.
null. Set
Collection .. Set
Collection. Set
equals , .
AbstractSet
Set

4.1.3. List

( ). D JDK 1.2
Vector, , List. List
Collection .. List
Collection,
. List ListIterator
, , .
AbstractList
List
Java

Rendered by www.RenderX.com

. 13 42

, java.awt List
. .. ,
java.util.List

4.1.4. Map

/. . Hashtable
JDK 1.2 Map. /
.
Map Collection. AbstractMap

Map
, List Set Collection, Map .

4.1.5. SortedSet
Set , .
SortedSet
Comparator
comparator.

4.1.6. SortedMap
Map ,
.

4.1.7. Iterator
Java 1 Enumeration.
Java 2
Iterator. Collection ,
iterator, Iterator. Iterator
Enumeration, , remove,
, Iterator .
. :
.
java.util.Collection
java.util.Set
java.util.List
java.util.Map
java.util.SortedSet
java.util.SortedMap
java.util.Iterator

Java

Rendered by www.RenderX.com

. 14 42

4.2. A .
java.util.AbstratctCollection -
Collection iterator size, ..
. ,
public void add(Object o) ( ,
UnsupportedOperationException).
Collection.
, .
AbstractList AbstractSet.
java.util.AbstratctList - AbstractCollection List.

Java

Rendered by www.RenderX.com

A .

. 15 42

public Object get(int index) public int size().


public void set(int index,Object element); (
, UnsupportedOperationException)
AbstractCollection
iterator, .. get, set, add,
remove.
java.util.AbstratctSet - AbstractCollection
Set. ,
AbstractCollection.
java.util.AbstratctMap -
Map ,
AbstractMap entrySet,
AbstractSet. (Set)
.
Map put
entrySet().iterator()
java.util.AbstratctSequentialList - AbstractList
LinkedList. AbstractList ,
, ,
get(int index), set(int index, Object element), set(int index, Object element),
add(int index, Object element) remove(int index).
listIterator size.
, hasNext, next,
hasPrevious, previous index.
set, add remove.

Java

Rendered by www.RenderX.com

. 16 42

4.3.
java.util.ArrayList - AbstractList Vector.
Vector,
, . ,
ArrayList,

List l = Collections.synchronizedList(new ArrayList(...));
public class Test {
public Test() {

Java

Rendered by www.RenderX.com

. 17 42

}
public static void main(String[] args) {
Test t = new Test();
ArrayList al = new ArrayList();
al.add("Firts element");
al.add("Second element");
al.add("Third element");
Iterator it = al.iterator();
while(it.hasNext()){
System.out.println((String)it.next());
}
System.out.println("\n");
al.add(2,"Insertion");
it = al.iterator();
while(it.hasNext()){
System.out.println((String)it.next());
}
}
}
Firts element
Second element
Third element
Firts element
Second element
Insertion
Third element

java.util.LinkedList - List.
List, ,
, . LinkedList
,
.LinkedList .
public class Test {
public Test() {
}
public static void main(String[] args) {
Test test = new Test();
LinkedList ll = new LinkedList();
ll.add("Element1");
ll.addFirst("Element2");
ll.addFirst("Element3");

Java

Rendered by www.RenderX.com

. 18 42

ll.addLast("Element4");
test.dumpList(ll);
ll.remove(2);
test.dumpList(ll);
String element = (String)ll.getLast();
ll.remove(element);
test.dumpList(ll);
}
private void dumpList(List list){
Iterator it = list.iterator();
System.out.println();
while(it.hasNext()){
System.out.println((String)it.next());
}
}
}
Element3
Element2
Element1
Element4
Element3
Element2
Element4
Element3
Element2

LinkedList ArrayList .
. ArrayList ( )
() .
LinkedList
.
java.util.Hastable - Dictionary. D JDK 1.2, Hashtable
Map. Hashtable
/. , Hshtable
.
.
.
,
, , ,
.
.
, ,
. Java Object.
, Object
Java

Rendered by www.RenderX.com

. 19 42

Object , Object.
hashCode().
Hashtable, :
,
. array.length % hashCode()
, / ,
, , ,
. , ,
.
, ,
, .
, ,
. .
, ,
, ..
.
( ) ,
.
,
, .
, ,

.

.
Hashtable ht = new Hashtable(1000,0.60);
.
101 0.75 .
,
, .
,
.
java.util.HashMap,- AbstractMap Hashtable.
HashMap /. ,
null.
.
. HashMap
get put.
.
,
.
HashMap . ,

,

Java

Rendered by www.RenderX.com

. 20 42

HashMap Hashtable. Hashtable


Java . HashMap JDK 1.2.
, Hashtable , HashMap .
, Hashtable , HasMap .
, , JDK 1.2 Hashtable Map,

JDK.
public class Test {
private class TestObject{
String text = "";
public TestObject(String text){
this.text = text;
};
public String getText(){
return this.text;
}
public void setText(String text){
this.text = text;
}
}
public Test() {
}
public static void main(String[] args) {
Test t = new Test();
TestObject to = null;
HashMap hm = new HashMap();
hm.put("Key1",t.new TestObject("Value 1"));
hm.put("Key2",t.new TestObject("Value 2"));
hm.put("Key3",t.new TestObject("Value 3"));
to = (TestObject)hm.get("Key1");
System.out.println("Object value for Key1 = " + to.getText() + "\n");
System.out.println("Iteration over entrySet");
Map.Entry entry = null;
Iterator it = hm.entrySet().iterator(); //
Map
while(it.hasNext()){
entry = (Map.Entry)it.next();
System.out.println("For key = " + entry.getKey() + " value = " +
((TestObject)entry.getValue()).getText());
}
System.out.println();

Java

Rendered by www.RenderX.com

. 21 42

System.out.println("Iteration over keySet");


String key = "";
it = hm.keySet().iterator(); //
Map
while(it.hasNext()){
key = (String)it.next();
System.out.println( "For key = " + key + " value = " +
((TestObject)hm.get(key)).getText());
}
}
}
Object value for Key1 = Value 1
Iteration
For key =
For key =
For key =

over
Key3
Key2
Key1

entrySet
value = Value 3
value = Value 2
value = Value 1

Iteration
For key =
For key =
For key =

over
Key3
Key2
Key1

keySet
value = Value 3
value = Value 2
value = Value 1

java.util.TreeMap - AbstractMap SortedMap.TreeMap


. ,
Comparable.

(containsKey, get, put remove). null .

. (. ).
public class Test {
public Test() {
}
public static void main(String[] args) {
Test t = new Test();
TreeMap tm = new TreeMap();
tm.put("key","String1");
System.out.println(tm.get("key"));
tm.put("key","String2");
System.out.println(tm.get("key"));
}
}

Java

Rendered by www.RenderX.com

. 22 42

String1
String2

4.4. Collections
, java.util.Collections c
java.util.Collection.
Collections -
.
,
..
-.
Map .
HashMap hm = new HashMap();

Map syncMap = Collections.synchronizedMap(hm);

, JDK 1.2 Vector List.


Vector.
,
, .
public class Test {
private class TestObject{
private String name = "";
public TestObject(String name){
this.name = name;
}
}
private class MyComparator implements Comparator{
public int compare(Object l,Object r){
String left = (String)l;
String right = (String)r;
return -1 * left.compareTo(right);
}
}
public Test() {
}
public static void main(String[] args) {
Test test = new Test();
Vector v = new Vector();

Java

Rendered by www.RenderX.com

Collections

v.add("bbbbb");
v.add("aaaaa");
v.add("ccccc");
System.out.println("Default
test.dumpList(v);
Collections.sort(v);
System.out.println("Default
test.dumpList(v);
System.out.println("Reverse
comparator");
Collections.sort(v,test.new
test.dumpList(v);
}

. 23 42

elements order");

sorting order");
sorting order with providing imlicit
MyComparator());

private void dumpList(List l){


Iterator it = l.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}

5. Properties
Properties ().
String getProperty(String key)
String getProperty(String key,String defaultValue)

.
setProperty(String key, String value) .
load(InputStream inStream)
( 15).
.
/. ,
ISO 8859-1. \r,\n \r\n.
.
! # , ..
. /,
. , ,
. , :, = .
,
\.
, .
. , \t,
\n, \r, \\, \", \', \ \uxxxx, .
\ ,
Java

Rendered by www.RenderX.com

. 24 42

Properties

, .
save(OutputStream inStream,String header)
, load.
, ,
. \uxxxx .
ISO 8859-1. , header
( .. # ),
.
Properties list(PrintWriter out)
save. , .
. Properties .
public class Test {
public Test() {
}
public static void main(String[] args) {
Test test = new Test();
Properties props = new Properties();
StringWriter sw = new StringWriter();
sw.write("Key1 = Vlaue1 \n");
sw.write("
Key2 : Vlaue2 \r\n");
sw.write("
Key3 Vlaue3 \n ");
InputStream is = new ByteArrayInputStream(sw.toString().getBytes());
try {
props.load(is);
}
catch (IOException ex) {
ex.printStackTrace();
}
props.list(System.out);
props.setProperty("Key1","Modified Value1");
props.setProperty("Key4","Added Value4");
props.list(System.out);
}
}
-- listing properties -Key3=Vlaue3
Key2=Vlaue2
Key1=Vlaue1
-- listing properties -Key4=Added Value4
Key3=Vlaue3
Key2=Vlaue2
Key1=Modified Value1

Java

Rendered by www.RenderX.com

. 25 42

6. Comparator

Comparator.
compare(Object obj1,Object obj2), ,
,
. compare
-1
obj1 < obj2
0 obj1 = obj2
1 obj1 > obj2

7. Arrays
Arrays
, , , . Arrays
public List aList(a[] arr);
. List .
, .. -
Object[] toArray()
Collections.
public class Test {
public Test() {
}
public static void main(String[] args) {
Test test = new Test();
String[] arr = {"String 1","String 4","String 2","String 3"};
test.dumpArray(arr);
Arrays.sort(arr);
test.dumpArray(arr);
int ind = Arrays.binarySearch(arr,"String 4");
System.out.println("\nIndex of \"String 4\" = " + ind);
}
void dumpArray(String arr[]){
System.out.println();
for(int cnt=0;cnt < arr.length;cnt++){
System.out.println(arr[cnt]);
}
}
}

Java

Rendered by www.RenderX.com

. 26 42

StringTokenizer

8. StringTokenizer
(tokens).
StringTokenizer(String
str). ,
- StringTokenizer(String str,String delim)
StringTokenizer(String str,String delim,Boolean retirnDelims)
.
public class Test {
public Test() {
}
public static void main(String[] args) {
Test test = new Test();
String toParse = "word1;word2;word3;word4";
StringTokenizer st = new StringTokenizer(toParse,";");
while(st.hasMoreTokens()){
System.out.println(st.nextToken());
}
}
}
word1
word2
word3
word4

9. BitSet
BitSet .
,
. BitSet BitSet
AND, OR XOR ( )
BitSet ( )
. 0 (false).
BitSet set(int index) clear(int index)
int length() "" , int size()
BitSet.
public class Test {
public Test() {
}
public static void main(String[] args) {
Test test = new Test();
Java

Rendered by www.RenderX.com

. 27 42

BitSet bs1 = new BitSet();


BitSet bs2 = new BitSet();
bs1.set(0);
bs1.set(2);
bs1.set(4);
System.out.println("Length = " + bs1.length() + " size = " +
bs1.size());
System.out.println(bs1);
bs2.set(1);
bs2.set(2);
bs1.and(bs2);
System.out.println(bs1);
}
}

Length = 5 size = 64
{0, 2, 4}
{2}

,
BitSet long.

10. Random
Random .
"" 48 . Random
,
.
Random
Java
double nextGaussian() -
0.0 1.0 , void
nextBytes(byte[] arr) - arr byte.
Random
public class Test {
public Test() {
}
public static void main(String[] args) {
Test test = new Test();
Random r = new Random(100);
// Generating the same sequence numbers
for(int cnt=0;cnt<9;cnt++){
System.out.print(r.nextInt() + " ");

Java

Rendered by www.RenderX.com

. 28 42

}
System.out.println();
r = new Random(100);
for(int cnt=0;cnt<9;cnt++){
System.out.print(r.nextInt() + " ");
}
System.out.println();
// Generating sequence of bytes
byte[] randArray = new byte[8];
r.nextBytes(randArray);
test.dumpArray(randArray);
}
void dumpArray(byte[] arr){
for(int cnt=0;cnt< arr.length;cnt++){
System.out.print(arr[cnt]);
}
System.out.println();
}
}
-1193959466 -1139614796 837415749 -1220615319 -1429538713 118249332 -951589224
-1193959466 -1139614796 837415749 -1220615319 -1429538713 118249332 -951589224
81;-6;-107;77;118;17;93;-98;

11.
11.1. Locale
Locale .
, .
, ,
.
Locale
Locale(String language, String country)
Locale(String language, String country, String variant)


, ISO. ( XXX1,XXX2).

Locale.getISOLanguages() Locale.getISOCountries() .
variant
. ,

Java

Rendered by www.RenderX.com

Locale

. 29 42

,
.

Locale l = new Locale("ru","RU");
Locale l = new Locale("en","US","WINDOWS");

getDefault() ,
JVM.
. Locale.US
Locale.GERMAN.
Loale ,
.
public class Test {
public Test() {
}
public static void main(String[] args) {
Test test = new Test();
Locale l = Locale.getDefault();
System.out.println(l.getCountry() + " " + l.getDisplayCountry() +
" + l.getISO3Country());
System.out.println(l.getLanguage() + " " + l.getDisplayLanguage()
" " + l.getISO3Language());
System.out.println(l.getVariant() + " " + l.getDisplayVariant());
l = new Locale("ru","RU","WINDOWS");
System.out.println(l.getCountry() + " " + l.getDisplayCountry() +
" + l.getISO3Country());
System.out.println(l.getLanguage() + " " + l.getDisplayLanguage()
" " + l.getISO3Language());
System.out.println(l.getVariant() + " " + l.getDisplayVariant());
}
}

"
+

"
+

US United States USA


en English eng

RU Russia RUS
ru Russian rus
WINDOWS WINDOWS

Java

Rendered by www.RenderX.com

. 30 42

11.2. ResourceBundle
ResourceBundle
. , ,
ResourceBundle.
ResourceBundle ,
.
, , ,
..
- , .
,
. , MyResources,
MyResources_en, - MyResources_ru.
,
. MyResources_de_CH
. variant (.
Locale
). , UNIX
: MyResources_de_CH_UNIX

getBundle.
ResourceBundle myResources =
someLocale);

ResourceBundle.getBundle("MyResources",

, , getBundle,
, .
. ,
, . ,
.
baseclass + "_" + language1 + "_" + country1 + "_" + variant1
baseclass + "_" + language1 + "_" + country1 + "_" + variant1 + ".properties"
baseclass
baseclass
baseclass
baseclass
baseclass
baseclass

+
+
+
+
+
+

"_"
"_"
"_"
"_"
"_"
"_"

+
+
+
+
+
+

language1
language1
language1
language1
language2
language2

baseclass
baseclass
baseclass
baseclass
baseclass

+
+
+
+

"_"
"_"
"_"
"_"

+
+
+
+

language2 + "_" + country2


language2 + "_" + country2 + ".properties"
language2
language2 + ".properties"

Java

Rendered by www.RenderX.com

+ "_" + country1
+ "_" + country1 + ".properties"
+ ".properties"
+ "_" + country2 + "_" + variant2
+ "_" + country2 + "_" + variant2 + ".properties"

ResourceBundle

. 31 42

baseclass + ".properties"

1 2 .
ResourceBundle fr_CH (
), en_US
ResourceBundle MyResources, ResourceBundle .
MyResources_fr_CH
MyResources_fr
MyResources_en_US
MyResources_en
MyResources

getBundle ,
. ..
, ".properties"
.
,
.. , . ,
(.. getResourceBundle), private
..
, ..
MyResource, MyResource.class
ResourceBundle /. ,
ResourceBundle ,
Enumeration getKeys()
public Object handleGetObject(String key)

, ResourceBundle, .
ResourceBundle.
public class MyResource extends ResourceBundle {
private Hashtable res = null;
public MyResource() {
res = new Hashtable();
res.put("TestKey","English Variant");
}
public Enumeration getKeys() {
return res.keys();
}
protected Object handleGetObject(String key) throws
Java

Rendered by www.RenderX.com

. 32 42

java.util.MissingResourceException {
return res.get(key);
}
}
public class MyResource_ru_RU extends ResourceBundle{
private Hashtable res = null;
public MyResource_ru_RU() {
res = new Hashtable();
res.put("TestKey"," ");
}
public Enumeration getKeys() {
return res.keys();
}
protected Object handleGetObject(String key) throws
java.util.MissingResourceException {
return res.get(key);
}
}
public class Test {
public Test() {
}
public static void main(String[] args) {
Test test = new Test();
ResourceBundle rb =
ResourceBundle.getBundle("experiment.MyResource",Locale.getDefault());
System.out.println(rb.getString("TestKey"));
rb = ResourceBundle.getBundle("experiment.MyResource",new
Locale("ru","RU"));
System.out.println(rb.getString("TestKey"));
}
}
English Variant

, , ResourceBundle
. ,
.
public interface Behavior {
public String getBehavior();
public String getCapital();
}

Java

Rendered by www.RenderX.com

ResourceBundle

. 33 42

public class EnglishBehavior implements Behavior{


public EnglishBehavior() {
}
public String getBehavior(){
return "English behavior";
}
public String getCapital(){
return "London";
}
}
public class RussianBehavior implements Behavior {
public RussianBehavior() {
}
public String getBehavior(){
return " ";
}
public String getCapital(){
return "";
}
}
public class MyResourceBundle_ru_RU extends ResourceBundle {
Hashtable bundle = null;
public MyResourceBundle_ru_RU() {
bundle = new Hashtable();
bundle.put("Bundle description"," ");
bundle.put("Behavior",new RussianBehavior());
}
public Enumeration getKeys() {
return bundle.keys();
}
protected Object handleGetObject(String key) throws
java.util.MissingResourceException {
return bundle.get("key");
}
}
public class MyResourceBundle_en_EN {
Hashtable bundle = null;
public MyResourceBundle_en_EN() {
bundle = new Hashtable();
bundle.put("Bundle description","English resource set");
bundle.put("Behavior",new EnglishBehavior());
}
public Enumeration getKeys() {
return bundle.keys();
}
protected Object handleGetObject(String key) throws
Java

Rendered by www.RenderX.com

. 34 42

java.util.MissingResourceException {
return bundle.get("key");
}
}
public class MyResourceBundle extends ResourceBundle {
Hashtable bundle = null;
public MyResourceBundle() {
bundle = new Hashtable();
bundle.put("Bundle description","Default resource bundle");
bundle.put("Behavior",new EnglishBehavior());
}
public Enumeration getKeys() {
return bundle.keys();
}
protected Object handleGetObject(String key) throws
java.util.MissingResourceException {
return bundle.get(key);
}
}
public class Using {
public Using() {
}
public static void main(String[] args) {
Using u = new Using();
ResourceBundle rb =
ResourceBundle.getBundle("lecture.MyResourceBundle",Locale.getDefault());
System.out.println((String)rb.getObject("Bundle description"));
rb = ResourceBundle.getBundle("lecture.MyResourceBundle",new
Locale("en","EN"));
System.out.println((String)rb.getObject("Bundle description"));
Behavior be = (Behavior)rb.getObject("Behavior");
System.out.println(be.getBehavior());
System.out.println(be.getCapital());
}
}></eg>
<eg><![CDATA[

English resource bundle
English behavior
London></eg>
</div2>
<div2 id="JAVA-LEC14-ListResourceBundle ">
<head> ListResourceBundle PropertiesResourceBundle</head>
<p> <kw>ResourceBundle</kw>
<kw>ListResourceBundle</kw> <kw>PropertiesResourceBundle</kw>. </p>
Java

Rendered by www.RenderX.com

ResourceBundle

. 35 42

<p>
<kw>PropertiesResourceBundle</kw> ,
. </p>
<p> ,
<kw>PropertiesResourceBundle</kw>
. </p>
<p>
.
<code>.properties</code>, <code>baseclass + "_" +
language1 + "_" + country1 + ".properties"</code>
<kw>ResourceBundle</kw> <code>baseclass + "_" +
language1 + "_" + country1</code> <code>properties. </code>
<kw>ResourceBundle</kw> <kw>resources</kw>,
<kw>resources</kw>.
() </p>
<eg><![CDATA[
getBundle("resources.MyResource",Locale.getDefault());

ListResourceBundle
. ListResourceBundle

Object[][] getContents() .


public class MyResource extends ListResourceBundle {
Vector v = new Vector();
Object[][] resources = {
{"StringKey","String"},
{"DoubleKey",new Double(0.0)},
{"VectorKey",v},
};
public MyResource(){
super();
v.add("Element 1");
v.add("Element 2");
v.add("Element 3");
}
protected Object[][] getContents() {
return resources;
}
}
public class Test {
public Test() {
Java

Rendered by www.RenderX.com

. 36 42

}
public static void main(String[] args) {
Test test = new Test();
ResourceBundle rb =
ResourceBundle.getBundle("experiment.MyResource",Locale.getDefault());
Vector v = (Vector)rb.getObject("VectorKey");
Iterator it = v.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
Element 1
Element 2
Element 3

,
, ResourceBundle.
, PropertiesResourceBundle
, ,
. Image
.
.. .
,
, .
. (. )
ResourceBundle .
( ResourceBundle,
ListResourceBundle), ,
. .. ResourceBundle
String.
MyResource .
public class MyResource extends ListResourceBundle {
Vector v = new Vector();
Object[][] resources = {
{"Key1","String1"},
{new Double(1.0),"Double value"}
};

protected Object[][] getContents() {


return resources;
}
}
Java

Rendered by www.RenderX.com

ResourceBundle

. 37 42

Double
.
public class Test {
public Test() {
}
public static void main(String[] args) {
Test test = new Test();
ResourceBundle rb =
ResourceBundle.getBundle("experiment.MyResource",Locale.getDefault());
System.out.println(rb.getString("Key1"));
System.out.println(rb.getObject(new Double(1.0)));
}
}

12.

Date , Calendar.
Calendar , GregorianCalendar.

Observer Observable MVC


.

(Collections)
.

(List) . ( ,

(Set) .

(Maps) , .

,
.

(LinkedList) ,
,

(Tree) ,
, ,
.

,
, ,
.

Properties /.
() .

Java

Rendered by www.RenderX.com

. 38 42

Comparator
, , , .

Arrays - ,
. .

StringTokenizer - ,
.

,
, BitSet

, ,
ResourceBundle, ListResourceBundle, PropertiesResourceBundle. Locale.

13.
14-1. ,
0 100 5. .
a.) public int getRandom5(){
return (int)(Math.random()*20) * 5;
}

b.) public int getRandom5(){


Math m = new Math()
return (int)(m.random()*20) * 5;
}

c.) public int getRandom5(){


return (Math.random()*20) * 5;
}

a. b .. Math,
.. Math . c , Math.random()
double 0.0 1.0.
double, int, , .

14-2. java.lang.Runtime ?
a.) Runtime
Runtime r = Runtime.getRuntime();

b.) gc() Runtime()


Java

Java

Rendered by www.RenderX.com

. 39 42

c.) freeMemory() Runtime,


.
a. b ..
, gc() JVM . c , ..
freeMemory , JVM.

14-3. ,
double .
.
double getCos(double angle){
return Math.cos(angle);
}

a.)

b.)

double getCos(double angle){


return Math.cos(angle * Math.PI / 180);
}

c.) double getCos(double angle){


return Math.cos(angle * PI / 180);
}

b. a ..
, . c .. PI
Math.

14-4. JDK 1.2 ,


. , .
a.) a java.util.List
b.) java.util.TreeMap
c.) java.util.AbstractList
d.) java.util.SortedMap
e.) java.util.Iterator
f.) java.util.Collections
a, d, e. TreeMap , AbstractList , Collections
-.

14-5. java.util.Vector java.util.Hashtable

a.) Vector
.
b.) Vector .

Java

Rendered by www.RenderX.com

. 40 42

c.) Hashtable String


d.) Hashtable .
e.) Hashtable Vector ,
,
.
b, e. a .. Vector .
-. c ,
.. , Hashtable . d , ..
Hashtable .

14-6. .
double getCos(double angle){
return Math.cos(angle);
}
public static void showStatus(Boolean flag){
if(flag){
System.out.println(FIRED)
}else{
System.out.println(NOT READY);
}
}

?
a.) if(flag){ if(flag.equals(true)
b.) public static void showStatus(Boolean flag){ public static void
showStatus(boolean flag){
c.) if(flag){ if(flag.booleanValue()){
b, c. a .. equals ,
true Boolean.

14-7. ?
String str1 = "abc";
String str2 = "abc";
System.out.println(str1 == str2);

a.) true
a.) false
a. .. , str1 str2 ,
.

Java

Rendered by www.RenderX.com

. 41 42

14-8. sb 2
?
1. StringBuffer sb = new StringBuffer("abc");
2. sb.append("x");

a.)
b.)
a. String.

14-9. Vector?
a.) TreeSet.
b.) AbstractCollection.
c.) c ArrayList
d.) d Hashtable
c .. ArrayList Vector. a ..
TreeSet . b , .. AbstractCollection . d ,
.. Hashtable /.

14-10. Hashtable?
a.) a SortedMap
b.) b Map
c.) c List
d.) d SortedSet
e.) e
b. a, c, d , .. Hashtable . e ,
.. JDK 1.2 Hashtable Map.

Java

Rendered by www.RenderX.com

Java ()

Java

Rendered by www.RenderX.com

Java
15. java.io
20 2003
:
( Sun ) <vyazovick@itc.mipt.ru>
( Sun ) < gene@itc.mipt.ru>
Copyright 2003 Sun , , .

Java ,
.
, , ,
.. (
InputStream OutputStream) (Reader Writer).
java.io ,
.
.

Rendered by www.RenderX.com

ii

15. java.io..................................................................................................... 1
1. /. (stream)..........................................................1
1.1. InputStream OutputStream...................................................................... 3
1.2. - .................................................................... 5
1.2.1. ByteArrayInputStream ByteArrayOutputStream ............................5
1.2.2. FileInputStream FileOutputStream ................................................6
1.2.3. PipedInputStream PipedOutputStream ...................................................... 8
1.2.4. StringBufferInputStream................................................................................. 9
1.2.5. SequenceInputStream ...................................................................................9
1.3. FilterInputStreeam FilterOutputStream. ....................... 11
1.3.1. BufferedInputStream BufferedOutputStream ........................................... 11
1.3.2. LineNumberInputStream ............................................................................. 13
1.3.3. PushBackInputStream .................................................................................13
1.3.4. PrintStream...................................................................................................14
1.3.5. DataInputStream DataOutputStream ....................................................... 14
2. Serialization.....................................................................................................................15
2.1. ..................................................................................................... 22
3. Reader Writer. .......................................................................23
4. StreamTokenizer.................................................................................................. 26
5. .......................................................................................27
5.1. File...............................................................................................................27
5.2. RandomAccessFile......................................................................................29
6. .................................................................................................................... 29
7. ...................................................................................................30

Java

Rendered by www.RenderX.com

. 1 34

15. java.io
.
1. /. (stream)......................................................... 1
1.1. InputStream OutputStream............................................................................ 3
1.2. - .......................................................................... 5
1.2.1. ByteArrayInputStream ByteArrayOutputStream ................................. 5
1.2.2. FileInputStream FileOutputStream ..................................................... 6
1.2.3. PipedInputStream PipedOutputStream ............................................................ 8
1.2.4. StringBufferInputStream.......................................................................................9
1.2.5. SequenceInputStream .........................................................................................9
1.3. FilterInputStreeam FilterOutputStream. ............................. 11
1.3.1. BufferedInputStream BufferedOutputStream ................................................. 11
1.3.2. LineNumberInputStream ................................................................................... 13
1.3.3. PushBackInputStream .......................................................................................13
1.3.4. PrintStream........................................................................................................ 14
1.3.5. DataInputStream DataOutputStream ............................................................. 14

2. Serialization.................................................................................................................... 15
2.1. ........................................................................................................... 22

3. Reader Writer. ...................................................................... 23


4. StreamTokenizer................................................................................................. 26
5. ...................................................................................... 27
5.1. File.....................................................................................................................27
5.2. RandomAccessFile............................................................................................29

6. ................................................................................................................... 29
7. .................................................................................................. 30

1. /. (stream)
. ,
, -
, .

. , ,
, -
Java

Rendered by www.RenderX.com

. 2 34

/. (stream)

. , , ,
- , , ()
.. - , ,
, () .. ,

.
, ,
- /. Java java.io (input/output).
/
, .
,
( 4 ),
.
(, HTML ),
( ).
.
Java /
(stream). ,
. ,
- , - () .
stream ,
,
/.
Java .
java.io.
. -
, .
.
"" , , ,
0 1 ( ,
; , 1
, 0 - ).
, 8 . , , 1 ,
0 28-1=255, , , -128 +127.
byte Java , .
,
. , java.io
, .
, - double , ,
. ,
(.. ) -
. ,
- ,
.

Java

Rendered by www.RenderX.com

InputStream OutputStream

. 3 34

/. ,
.
InputStream:

- OutputStream:

1.1. InputStream OutputStream


InputStream - , .. . ,
.
, InputStream.
read() ( ).
, , , -.
,
int. ,
0 255 (
int 4
). ,
-128 +127 byte Java.
, ,
-1.
- - ,
java.io.IOException. Exception, ..
. , ,
, , , ,
Java

Rendered by www.RenderX.com

. 4 34

/. (stream)

. , ,
.
read() - ,
-.
, -
. read(),
byte[].
read() ( ), .
, , .
, ,
. , , ()
. int, ,
. , 0
.
, ,
read(), byte[], int
. - , ,
- , . ,
int - offset () length (),
java.io.
read(), ,
. , ,
, . ,
, - read()
"".
, - available().
int, ,
. , ,
, .
available() - , ,
.
, .
close(). ,
.
, InputStream - , OutputStream
- .
OutputStream, , write() -
int, byte[], byte[], int-.
void, .
write(int) , - .
int,
byte - 8 . 24
. java.io.IOException,
, , , -.

Java

Rendered by www.RenderX.com

. 5 34

, write()
. , - byte[],
int- - . ,
- , ,
+ -
IndexOutOfBoundsException.
, ,
. , - ,
10 , 200 . 200
,
2000 .
( )
. , , ,
flush(), OutputStream.
, - ,
.
, .
close(). , ,
.
. OutputStream
close() .
, InputStream OutputStream
. . -
, .
, , , , .. , ,
, , .

1.2. -
1.2.1. ByteArrayInputStream ByteArrayOutputStream
, - , ,
. ByteArrayInputStream ,
. ,
byte[]. , read(),
. :
byte[] bytes = {1,-1,0};
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
int readedInt = in.read(); // readedInt=1
System.out.println("first element read is: " +readedInt);
readedInt = in.read(); // readedInt=255. (byte)readedInt
-1
System.out.println("second element read is: " +readedInt);
readedInt = in.read(); // readedInt=0
System.out.println("third element read is: " +readedInt);

Java

Rendered by www.RenderX.com

. 6 34

/. (stream)

, :
first element read is: 1
second element read is: 255
third element read is: 0

read() bytes,
ByteArrayInputStream. -1,
. 255. , ,
, read byte, int -
( ). , -1
11111111 , , ,
24- , 255( ).
byte, .
, , ByteArrayOutputStream.
byte[], ,
write(). ,
toByteArray(). :
ByteArrayOutputStream out = new ByteArrayOutputStream();
out.write(10);
out.write(11);
byte[] bytes = out.toByteArray();

bytes : 10 11.
ByteArrayInputStream ByteArrayOutputStream
, , . ,
.
, ,
, , - .

1.2.2. FileInputStream FileOutputStream


FileInputStream .
,
. ,
,
. ,
,
java.io.FileNotFoundException.
, , read(),
.
FileOutputStream.
, , ,
. ,
, FileOutputStream
. , write(),
Java

Rendered by www.RenderX.com

. 7 34

. close(),
, . :
byte[] bytesToWrite = {1, 2, 3};
byte[] bytesReaded = new byte[10];
String fileName = "d:\\test.txt";
try {
//
FileOutputStream outFile = new FileOutputStream(fileName);
System.out.println(" ");
//
outFile.write(bytesToWrite);
System.out.println(": " + bytesToWrite.length + " ");
//
outFile.close();
System.out.println(" ");
//
FileInputStream inFile = new FileInputStream(fileName);
System.out.println(" ");
// ,
int bytesAvailable = inFile.available();
System.out.println(" : " + bytesAvailable + " ");
//
int count = inFile.read(bytesReaded,0,bytesAvailable);
System.out.println(": " + count + " ");
inFile.close();
System.out.println(" ");
} catch (FileNotFoundException e) {
System.out.println(" : " + fileName);
} catch (IOException e) {
System.out.println(" /: " + e.toString());
}

FileInputStream available() ,
, .
,
- available() ,
. , ,
,
.

.
finally .
} finally {
try{inFile.close();}catch(IOException e){};
}

Java

Rendered by www.RenderX.com

. 8 34

/. (stream)

, ,
.

1.2.3. PipedInputStream PipedOutputStream


PipedInputStream PipedOutputStream ,
- PipedInputStream
PipedOutputStream. ,
.
: PipedInputStream PipedOutputStream, . PipedOutputStream
PipedInputStream .
- , PipedOutputStream ,
PipedInputStream.
connect()
PipedStream, .
PipedInputStream PipedOutputStream.
try {
int countRead = 0;
byte[] toRead = new byte[100];
PipedInputStream pipeIn = new PipedInputStream();
PipedOutputStream pipeOut = new PipedOutputStream(pipeIn);
// ,
while(countRead<toRead.length){
//
for(int i=0; i<(Math.random()*10); i++){
pipeOut.write((byte)(Math.random()*127));
}
// ,
// .
int willRead = pipeIn.available();
if(willRead+countRead>toRead.length)
//
willRead = toRead.length-countRead;
countRead += pipeIn.read(toRead, countRead, willRead);
}
} catch (IOException e) {
pr("Impossible IOException occur: ");
e.printStackTrace();
}

,
. ,
, (
- Thread, Stream Thread - ),

PipedStream. PipedInputStream
Java

Rendered by www.RenderX.com

. 9 34

PipedOutputStream, Thread.
, :
// inStream - PipedInputStream
try{
while(true){
byte[] readedBytes = null;
synchronized(inStream){
int bytesAvailable = inStream.available();
readedBytes = new byte[bytesAvailable];
inStream.read(readedBytes);
}
// do some work with readedBytes
//
}catch(IOException e){
/* IOException , inStream
PipedOutputStream ,
inStream */
System.out.println(" inStream ");
}

inStream ,
synchronized(inStream){} ,
inStream.available() inStream.read(),
inStream. inStream.read(readedBytes)
, , - .

1.2.4. StringBufferInputStream
StringBufferInputStream - ,
.
.
- , - String byte,
StringBufferInputStream. ,
, ,
. StringBufferInputStream
String. , read(),
String.
- 8 (
char 2- ).

1.2.5. SequenceInputStream
SequenceInputStream .
.
- , ,
. SequenceInputStream ,
, .

Java

Rendered by www.RenderX.com

. 10 34

/. (stream)


InputStream - Enumeration .
read(), SequenceInputStream .
( -1),
close(), .
, ,
. , ,
, SequenceInputStream -1,
, . SequenceInputStream
close() , . close()
SequenceeInputStream ,
.
:
FileInputStream inFile1 = null;
FileInputStream inFile2 = null;
SequenceInputStream sequenceStream = null;
FileOutputStream outFile = null;
try {
inFile1 = new FileInputStream("file1.txt");
inFile2 = new FileInputStream("file2.txt");
sequenceStream = new SequenceInputStream(inFile1, inFile2);
outFile = new FileOutputStream("file3.txt");
int readedByte = sequenceStream.read();
while(readedByte!=-1){
outFile.write(readedByte);
readedByte = sequenceStream.read();
}
} catch (IOException e) {
System.out.println("IOException: " + e.toString());
} finally {
try{sequenceStream.close();}catch(IOException e){};
try{outFile.close();}catch(IOException e){};
}

file3.txt
file1.txt file2.txt - file1.txt file2.txt.
finally. , close() IOException,
try-catch . try-catch
close() - ,
.
inFile1 inFile2 -
sequnceStream - ,
sequencecStream close().
SequenceInputStream :
Enumeration, , Enumeration
SequenceInputStream:

Java

Rendered by www.RenderX.com

FilterInputStreeam FilterOutputStream. .

. 11 34

Vector vector = new Vector();


vector.add(new StringBufferInputStream("Begin file1\n"));
vector.add(new FileInputStream("file1.txt"));
vector.add(new StringBufferInputStream("\nEnd of file1, begin file2\n"));
vector.add(new FileInputStream("file2.txt"));
vector.add(new StringBufferInputStream("\nEnd of file2"));
Enumeration enum = vector.elements();
sequenceStream = new SequenceInputStream(enum);

sequenceeStream
, file3.txt file1.txt file2.txt
- , file1.txt file2.txt
file3.txt.

1.3. FilterInputStreeam FilterOutputStream. .


, / -
, , ,
.
. ,
, . (
.) -
. ,
- /. java.io .
-, , ,
.
java.io / FilterInputStream ( ) FilterOutputStream ( ).
/ - InputStream OutputStream
.
InputStream protected.
. ( ),
.
.
- ,
, :
, ,
.

1.3.1. BufferedInputStream BufferedOutputStream


, ,
. BuffereInputStream
BufferedOutputStream.
BufferedInputStream - ,
. , ( read())
( skip()), ,
Java

Rendered by www.RenderX.com

. 12 34

/. (stream)

. BufferedInputStream
mark() reset(). InputStream,
IOException. mark()
reset() , ,
mark(), ,
.
BufferedOutputStream - ,
/ .
.
, , ,
.
- flush().
( close()).
, .

.
try {
String fileName = "d:\\file1";
InputStream inStream = null;
OutputStream outStream = null;
//
long timeStart = System.currentTimeMillis();
outStream = new FileOutputStream(fileName);
outStream = new BufferedOutputStream(outStream);
for(int i=1000000; --i>=0;){
outStream.write(i);
}
long time = System.currentTimeMillis() - timeStart;
System.out.println("Writing durates: " + time + " millisec");
outStream.close();
//
timeStart = System.currentTimeMillis();
inStream = new FileInputStream(fileName);
while(inStream.read()!=-1){
}
time = System.currentTimeMillis() - timeStart;
inStream.close();
System.out.println("Direct read durates " + (time) + " millisec");
timeStart = System.currentTimeMillis();
inStream = new FileInputStream(fileName);
inStream = new BufferedInputStream(inStream);
while(inStream.read()!=-1){
}
time = System.currentTimeMillis() - timeStart;
inStream.close();
System.out.println("Buffered read durates " + (time) + " millisec");

Java

Rendered by www.RenderX.com

FilterInputStreeam FilterOutputStream. .

. 13 34

} catch (IOException e) {
pr("IOException: " + e.toString());
e.printStackTrace();
}

, , :
Writing durates: 359 millisec
Direct read durates 6546 millisec
Buffered read durates 250 millisec

,
, .
10 (!) ,
.
, ,
, BufferedOutputStream.
.
BufferedInputStream BufferedOutputStream
, .

. , - LineNumberInputStream deprecated
jdk 1.1, .

1.3.2. LineNumberInputStream
InputStream , ,
. ,
getLineNumber().
, setLineNumber(int lineNumber).
, '\n' '\r'
'\r\n' . OutputFilter
- .

1.3.3. PushBackInputStream
.
unread(). ,
- ,
. ,
, .
, .
OutputFilter - .
deprecated,
, .
, out err
System , ,
.

Java

Rendered by www.RenderX.com

. 14 34

/. (stream)

1.3.4. PrintStream
. PrintStream
print(), java Object.

String.valueOf(), . ,
, . ,
, print .
, ,
. PrintStream Unicode.
Writer`.
InputFilter - .
, - .
.

.

1.3.5. DataInputStream DataOutputStream


byte.
java, DataInput
DataOutput, - - DataInputStream
DataOutputStream. /
, .1 .2.
DataInput DataOutput , DataInputStream DataOutputStream, ,
. byte .
,
- , ,
. , , , int long,
short - -
,
- , .
:
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
DataOutputStream outData = new DataOutputStream(out);
outData.writeByte(128); // it would write -128, as casted to byte
outData.writeInt(128);
outData.writeLong(128);
outData.writeDouble(128);
outData.close();
byte[] bytes = out.toByteArray();
InputStream in = new ByteArrayInputStream(bytes);
DataInputStream inData = new DataInputStream(in);
System.out.println("Read data in order it was writen: ");
System.out.println("readByte: " + inData.readByte());

Java

Rendered by www.RenderX.com

FilterInputStreeam FilterOutputStream. .

. 15 34

System.out.println("readInt: " + inData.readInt());


System.out.println("readLong: " + inData.readLong());
System.out.println("readDouble: " + inData.readDouble());
inData.close();
System.out.println("read the same data in other order (first byte is
skipped):");
in = new ByteArrayInputStream(bytes);
inData = new DataInputStream(in);
System.out.println("readInt: " + inData.readInt());
System.out.println("readDouble: " + inData.readDouble());
System.out.println("readLong: " + inData.readLong());
inData.close();
} catch (Exception e) {
System.out.println("Impossible IOException occurs: " + e.toString());
e.printStackTrace();
}

DataInput DataOutput /
Java.
ObjectInput ObjectOutput . java.io
- ObjectInputStream ObkectOutputStream.

- ,
..
(Serialization) , , -
- .

2. Serialization
java - .
, ,
java.io.Serializable(
, , ).
java.io.Serializable .
, .
, ,
java.io.NotSerializableException

, , ,
,
( , ),

, .
Java - ,
Windows, ,
Unix, .

Java

Rendered by www.RenderX.com

. 16 34

Serialization

java.io ObjectInput, ObjectOutput


ObjectInputStream ObjectOutputStream .
OutputStream,
ObjectOutputStream. writeObject()
. :
ByteArrayOutputStream os = new ByteArrayOutputStream();
Object objSave = new Integer(1);
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(objSave);

, objSave,

byte[] bArray = os.toByteArray();

, :
ByteArrayInputStream is = new ByteArrayInputStream(bArray);
ObjectInputStream ois = new ObjectInputStream(is);
Object objRead = ois.readObject();

, :
System.out.println("readed object is: " + objRead.toString());
System.out.println("Object equality is: " + (objSave.equals(objRead)));
System.out.println("Reference equality is: " + (objSave==objRead));

:
readed object is: 1
Object equality is: true
Reference equality is: false

, ( -
), .
,
.
. , ,
,
. :
package demo.io;
import java.io;
class Point implements java.io.Serializable{
double x;
double y;
public Point(double x, double y) {
Java

Rendered by www.RenderX.com

. 17 34

this.x = x;
this.y = y;
}
public String toString() {
return "("+x+","+y+") reference="+super.toString();
}
}
class Line implements java.io.Serializable{
Point point1;
Point point2;
int index;
public Line() {
System.out.println("Constructing empty line");
}
Line(Point p1, Point p2, int index) {
System.out.println("Constructing line: " + index);
this.point1 = p1;
this.point2 = p2;
this.index = index;
}
public int getIndex() {return index;}
public void setIndex(int newIndex) {index = newIndex;}
public void printInfo() {
System.out.println("Line: " + index);
System.out.println(" Object reference: " + super.toString());
System.out.println(" from point "+point1);
System.out.println(" to point "+point2);
}
}
public class Main {
public static void main(java.lang.String[] args) {
Point p1 = new Point(1.0,1.0);
Point p2 = new Point(2.0,2.0);
Point p3 = new Point(3.0,3.0);
Line line1 = new Line(p1,p2,1);
Line line2 = new Line(p2,p3,2);
System.out.println("line 1 = " + line1);
System.out.println("line 2 = " + line2);
String fileName = "d:\\file";
try{
// write objects to file
FileOutputStream os = new FileOutputStream(fileName);
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(line1);
oos.writeObject(line2);
//change state of line 1 and write it again
line1.setIndex(3);
//oos.reset();
oos.writeObject(line1);
Java

Rendered by www.RenderX.com

. 18 34

Serialization

// close stream
// it is enought to close only filter stream
oos.close();
os.close();
//read objects
System.out.println("Read objects:");
FileInputStream is = new FileInputStream(fileName);
ObjectInputStream ois = new ObjectInputStream(is);
while(is.available()>0){
Line line = (Line)ois.readObject();
line.printInfo();
}
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
}

, available() ObjectInputStream, InputStream, .


, available() ObjectOutputStream ,
: - (-1),
,
, (,
, ),
, 0.
:
Constructing line: 1
Constructing line: 2
Read objects:
Line: 1
Object reference: study.java.Line@2dc5
from point (1.0,1.0) reference=study.java.Point@322b
to point (2.0,2.0) reference=study.java.Point@3481
Line: 2
Object reference: study.java.Line@5214
from point (2.0,2.0) reference=study.java.Point@3481
to point (3.0,3.0) reference=study.java.Point@5435
Line: 1
Object reference: study.java.Line@2dc5
from point (1.0,1.0) reference=study.java.Point@322b
to point (2.0,2.0) reference=study.java.Point@3481

, Point - point2 point1


- - . ,
Java

Rendered by www.RenderX.com

. 19 34

- , , . ,
, index 3,
1. , , ,
, ,
, ,
. ,
, .
,
.
,
. ,
,
.. ,
, .. -
.
, line1, ,
, . ,
, , ObjectOutputStream
reset().

//reset();

, , line1
. point2
point1 line1. , , - line1
, , Point .
, Line ,
, . ,
-
, Point .
, .
, , -
, .
, , ,
. ,
, ,
,
. . ,
java.io.InvalidClassException .
, ,

class AbstractEntity{
public AbstractEntity(){
System.out.println("Create Abstract Entity");
}
Java

Rendered by www.RenderX.com

. 20 34

Serialization

- , Point, AbstractEntity.
class Point extends AbstractEntity implements java.io.Serializable

, ( ,
Serializable) .
.
.
, , Serializable.
java.io.NotSerializableException .
:
.
, . Point,
, Point.class ,
CLASSPATH. "d:\file",
readObject() ClassNotFoundException.
ObjectInputStream,
java.io.StreamCorruptedException. InputStream
ObjectInputStream ,
,
Java-,
. java.io.StreamCorruptedException
,
InputStream. ObjectInputStream ,
,
java.io.StreamCorruptedException . , InputStream
read() ObjectInputStream, (-1),
. ObjectOutputStream
Java( ObjectOutput DataOutput).
,
Java, java.io.OptionalDataException.
ObjectInputStream,
, ,
, , .
,
,
:
private void writeObject(java.io.ObjectOutputStream out) throws IOException;
private void readObject(java.io.ObjectInputStream in) throws IOException,
ClassNotFoundException;

writeObject , readObject ,
, .
,
Java

Rendered by www.RenderX.com

. 21 34

out.defaultWriteObject();


in.defaultReadObject();


, .
, ,
.
, ,
. ,
, , .
java.io.Externalizable
.

.
, .
, ,
writeExternal() readExternal() Externalizable.
, .
,
Externalizable. Externalizable,
writeExternal . Externalizable, Serializable,
ObjectOutputStream. Externalizable , public ,
readExternal . , Serializable
ObjectInputStream.
writeExternal :
void writeExternal(ObjectOutput out) throws IOException;

, ObjectInput
, .
,
void readExternal(ObjectInput in) throws IOException, ClassNotFoundException;

.

Externalizable readObject, writeObject.
, -
. ,
, .
private, , , ,
Java

Rendered by www.RenderX.com

. 22 34

Serialization

, .
,
-
. -
Externalizable, readObject writeObject -
.
- transient. ,
Account, ,
login name
class Account implements java.io.Serializable {
private String name;
private String login;
private transient String password;
/* Some accessors and mutators for fields
...
*/
}

, ,
null.

2.1.
, ,
. , ,
- , ..
,
.
InvalidClassException. , User,

class User implements java.io.Serializable{
String name;
}

, name :
class User implements java.io.Serializable{
protected String firstName;
protected String lastName;
}

,
InvalidClassException . ,
:
class User implements java.io.Serializable{

Java

Rendered by www.RenderX.com

. 23 34

private String name;


String lastName;
}

, (ID)
. long ( 64 ), . , ,
. ,
, .
, - ,
, ,
, - ,
. , ,
: ,
, ,
.
, :

static transient

, ,

static transient

Serializable Externalizable .

, ,
.
,
. ,
Externalizable, readExternalizable writeExternalizable.

3. Reader Writer. .
- InputStream OutputStream
. , 8-
16-
Unicode - char()
Java. /

Java

Rendered by www.RenderX.com

. 24 34

Reader Writer. .

Reader () Writer ().


.3 .

InputStream OutputStream.
1 .
InputStream

Reader

OutputStream

Writer

ByteArrayInputStream

CharArrayReader

ByteArrayOutputStream

CharArrayWriter

InputStreamReader

OutputStreamWriter

FileInputStream

FileReader

FileOutputStream

FileWriter

FilterInputStream

FilterReader

FilterOutputStream

FilterWriter

BufferedInputStream

BufferedReader

BufferedOutputStream

BufferedWriter

PrintStream

PrintWriter

DataInputStream

DataOutputStream

ObjectInputStream

ObjectOutputStream

PipedInputStream

PipedReader

PipedOutputStream

PipedWriter

Java

Rendered by www.RenderX.com

. 25 34

StringBufferInputStream

StringReader

StringWriter

LineNumberInputStream

LineNumberReader

PushBackInputStream

PushBackReader

SequenceInputStream

, :
, SequenceInputStream
, , ,
Java (DateInput/Output, ObjectInput/Output).
,
, (
). , , : InputStreamReader OutputStreamWriter .
, ,
:

- : FilterReader FilterWriter
, : InputStream OutputStream .

: close Reader flush close Writer ,


InputStream OutputStream

BufferedReader FilterReader, Reader

LineNumberReader FilterReader,
BufferedReader, Reader

FileReader FileWriter - InputStreamReader OutputStreamWriter

available() InputStream, Reader,


ready() - ,
- (
)

,
. , ,
:
String fileName = "d:\\file.txt";
FileWriter fw = null;
BufferedWriter bw = null;
FileReader fr = null;
BufferedReader br = null;
//,
String data = "Some data to be written and readed\n";
Java

Rendered by www.RenderX.com

. 26 34

StreamTokenizer

try{
fw = new FileWriter(fileName);
bw = new BufferedWriter(fw);
System.out.println("Write some data to file: " + fileName);
//
for(int i=(int)(Math.random()*10);--i>=0;)bw.write(data);
bw.close();
fr = new FileReader(fileName);
br = new BufferedReader(fr);
String s = null;
int count = 0;
System.out.println("Read data from file: " + fileName);
// ,
while((s=br.readLine())!=null)
System.out.println("row " + ++count + " read:" + s);
br.close();
}catch(Exception e){
e.printStackTrace();
}

- InputStreamReader OutputStreamWriter
, .
, . ,
, UnsupportedEncodingException.
: "Cp1521", "UTF-8", "8859_1", "8859_2" ...

4. StreamTokenizer
InputStream Reader.
- ,
.
.
StreamTokenizer , ,
.
, ,
nextToken, StreamTokenizer.TT_EOF.
nextToken ttype
. ,
nval. ,
sval.
, -
commentChar, ordinaryChar, parseNumbers, quoteChar, resetSyntax, slashSlashComments,
slashStarComments, whitespaceChars, wordChars.
, , ( )
.

Java

Rendered by www.RenderX.com

File

. 27 34

5. .
5.1. File
, File -
, .
File .
, ,
. ,
exists, true, .
File .
. File
( isDirectory),
list ( String) ( File
- null).
File.
import java.io.*;
public class FileDemo {
public static void findFiles(File file, FileFilter filter, PrintStream output)
throws IOException{
if(file.isDirectory()){
File[] list = file.listFiles();
for(int i=list.length; --i>=0;){
findFiles(list[i], filter, output);
}
}else{
if(filter.accept(file))
output.println("\t" + file.getCanonicalPath());
}
}
public static void main(String[] args) {
class NameFilter implements FileFilter{
private String mask;
NameFilter(String mask){
this.mask = mask;
}
public boolean accept(File file){
return (file.getName().indexOf(mask)!=-1)?true:false;
}
}
File pathFile = new File(".");
String filterString = ".java";
try{
FileFilter filter = new NameFilter(filterString);
findFiles(pathFile, filter, System.out);
}catch(Exception e){
e.printStackTrace();
Java

Rendered by www.RenderX.com

. 28 34

}
System.out.println("work finished");
}
}

(
) , ".java",
-. , ".java"
FileFilter NameFilter.
FileFilter accept, ,
.
- FilenameFilter, accept
: ,
.
, accept.
FileFilter
FilenameFilter. list
File - .
File :

canRead canWrite - boolean ,


exists - boolean ,

getName - - ( )

getParent, getParentName - ,
File

getPath - ( ,
File)

isAbsolutely - boolean , ,
. , - ,
Java-. , Windows -
, '\'. Unix - '/'

isDirectory, isFile - boolean ,


isHidden - boolean ,

lastModified

length

- setReadOnly, setLastModified . -
createNewFile, mkDir, mkDirs. createNewFile
( ), mkDir
, mkDir ,
.

Java

Rendered by www.RenderX.com

RandomAccessFile

. 29 34

- delete deleteOnExit.
delete, , deleteOnExit
Java-( ),
.
File
.

5.2. RandomAccessFile
: DataInput DataOutput , ,
, Java.
, , .
, seek(
getFilePointer) .

: , . ,
String - , File
. (mode) - String,
: "r"() "rw"( ). ,
, mode "r" ( ),
FileNotFoundException. , mode "rw"
, (
FileNotFoundException ).
RandomAccessFile,
DataInput DataOutput .
, , close.

6.
, .

/. ,
java.io ,
( ) .
,
.
InputStream OutputStream,
Reader Writer.
. ,
, , , pipe
(), . ,
BufferedInputStream BufferedOutputStream,
, .
() ( ) Java
DataInputStream, DataOutputStream ( ObjectInputStream, ObjectOutputStream
Java

Rendered by www.RenderX.com

. 30 34

PrintWriter, BufferedReader).
.
() StreamTokenizer.
File
RandomAccessFile.

7.
15-1.
java ?
?
a.)
:

File

byte[] char[]

String

getInputStream() java.net.Socket

Pipe
PipedOutputStream(PipedWriter)

,
(String). , ,
: getOutputStream() Socket.
15-2. File, ,
( )?
? ,
(
)?
a.) equals() File
. ,
File.
( getCanonicalPath() getCanonicalFile())
. , File
, isDirectory(). (
) delete() File.
,
. File
, exist() false
, .
, ,
File, delete() File.

Java

Rendered by www.RenderX.com

. 31 34

15-3. InputStream OutputStream?


/?
a.) ( ) InputStream, OutputStream.
InputStream OutputStream Object.
15-4. write(0x01234567) OutputStream,
?
a.) , write() OutputStream
int,
0x67, 16*6+7=103.
15-5. false?
public static boolean test(InputStream is) throws IOException {
int value = is.read();
return value == (value &amp; 0xff);
}

a.) value == (value & 0xff) true ,


value
( 0xff int 255, 1).
,
,
IOException.
15-6.
Java?
a.) Java,
DataOutput. java.io DataOutputStream. , ObjectOutputStream ObjectOutput,
DataOutput.
15-7. ( ) ( ),
( , )?
?
a.)

:
new PrintWriter(new BufferedWriter(new
FileWriter("file.txt")))

, , , :
new BufferedReader(new FileReader("file.txt"))

BufferedWriter
(
,
Java

Rendered by www.RenderX.com

. 32 34

). ,
FileWriter, - FileReader,
PrintWriter
BufferedReader ( LineNumberReader ).
15-8. PipedWriter
PipedReader? ,
PipedReader?
a.) PipedWriter
PipedReader. PipedReader,
new IOException("Already connected") .
,
PipedReader connect() ,
new IOException("Already connected")
, PipedWriter
PipedReader
PipedWriter.
15-9. Java
write() Writer? print() PrintWriter?
a.) Writer write()
:

write(char cbuf[])

write(char cbuf[], int off, int len)

write(int c)

write(String str)

write(String str, int off, int len)

, int (
byte, char short
int).
print() PrintWriter
Java ( Object String).
15-10. OutputStreamWriter ?
a.) , Java-.
15-11. , print() PrintWriter,
new File(d:\\word.txt) ?
a.) print(Object obj) , ,
String.valueOf(obj).
valueOf(Object obj) String , ,
null,
obj.toString() . , File, ,
getPath(), ,
d:\\word.txt.

Java

Rendered by www.RenderX.com

. 33 34

15-12. RandomAccessFile
(/)?
a.) RandomAccessFile String,
.
r() rw(
). new IllegalArgumentException("mode must be r or rw") ( ,
null, NullPointerException).
15-13. seek() RandomAccessFile,
read()?
a.) , RandomAccessFile,
length(). ,
seek() 0. ,
, seek() randomAccessFile.length()-1 .
15-14. Serializable?
a.) java.io.Serializable .
, ,
.
15-15. , , ObjectOutputStream,
long, int, byte , ,
DataInputStream?
a.) DataInputStream long, int byte,
8 , long, 4 ,
int, , , . ,
, : byte
, int 4
long 8 . ,
, ,
,
, byte, int long ( - )
, .

Java

Rendered by www.RenderX.com

Java ()

Java

Rendered by www.RenderX.com

Java
16.
20 2003
:
( Sun ) <vyazovick@itc.mipt.ru>
( Sun ) < gene@itc.mipt.ru>
Copyright 2003 Sun , , .

,
. ,
OSI, TCP/IP ,
. ,
java.net .
,
TCP UDP.

Rendered by www.RenderX.com

ii

16. ......................................................................1
1. OSI........................................................................................................ 2
2. Physical layer (layer 1)...................................................................................................... 4
3. Data layer (layer 2)............................................................................................................8
3.1. LLC sublayer............................................................................................................ 9
3.2. MAC sublayer...........................................................................................................9
4. Network layer (layer 3).................................................................................................... 10
4.1. Class A................................................................................................................... 11
4.2. Class B................................................................................................................... 12
4.3. Class CClass DClass E..........................................................................................12
5. Transport layer (layer 4).................................................................................................. 13
5.1. TCP........................................................................................................................ 14
5.2. UDP........................................................................................................................14
6. Session layer (layer 5).....................................................................................................15
7. Presentation layer (layer 6)............................................................................................. 15
8. Application layer (layer 7)................................................................................................15
9. ........................................................................................16
9.1. IPCONFIG (IFCONFIG)......................................................................................... 17
9.2. ARP........................................................................................................................ 18
9.3. Ping........................................................................................................................ 18
9.4. Traceroute.............................................................................................................. 19
9.5. Route......................................................................................................................21
9.6. Netstat.................................................................................................................... 22
9.7. ................................................................... 23
10. java.net............................................................................................................... 24
11. .................................................................................................................. 32
12. .................................................................................................32

Java

Rendered by www.RenderX.com

. 1 37

16.

.
1. OSI........................................................................................................2
2. Physical layer (layer 1)..................................................................................................... 4
3. Data layer (layer 2)........................................................................................................... 8
3.1. LLC sublayer.................................................................................................................. 9
3.2. MAC sublayer.................................................................................................................9

4. Network layer (layer 3)................................................................................................... 10


4.1. Class A......................................................................................................................... 11
4.2. Class B......................................................................................................................... 12
4.3. Class CClass DClass E................................................................................................12

5. Transport layer (layer 4)................................................................................................. 13


5.1. TCP.............................................................................................................................. 14
5.2. UDP..............................................................................................................................14

6. Session layer (layer 5)....................................................................................................15


7. Presentation layer (layer 6)............................................................................................ 15
8. Application layer (layer 7)............................................................................................... 15
9. ....................................................................................... 16
9.1. IPCONFIG (IFCONFIG)............................................................................................... 17
9.2. ARP.............................................................................................................................. 18
9.3. Ping.............................................................................................................................. 18
9.4. Traceroute.................................................................................................................... 19
9.5. Route............................................................................................................................21
9.6. Netstat.......................................................................................................................... 22
9.7. ......................................................................... 23

10. java.net.............................................................................................................. 24
11. ................................................................................................................. 32
Java

Rendered by www.RenderX.com

. 2 37

OSI

12. ................................................................................................ 32

1. OSI

. 80- .
,
.
(,
).
(International Organization for Standardization, ISO),
,
.
1984 . OSI -
(Open Systems Interconnected). .
:

Layer 7

(data)

Layer 6

(data)

Layer 5

(data)

Layer 4

(segment)

Layer 3

(packet)

Layer 2

(frame)

Layer 1

(bit)

,
. OSI-
, .
,
.
. ,
(HTTP, FTP) .
.
7 (),
. ,
(,
, , ,
). , ,
(layer 6).
, 7 ,
6 ( 6
7).
, ,
,
(6-) .
, .
..,
( .1).
Java

Rendered by www.RenderX.com

. 3 37

. , 3-
(.2).
, 7 .
(encapsulation).

. -
, 0 1. ,
, 010110101.
,
(0 - , 1 - ).
.
/ /.


(.3). - .
Java

Rendered by www.RenderX.com

. 4 37

Physical layer (layer 1)

.
( 1 ),
,
,
. (2-) ,
. ,
,
. -.
- , -.
7
OSI. , ""
.
() .
,
-,
. -
, , .
(message) ISO
(Protocol Data Unit, PDU).

.

2. Physical layer (layer 1)


OSI -
(physical layer) . .
,
(, ..) .
.
( ,
, , ).
.
:


. -
.
,
( ,
).
. ,
Java

Rendered by www.RenderX.com

. 5 37

, .

, .. ,
.
, "". ..
( ""
), .
.
,
, , .
-
, (
75 ,
- 50 ).
( 10
/), . ,
, ,
.

,
.
("twisted pair") -
. ,
,
, .
. : Cat 3 - 1991 ,
16 ,
. , Cat 5
.
100.
10,100,1000 /. Cat5 Cat
3.
- .
Cat 5 ,
, .
,
, , ,
.
() - , - ,
, .
, ,
. .

:


Java

Rendered by www.RenderX.com

. 6 37

Physical layer (layer 1)

"" .
,
. ,
.
, .
.
: ,
.
, ..
.

. , ,
.. (
).
- , ,
. ( , .
Network adapter) ISA PCI,
(,
, ..).
, ,
-
( ).
""(bus):

,
.

Java

Rendered by www.RenderX.com

. 7 37

""(ring):

,
.
""(star):

Java

Rendered by www.RenderX.com

. 8 37

Data layer (layer 2)

" "(extended star):

"" .
,
"".

3. Data layer (layer 2)


- .
,
.
.
.
Data layer :

LLC sublayer

MAC sublayer

LLC - 3 .
MAC - physical layer.
.

Java

Rendered by www.RenderX.com

LLC sublayer.

. 9 37

3.1. LLC sublayer.


.
(3-)
. LLC ,

. , Ethernet, Token Ring, Frame Relay.

3.2. MAC sublayer.


. , data
layer . ..
data layer ,
MAC-.
-
. MAC- 48 6 ( 8 ),
. 3 OUI.
OUI - Organizational Unique Identifier, IEEE (Institute of Electrical and Electronic Engineers,
- ,
) . 3
.
, : 00:00:B4:90:4C:8C, 00-00-B4-904C-8C, 0000.B490.4C8C - .
, , 0000.1c12.3456.
, 12.3456 - .

00001

,
.
data layer Ethernet.
, MAC- MAC- .
, , , .
MAC- MAC- ,
.
, .
, ,
MAC- FF-FF-FF-FF-FF-FF.
(broadcast),
.
Ethernet - CSMA/CD
(carrier sense multiply access/collision detect).
. ,
.
,
. CSMA/CD
- (collision - ,
).
Java

Rendered by www.RenderX.com

. 10 37

Network layer (layer 3)

, .
("bus")
, (, )
. .. , ,
, .
.
Token Ring .
. ,
Ethernet, . .. ,
,
..
""
,
" ". (hub).
" ".
. Ethernet
CSMA/CD. .
. ,
MAC MAC-, , . ,
"" ( ,
).
. 10 /,
2 /.
, ,
(switch). MAC-address
- Port. .
, ,
, .
, , ,
. , ,
,
"".

4. Network layer (layer 3)


OSI.
2? "" .
, MAC-,
broadcast-. ,
, .
.
. , +7-095-101-12-34 ,
/(095), (101-12-34).
. 101 - ,
, 12-34 .
Java

Rendered by www.RenderX.com

Class A

. 11 37


.
.
, - IP, IPX.
IP. IPX
, , .
, 3- , (router).
, (LAN) (WAN).
(
LAN) 3 .
3 , . , . ..
-
. ( hop')
"routing the packet". "next hop",
, - ,
, ..

.
.
- IP. .

. IP-
- ,
( ).
IP-. IP- 32- ,
4 . - network
host. network IP-
, network-ID,
, "" .
IP- -
. (host) . ..
4- , ,
. 3-
host-. IP-.
(class A, class B, class C).
Class A

Class B

Class C

4.1. Class A
,
.
- 0-126(127
Java

Rendered by www.RenderX.com

. 12 37

Network layer (layer 3)

).
.
2^24 ( ) - 16 777 214
.
10.0.0.0-10.255.255.255 .

.

4.2. Class B
B ,
- . B 128 191
( ). B 65534
- 216 ( ).

: 172.16.0.0-172.31.0.0.

4.3. Class CClass DClass E


C .
192 223.
. , C 28( )
254
:
192.168.0.0-192.168.255.255.
multicast-. 224.0.0.0-239.255.255.255.
.
240.0.0.0-247.255.255.255.
. IP-,
, .
- 112.0.0.0, - 112.2.3.4.
.
- - (broadcast). ,
. -
( , ). ,
171.10.0.0 16 , 171.10.255.255. 171.10.0.0
, 171.10.255.255.
.

. .
A,B C .. subnet field
. subnet field , (..
3- , 2
B, 1 C ). ,
Java

Rendered by www.RenderX.com

Class E

. 13 37

. ,
- 2 . ,
, - -.
, - ,
.
- - .. - 16
. -
. .. -
- .
.
, IP- ,
. . IP-
. , network-part subnet-part
1, , host-part 0.
.
: 255.0.0.0,
B: 255.255.0.0, C: 255.255.255.0.
- , 1,
- 0. 255.255.255.192 , -
64.
IP- MAC-.
IP- MAC- ARP-(Address Resolution Protocol,
). ARP-
. IP- .
, MAC
ARP-,
MAC- . RARP (Reverse ARP - ARP)
- MAC- IP-. ,
, , BOOTP, DHCP.
broadcast- - ARP-. ARP-
"IP- , MAC- - ???", RARP- "MAC-
, IP - ???".
IP-, RARP-
IP- ( - DHCP -
- ).

5. Transport layer (layer 4)


TCP/IP 4 OSI. TCP/IP
- TCP UDP. TCP
.
TCP UDP
TCP

UDP

Java

Rendered by www.RenderX.com

. 14 37

Transport layer (layer 4)


TCP

UDP

5.1. TCP
TCP/IP TCP IP. IP - 3
- ,
. TCP - 4 - .
. TCP . -
(sequence number - x). , ,
(sequence number + 1 - x+1)
sequence number(y). sequence number,
1. ( sequence number ,
+1(x+1)), sequence number y+1
. sequence
number, .
(window) TCP.
. , ,
.
"". ,
, , .
- "" 5,

5 , .
TCP , " "
.
TCP-.

5.2. UDP
TCP - UDP . UDP
, user datagram .
, - UDP
. .
,
. , UDP . ,
- TCP,
.
UDP - /,
. UDP
- ,
- ,
Java

Rendered by www.RenderX.com

UDP

. 15 37

- UDP-
.
TCP UDP (port)
.
. ,
. , FTP 21.
: 255 - ,
255-1023 - - ,
1023 - .

6. Session layer (layer 5)


, , session layer. 5 ,
. ,
.
-"",
.

7. Presentation layer (layer 6)


,
. - .
, , .
- ,
. 6- : data formatting(presentation), data encryption, data compression. ,

session layer. . ,
Extended Binary Coded Decimal Interchange Code (EBCDIC)
. American
Standard Code for Information Interchange (ASCII). Presentation layer
.
-
.
.
.
..
.

8. Application layer (layer 7)


, .
OSI.
presentation layer.
- .
Java

Rendered by www.RenderX.com

. 16 37

.
. -
: client-request, server-response, client-request, server-response ..
, - URL,
-. application layer
:

telnet -

dns - domain name system

e-mail -

DNS.
IP-. , , web-.
. IP-, 194.87.0.50
- IP- . IP-
.
IP-. .. 194.87.0.50 www.ru.
- . .
. : .ru, .us, .uk -
, .edu - .edu - educational sites, .com - commercial sites, .gov - government sites, .org
- non-profit sites, .net - network service.
.
.. -.
,
- ( test.ru test.ru,
node1.host1.test.ru -
host1.test.ru,
)

9.
, ,
.
. 2 , Microsoft Windows NT Sun Solaris.
, OSI.
OSI ,
,
.
, - 2 .
- Windows Solaris (
). Windows
OSI.
.

-, Solaris.
. ,
. .. OSI
Java

Rendered by www.RenderX.com

IPCONFIG (IFCONFIG)

. 17 37

,
. Solaris ,
OC .

( ,
),
. - . ,
-. .. Ethernet ATM
. ,
-
. Ethernet FDDI
. - .
.
.

9.1. IPCONFIG (IFCONFIG)


, ,
. 3- () IP
, .. Windows
ipconfig. IP-,
(netmask), (default gateway).
ipconfig all, ,
, , MAC- ..

Solaris IP-
ifconfig. , IP-, , MAC.

Java

Rendered by www.RenderX.com

. 18 37

9.2. ARP
, arp-.
MAC- IP-.
arp. , arp a
MAC-.

MAC- .
, IP-
. ARP-
. ,
MAC-IP .
,
() .
IP-,
broadcast-frame .. ARP-.
ARP- IP- .
ARP-,
IP- MAC-. , ARP-
ARP-. MAC-
,
(
MAC-,
ARP-, ,
).

9.3. Ping
,
, OSI
. ping.
(layer 3), ICMP (Internet Control
Message Protocol) .
: ping 194.87.0.50 ( 194.87.0.50 IP-
Java

Rendered by www.RenderX.com

Traceroute

. 19 37

).
.
ICMP .
ICMP - (echo-request)
- (echo-reply).
- .
- -
, ,
,
.
, echo-request echo-reply ,
.
-, , ,
OSI.

, 32 ,
, TTL (time to live ).
ping. ,
echo request , echo reply ,
.

9.4. Traceroute
traceroute ICMP
. traceroute TTL
1 30. ,
, TTL . TTL
. ,
Java

Rendered by www.RenderX.com

. 20 37

,
, .
,
. , TTL
.
IP TTL 0, 1,
. (
, .
, TTL 0).
, ,
, ICMP " " (time exceeded). traceroute
, IP , ICMP ,
IP .
, Traceroute. IP
TTL, . ,
, ( TTL 1) ICMP
(time exceeded). ,
. Traceroute TTL, 2,
IP . ,
.
, ICMP ,
. UDP , (
30000) port unreachable. ,
traceroute, ,
, TTL (
traceroute TTL 30).
traceroute
traceroute to netserv1.chg.ru (193.233.46.3), 30 hops max, 38 byte packets
1 n3-core.mipt.ru (194.85.80.1) 1.508 ms 0.617 ms 0.798 ms
2 mipt-gw-eth0.mipt.ru (193.125.142.177) 2.362 ms 2.666 ms 1.449 ms
3 msu-mipt-atm0.mipt.ru (212.16.1.1) 5.536 ms 5.993 ms 10.431 ms
4 M9-LYNX.ATM6-0.11.M9-R2.msu.net (193.232.127.229) 12.994 ms 7.830 ms
6.816 ms
5 Moscow-BNS045-ATM4-0-3.free.net (147.45.20.37) 12.228 ms 7.041 ms 8.731
ms
6 ChgNet-gw.free.net (147.45.20.222) 77.103 ms 75.234 ms 92.334 ms
7 netserv1.chg.ru (193.233.46.3) 96.627 ms 94.714 ms 134.676 ms

IP- , TTL
30 38 . TTL,
IP .
TTL 3 .
. 3- 3-
, ,
.
(, traceroute) .
Java

Rendered by www.RenderX.com

Route

. 21 37

, ,
TTL N TTL N+1.
, .
Solaris traceroute. IP-
, . ,
, traceroute (, , ).
Windows tracert. Solaris (tracert
netserv1.chg.ru). tracert traceroute .
traceroute (,
, TTL ).
- . ,
net unreachable:
Moscow-BNS045-ATM4-0-3.free.net (147.45.20.37)
995.257 ms

947.327 ms !N

996.548 ms !N

!N 147.45.20.37 , .
: msu-mipt-atm0.mipt.ru (212.16.1.1) 5.536 ms !H 5.993 ms !H 10.431
ms !H. !P - protocol unreachable.

9.5. Route
route.
:
Windows:
route print

, , ,
, . ,
192.168.1.1. 192.168.1.0
netmask 255.255.255.0 .
.
route ADD 157.0.0.0 MASK 255.0.0.0

157.55.80.1
Java

Rendered by www.RenderX.com

. 22 37

157.0.0.0 , 255.0.0.0 , 157.55.80.1 ,


.
: route DELETE 157.0.0.0
Solaris
netstat r.

route:
route add net 157.6 157.6.1.20, 157.6 , 157.6.1.20
, .
: route del net 157.6

9.6. Netstat
netstat ,
. , -
web-, , netstat, :
TCP

jawa:3687

www.ru:http

ESTABLISHED

TCP ( tcp,udp),
, www.ru:http -
, , ESTABLISHED , tcp .
Windows netstat an (
n DNS- , IP-). ,
,
, .. . TCP 139 Netbios- (
).

Java

Rendered by www.RenderX.com

. 23 37

Solaris
netstat. .

9.7.
1. IP-, .
2. arp-.

Java

Rendered by www.RenderX.com

. 24 37

java.net

3. ping. IP-
; IP-
194.87.0.50. arp- (
).
4. traceroute. DNS-
IP- .
5. netstat. - netstat .

10. java.net
Java java.net,
URL. uniform resource locator (URL),
:
protocol://host:port/resource

protocol - , ; host - IP- DNS , ; port - (


, ); resource , , :
ftp://myserver.ru/pub/docs/Java/JavaCourse.txt

openStream(), InputStream,
. ,
LineNumberReader http://www.ru .
import java.io.*;
import java.net.*;
public class Net {
public static void main(String args[]) {
try {
URL url = new URL("http://www.ru");
LineNumberReader r = new LineNumberReader(new
InputStreamReader(url.openStream()));
String s = r.readLine();
while (s!=null) {
System.out.println(s);
s = r.readLine();
}
System.out.println(r.getLineNumber());
r.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

Java

Rendered by www.RenderX.com

. 25 37

}
}

, , ,
. MalformedURLException
, c URL .
URLConnection,
URL.openConnection(). - getInputStream() ( URL.openStream()) getOutputStream(),
,
( web- ).
URLConnection .
, , java.net
HttpURLConnection. , URL URLConnection

.
java.net - TCP
UDP. InetAddress,
-, IP. ,
:
InetAddress getLocalHost()
InetAddress getByName(String name)
InetAddress[] getAllByName(String name)

IP- , Java-.
, .
DNS-, IP, , ,
"67.11.12.101". IP- .
TCP- Socket ServerSocket.
ServerSocket - .
- , .
accept(),
, - .
, Socket
:
try {
ServerSocket ss = new ServerSocket(3456);
Socket client=ss.accept(); // ,

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

Socket.
- (
InetAddress) . , ,
getInputStream() getOutputStream().

Java

Rendered by www.RenderX.com

. 26 37

java.net

try {
Socket s = new Socket("localhost", 3456);
InputStream is = s.getInputStream();
is.read();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

UnknownHostException,
,
, .
InetAddress,
.
Socket -
getInputStream() getOutputStream(). :
import java.io.*;
import java.net.*;
public class Server {
public static void main(String args[]) {
try {
ServerSocket ss = new ServerSocket(3456);
System.out.println("Waiting...");
Socket client=ss.accept();
System.out.println("Connected");
client.getOutputStream().write(10);
client.close();
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

10 . ,
close() .
:
import java.io.*;
import java.net.*;
public class Client {
public static void main(String args[]) {
try {
Socket s = new Socket("localhost", 3456);
InputStream is = s.getInputStream();
System.out.println("Read: "+is.read());
Java

Rendered by www.RenderX.com

. 27 37

s.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

, , - 10,
.
. -, ServerSocket ,
.
, , ,
?
( ), .
,
. , .
Socket
, , (
).
-, setSoTimeout(int timeout) ServerSocket,
,
. "" ,
. ,
.
,
accept(), .
, .

, ,
accept(). :
import java.io.*;
import java.net.*;
public class NetServer {
public static final int PORT = 2500;
private static final int TIME_SEND_SLEEP = 100;
private static final int COUNT_TO_SEND = 10;
private ServerSocket servSocket;
public static void main(String[] args) {
NetServer server = new NetServer();
server.go();
}
public NetServer() {
Java

Rendered by www.RenderX.com

. 28 37

java.net

try{
servSocket = new ServerSocket(PORT);
}catch(IOException e){
System.err.println("Unable to open Server Socket : " + e.toString());
}
}
public void go() {
// -
class Listener implements Runnable{
Socket socket;
public Listener(Socket aSocket){
socket = aSocket;
}
public void run(){
try{
System.out.println("Listener started");
int count = 0;
OutputStream out = socket.getOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(out);
PrintWriter pWriter = new PrintWriter(writer);
while(count<COUNT_TO_SEND){
count++;
pWriter.print(((count>1)?",":"")+ "Say" + count);
sleeps(TIME_SEND_SLEEP);
}
pWriter.close();
}catch(IOException e){
System.err.println("Exception : " + e.toString());
}
}
}
// , accept()
System.out.println("Server started");
while(true){
try{
Socket socket = servSocket.accept();
Listener listener = new Listener(socket);
Thread thread = new Thread(listener);
thread.start();
}catch(IOException e){
System.err.println("IOException : " + e.toString());
}
}
}
public void sleeps(long time) {
Java

Rendered by www.RenderX.com

. 29 37

try{
Thread.sleep(time);
}catch(InterruptedException e){
}
}
}

. ,
, .
import java.io.*;
import java.net.*;
public class NetClient implements Runnable{
public static final int PORT = 2500;
public static final String HOST = "localhost";
public static final int CLIENTS_COUNT = 5;
public static final int READ_BUFFER_SIZE = 10;
private String name = null;
public static void main(String[] args) {
String name = "name";
for(int i=1; i<=CLIENTS_COUNT; i++){
NetClient client = new NetClient(name+i);
Thread thread = new Thread(client);
thread.start();
}
}
public NetClient(String name) {
this.name = name;
}
public void run() {
char[] readed = new char[READ_BUFFER_SIZE];
StringBuffer strBuff = new StringBuffer();
try{
Socket socket = new Socket(HOST, PORT);
InputStream in = socket.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
while(true){
int count = reader.read(readed, 0, READ_BUFFER_SIZE);
if(count==-1)break;
strBuff.append(readed, 0, count);
Thread.yield();
}
} catch (UnknownHostException e) {
e.printStackTrace();
Java

Rendered by www.RenderX.com

. 30 37

} catch (IOException e) {
e.printStackTrace();
}
System.out.println("client " + name + "
}

java.net

read : " + strBuff.toString());

UDP. ,
DatagramSocket. :
DatagramSocket()
DatagramSocket(int port)
DatagramSocket(int port, InetAddress laddr)

,
. , ,
, ,
. , ,
.
.
DatagramPacket.
:
DatagramPacket(byte[] buf, int length, InetAddress address, int port)

( length),
. send()
DatagramSocket.
try {
DatagramSocket s = new DatagramSocket();
byte data[]={1, 2, 3};
InetAddress addr = InetAddress.getByName("localhost");
DatagramPacket p = new DatagramPacket(data, 3, addr, 3456);
s.send(p);
System.out.println("Datagram sent");
s.close();
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

DatagramPacket,
,
( ).
, .
receive() DatagramSocket ( ServerSocket.accept()

Java

Rendered by www.RenderX.com

. 31 37

, ).
:
try {
DatagramSocket s = new DatagramSocket(3456);
byte data[]=new byte[3];
DatagramPacket p = new DatagramPacket(data, 3);
System.out.println("Waiting...");
s.receive(p);
System.out.println("Datagram received: "+data[0]+", "+data[1]+", "+data[2]);
s.close();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

, , ,
,
.
,
, received.
import java.io.*;
import java.net.*;
public class DatagramDemoServer {
public static final int PORT = 2000;
private static final int LENGTH_RECEIVE = 1;
private static final byte[] answer = ("received").getBytes();
private DatagramSocket servSocket = null;
private boolean keepRunning = true;
public static void main(String[] args) {
DatagramDemoServer server = new DatagramDemoServer();
server.service();
}
public DatagramDemoServer() {
try{
servSocket = new DatagramSocket(PORT);
}catch(SocketException e){
System.err.println("Unable to open socket : " + e.toString());
}
}
protected void service() {
DatagramPacket datagram;
InetAddress clientAddr;
Java

Rendered by www.RenderX.com

. 32 37

int clientPort;
byte[] data;
while(keepRunning){
try{
data = new byte[LENGTH_RECEIVE];
datagram = new DatagramPacket(data, data.length);
servSocket.receive(datagram);
clientAddr = datagram.getAddress();
clientPort = datagram.getPort();
data = getSendData(datagram.getData());
datagram = new DatagramPacket(data, data.length, clientAddr, clientPort);
servSocket.send(datagram);
}catch(IOException e){
System.err.println("I/O Exception : " + e.toString());
}
}
}
protected byte[] getSendData(byte b[]) {
byte[] result = new byte[b.length+answer.length];
System.arraycopy(b, 0, result, 0, b.length);
System.arraycopy(answer, 0, result, b.length, answer.length);
return result;
}
}

11.

. OSI
. ,
.

12.
16-1. OSI.
a.) OSI :
7 -
6 -
5-
4-
3 -
2
1
Java

Rendered by www.RenderX.com

. 33 37

16-2. ?
.
a.)
(, , ).

( 0 1, , 010110101).
.
:

16-3. MAC- LLC-.


a.) MAC- .
. MACsublayer . LLCsublayer . LLC
, .
16-4. IP-?

64.12.8.130

224.180.224.5

172.16.0.1

194.86.87.256

195.149.20.130
a.) :

A;

D;

B, private;

C.

16-5. ARP- RARP-?


a.) IP-
MAC- . IP- MAC ARP- (Address Resolution Protocol). ARP .
IP-
Java

Rendered by www.RenderX.com

. 34 37

. MAC- ,
arp-, ,

.
RARP MAC-
IP-. , ,
, BOOTP, DHCP.
broadcast arp-. ARP-
IP- , MAC- - ???, RARP MAC- , IP - ???. , DHCP
IP-
. broadcast
MAC-. MAC IP, rarp-,
IP-
( ).
16-6. , ?
a.) .
, IP- (network
part), , host part (,
). , IP . , network-part
1, , host-part, 0.
.
:
255.0.0.0, B: 255.255.0.0, C: 255.255.255.0.
, ( ) ,
, 1, 0.
255.255.255.192 , -
64.
16-7. TCP UDP?
a.) TCP-
. UDP
. TCP-
,
, HTML-, FTP.
UDP ,
:
.
16-8. , ,
.
a.) ,
.
OSI.
Java

Rendered by www.RenderX.com

. 35 37

,
. ,
, Extended Binary Coded Decimal Interchange Code (EBCDIC) American Standard Code for Information Interchange (ASCII). ,
, , presentation layer
.
: ,
,
.
,
, .
,
,

.
16-9. Ping traceroute .
a.) ping traceroute
. ICMP. Ping
.
ping echo- IP- . echo-
, echo-.
echo- ,
. .. echo- ,
,
, .
Traceroute ICMP
.
, .
16-10. ?
?
a.) , ,
,
.
.
, ,
,
.
, ,
IP- ,
.
,
default gateway .

route.
Java

Rendered by www.RenderX.com

. 36 37

16-11. TCP
Java-? ?
a.) -, ServerSocket , accept().

.
Socket IP .
accept() Socket
.
16-12. UDP ?
a.) -,
DatagramSocket. DatagramPacket ,
, IP- .
DatgramSocket ,
. DatagramPacket , DatagramSocket.receive(). DatagramSocket.send()
16-13. URL ?
a.)
b.)
c.) , (upload) .

Java

Rendered by www.RenderX.com


ABDEFGHIJKLMNOPQRSTUVWXYZ
100% Pure JavaTM
"100% Pure JavaTM" Java-,
Java-, -
(native) , Java core API.
, ,
100% Pure Java .

A
Abstract Window Toolkit - AWT
,
.
, .
Project Swing (. Swing-).
abstract
Java,
,
.
() , .
(abstract class)
, ,
. ,
, .
(abstract method)
, .
(access control)
,
, , ,
.
(ACID - Atomicity, Consistency, Isolation and Durability)
, : , ,
.
(activation)
(enterprise beans)
.
(actual parameter list)
, (. ).

- (alpha value)
, ( ) .
(API - Application Programming Interface)
,
.
(applet)
, Web-
.
(applet container)
, .
(appliances)
, , JavaTM
, Java Management API (JMAPI).
(application assembler)
, .
(application client)
, Java.
(application client container)
,
API J2EE.
(application client module)
,
.
(Application Component Provider)
, Java, ,
JSP- .
(Application Programming Model - APM)
, ,
J2EE
.
(argument)
, . ,
.
(array) ,
( ).

(American standard code for


information interchange - ASCII)
, 7 . . .
(atomic)
, .
(authentication)
, ,
. J2EE
: (basic), (form-based) (mutual).
(authorization)
. .
(authorization constraint)
, Web-.

B
() (basic authentication)
Web- ,
, Web-.
bean- (bean)
. Bean-
.
, bean- (bean-managed persistence)
, bean-
bean-.
, bean- (bean-managed transaction)
(enterprise bean) .
(binary operator)
, .
(bit)
. 0 1.
(bitwise operator)
, , (0 1). ,
(&, |, ^), (<<, >>, >>>)
(~).

(block)
JavaTM,
. , {x = 1;}.
(boolean)
, : true
("") false (""). JavaTM boolean,
true false.
(bounding box)
, .
.
break
JavaTM. break
, . break ,
, "" .
- (business logic)
, . Enterprise Java Beans
(enterprise bean).
- (business-method)
(enterprise bean), -
.
(byte)
. JavaTM
byte.
- (bytecode)
- , Java- Java.

(callback methods)
,
.
(caller)
. .
(caller principal)
, ,
(enterprise bean).

case
Java ( switch),
, ,
( ),
case.
(casting)
.
catch
JavaTM,
,
, try.
char
JavaTM,
.
(class)
JavaTM, .
, .
.
Object.
() (class method)
, .
, .
. . .
(classpath)
, JavaTM
Java (, , JDKTM 1.1.X\bin),
, .
(JVM),
, , , JVM.
() (class variable)
, ,
. .
. . .
(client)
"-" - ,
.
(codebase)
code <APPLET>
: code , codebase - URL , .

(comment)
, .
JavaTM // /*...*/.
() (commit)
, , ,
.
(compilation unit)
, .
JavaTM -
, .
(compiler)
, , .
JavaTM- , Java, (-) Java. . .
(component)
, .
. J2EE :
(enterprise beans), Web-, .
(component contract)
, .
: , ,

, ,
.
(component environment)
, (Application
Component Provider), J2EE.
.
, java:comp/env JNDI.
, , JDBC DataSource
, .
(compositing)
, .
(connection)
. .
(connection factory)
. .
(connector)

(Executive Information Systems - EISs).


EIS
EIS.
, .
(connector architecture)
, J2EE
(Executive Information Systems - EISs).
: EIS J2EE,
. ,
J2EE-. , ,
, .
(constructor)
, .
Java .
( new).
const
JavaTM. ,
Java.
(container)
, , ,
. , (EJB, Web, JSP, ,
-) .
(), (container-managed persistence)
,

(enterprise bean).
, (container-managed transaction)
, EJB-.
(enterprise bean) , .
(context attribute)
, , .
continue
Java, ,
, ,
. , continue
, (
, ).
(conversational state)
bean- ,
bean-. bean-

Java,
bean-.
Common Object Request Broker Architecture - CORBA
,
(Object Management Group - OMG).
(core class)
( ), JavaTM Platform.

, Java. , "" Java,
, , , ,
. . 100% Pure JavaTM.
(core packages)
(Application Programming
Interfaces - APIs) Java, .
create (create method)
, "" ,
(enterprise bean).
(credentials)
,
.
(critical section)
, ,
.
(Compatibility Test Suite - CTS)
, J2EE
J2EE.

D
(declaration)
, ().
( ) ( ). .
.
default
JavaTM,
case switch.
switch, ,
default.

(definition)
, ( ) (
). . .
(delegation)
() -
.
(deployer)
, J2EE .
(deployment)
.
(deployment descriptor)
XML-,
.
- ,
, .
(deprecation)
, , , ,
,
.
" " (derived from)
X " " Y, X () Y. .
, .
(distributed)
.
(distributed application)
, ,
, , , .
: (/),
(/ /), n- (/
/).
do
JavaTM, ,
.
while .
(Document Object Model - DOM)
XML W3C.

double
JavaTM,
double.
(double precision)
JavaTM, ,
64 . . .
(Document Type Definition - DTD)
XML-.

E
EJB- (EJB-container)
, (EJB).
EJB- (EJB Container Provider)
, EJB-.
EJB- (EJB-context)
, (enterprise bean)
, .
"" EJB (EJB home object)
, (, , )
(enterprise bean). "" EJB
. "" EJB
(enterprise bean). ""
EJB, EJB-.
EJB home object JNDI .
EJB-.jar (EJB .jar file)
JAR, EJB-.
EJB- (EJB module)
,
(enterprise beans) EJB.
EJB- (EJB object)
,
(enterprise bean).
, EJB. EJB
, .
EJB- (EJB-server)
, EJB-. , EJB , EJB-,

. J2EE ,
EJB-, EJB-, ,
. EJB-
EJB.
EJB- (EJB Server Provider)
, EJB-.
( ) (EIS resource)
, .
, , - ERP (, ),
.
else
JavaTM,
, if
(false).
EmbeddedJavaTM (Embedded JavaTM technology)
, Java 2 Platform.
,
Java-
.
(encapsulation)
() .
,
, .
, , , ,
, , ,
. . .
(enterprise bean)
, - -,
.
- (Enterprise Information System - EIS)
,
. .
.
/ . : ERP-
(, ),
, .
(Enterprise Bean Provider)
, (enterprise
beans), ,
EJB-.jar .

Enterprise JavaBeansTM - EJB


, -,
, . ,
Enterprise JavaBeansTM, ,
.
(entity bean)
(enterprise bean), ,
. .
, , , ,
.
ebXML
ebXML XML (Extensive Markup Language)
,
Internet. ebXML
,
, , .
(exception)
,
, throw.
,
. JavaTM
try, catch throw. .
.
(exception handler)
, .
,
,
.
(executable context)
, HTML-. . .
"" (extends)
X "" Y (
Y Y).
, X Y. ""
. . " ".

F
(finder method)
, ""
.

(First Customer Ship - FCS)


/ .
(field)
. , .
- final
JavaTM. final
, . Final-
, final- .
finally
JavaTM, ,
, ,
try, .
float
JavaTM,
.
for
JavaTM, ,
. ,
,
( .).
, (form-based authentication)
, Web-
.
FTP - (File Transfer Protocol - FTP)
Internet-, TCP\IP. . . TCP\IP.
(formal parameter list)
, . . .

G
" " (garbage collection)
, .
(JavaTM runtime
system) " " ,
.
, .
.

goto
JavaTM. ,
.
(group)
.
(Graphical User Interface - GUI)
, .

H
(handle)
,
(enterprise bean). ,
(enterprise bean).
(hexadecimal)
16. 0-9 a-f 0 15.
, JavaTM,
0x. . .
(hierarchy)
, , (
), , .
, .
JavaTM, , Object.
"" (home interface)
(enterprise bean). ""

(enterprise bean). (session beans) ""
, (entity beans) , .
"" (home handle)
, "" . ""
,
.
HotJavaTM (HotJavaTM Browser)
Web-, Sun Microsystems
JavaTM.
(HyperText Markup Language - HTML)
Internet, SGML.
, , , ,
. URL.

(HyperText Transfer Protocol - HTTP)


Internet-, TCP/IP
. . TCP/IP.
(HyperText Transmission Protocol, Secure HTTPS)
HTTP SSL (Secure Sockets Layer) - .

I
(Interface Definition Language - IDL)
(APIs), JavaTM,

CORBA (Common Object Request Broker Architecture).
(identifier)
(, , .) , JavaTM.
Internet InterORB Protocol - IIOP
,
TCP/IP CORBA.
if
JavaTM,
, (true).
(impersonation)
,
, . -
.
implements
JavaTM,
, , .
import
JavaTM, ,
, .
(inheritance)
, ,
. . , .
(initialization parameter)
, , .

(instance)
. , JavaTM,
new, -.
(instance method)
, . .
. .
(instance variable)
, .
, . . .
.
instanceof
JavaTM, ,
.
int
JavaTM,
(integer).
interface
JavaTM,
( ).
,
implements.
, (Internet)
,
. Internet ,
.
(Internet Protocol - IP)
Internet.
. , ,
, ,
. , IP,
. . TCP/IP.
(interpreter)
, .
JavaTM Java*. .
, .
(Independent Software Vendor - ISV)
, ,
.

J
J2EE (J2EE application)
, J2EE.
, .war-,
J2EE-. J2EE ,
.
J2EE (J2EE product)
, J2EE.
J2EE (J2EE Product Provider)
, J2EE.
J2EE (J2EE server)
J2EE. J2EE Web / EJB-.
JAIN
. Java APIs for Integrated NetworksTM.
JAR- (Java ARchive files (.jar))
, .
JAR (JAR file format)
- , .
, JavaTM, (.class, , ) JAR-
HTTP-.
.
JavaTM
Sun
, .
JavaTM Application Environment - JAE
Java Development Kit (JDKTM).
Java APIs for Integrated NetworksTM - JAIN
,
, Java.
J2SE (JavaTM 2 Platform, Standard Edition (J2SE platform))
Java.
J2EE (JavaTM 2 Platform, Enterprise Edition (J2EE platform))
. J2EE ,
(APIs) ,
Web-.

JavaTM 2 SDK, Enterprise Edition


J2EE Sun.
J2EE.
JavaBeansTM
.
Java BlendTM
,
JavaTM Java- -
.
Java CardTM API
API , -.
, ISO 7816-4
.
JavaCheckTM Java.
JavaChipTM
Sun, - Java*.
JavaChipTM - Java- - ,
.
JavaTM Compatibility Kit (JCK)
,
Java Java, Java.
TCK Java 2 Standard Edition. . TCK.
JDBC (Java Database Connectivity - JDBCTM)
JavaTM . JDBCTM API
Java-.
Java Developer Connection
, ,
, , , ,
.
Java (Java Development Kit - JDKTM)

Java.
JavaTM Electronic Commerce Framework

JavaTM.

JavaTM Enterprise API


API ,

Internet. JavaTM Enterprise API
.
Java (JavaTM Foundation Classes - JFC)
(Graphical
User Interface - GUI), (Abstract Window
Toolkit - AWT).
JavaTM IDL
,
CORBA J2EE-.
J2EE , OMG IDL IIOP.
JavaTM Interface Definition Language (IDL)
API, Java,
CORBA (Common Object Request Broker
Architecture).
JavaMailTM
API .
JavaTM Media APIs
(APIs)
, , ,
.
JavaTM Media Framework
(,
). Standard extension framework
.
JavaTM Message Service - JMS
(API)
, IBM MQ Series, TIBCO Rendezvous ..
Java Naming and Directory InterfaceTM (JNDI)
API .
Java (JavaOSTM)
, JavaTM
. JavaOSTM Java-
, .
JavaPlanTM
- ,
JavaTM.

JavaTM (JavaTM Platform)


Java, ,
(APIs), , ,
, ,
Java, .
, Java
. ,
,
Sun.
Java 2 - Java.
Java (JavaTM Platform Editions)
"" Java - Java,
,
.
API: (i) " ",
; (ii) "
",
.
Java:

Java 2 Platform, Enterprise Edition:


Java,
,
.
Java 2 Platform, Standard Edition:
Java, ,
.
Java 2 Platform, Micro Edition:
Java, ,
, , -
.

JavaTM Remote Method Invocation (RMI)


Java-,
, Java,
Java, , .
JavaTM Runtime Environment (JRE)
Java (Java Developer Kit - JDKTM)
,
(run-time environment).
Java*, Java .
JavaSafeTM
,
Java.

JavaScript (JavaScriptTM)
, , Web-.
,
.
Java Server PagesTM (JSP)
Web-, , ,
Java
. , - HTML XML , - Web.
JAX
JAX (APIs),
, ,
XML.
XML, ebXML UDDI,
, .
Java Server PagesTM (JSP) (JSP action)
JSP ,
.
XML , ; ,
. .
Java Server PagesTM (JSP action, standard)
, JSP JSP-
.
Java Server PagesTM (JSP action, custom)
, Java, JSP
.
JSP (JSP application)
Web- , Java Server Pages
JSP , , HTML , ,
JavaBeans.
JSP (JSP container)
, , -,
JSP .
JSP (JSP container, distributed)
JSP , Web-,
Java.
, , .
JSP (JSP declaration)
JSP, JSP .

JSP (JSP directive)


JSP, JSP
.
JSP (JSP element)
JSP , JSP . JSP
, .
JSP (JSP expression)
, , ,
.
JSP (JSP file)
.jsp,
HTML, JSP ,
Web-.
JSP (JSP page)
, JSP.
, .
JSP (JSP scripting element)
JSP, ,
JSP ,
JSP. JSP ,
- java.
JSP (JSP scriptlet)
JSP, ,
, JSP . JSP ,
, - java.
JSP (JSP tag)
, JSP,
JSP. , , ..
.
JSP (JSP tag library)
, Java.
JSP JSP
.
Java StudioTM
Java- ,
.
Java (JavaTM Technologies)
,
, .

JavaTM Transaction API (JTA)


API, J2EE .
JavaTM Transaction Service (JTS)
, JTA
Java OMG Object Transaction Service (OTS) 1.1
API.
Java* (JavaTM virtual machine - JVM*)
" ", -
Java ( ).
Java HotSpot -
Java , ,
.
KJava - ,
(runtime environment) Java 2 Platform, Micro Edition. KJava
Java
. 30 128 ,
.
Java Card - ,
(runtime environment) Java 2 Platform, Micro Edition. KJava
Java -
( 24 , 16 EEPROM 512 ).
Web- Java (Java Web ServerTM)
, , , ,
Internet/Intranet Web-.
,
Java.
Java WorkshopTM
,
Java . Java Workshop
,
.
JavaTM wallet
, JavaTM Electronic Commerce Framework,
,
.
JavaSpacesTM
,
JavaTM.
JavaSoftTM
Sun Microsystems,
Sun Microsystems Java Software.

JDBCTM
. JDBC (Java Database Connectivity - JDBCTM).
JDKTM
. Java (Java Development Kit - JDKTM).
JFC
. Java (JavaTM Foundation Classes - JFC).
Jini (JiniTM Technology)
(APIs) Java,
Java 2. Jini
,
.
Jini ,
Java .
JavaTM Management API - JMAPI
Java , ,
.
JMS
. JavaTM Message Service.
JNDI
. Java Naming and Directory InterfaceTM.
JPEG (Joint Photographic Experts Group - JPEG)
,
.
, .
JRE
. JavaTM Runtime Environment.
JIT (Just-in-time (JIT) Compiler)
, (" ") -
. Java.
JVM
. Java*.

K
(keyword)
, JavaTM,
.

L
(lexical)
(, , ..)
. - ,
.
(linker)
, ,
. JavaTM
. . , ,
.
(literal)
,
. , 3.0 - , "" -
.
(local variable)
, , . ,
, ,
.
long
JavaTM,
long.

M
(member)
. , .
(method)
, . . , .
, .
(method permission)
""
(enterprise bean).
(module)
, J2EE,
, .
: EJB, Web .
.
Mosaic
c (GUI),

, Internet.
. Mosaic NCSA.
(multithreaded)
,
(threads),
. . .
(mutual authentication)
,
.

N
native
JavaTM,
, Java, .
(National Center for
Supercomputer Applications - NCSA)
, Mosaic.
new
JavaTM,
.
null
null - "" , null,
ASCII. null null.

O
(object)
- .
( )
( ). . .
- (object-oriented design)
,
.
(octal)
8. 0-7 . ,
JavaTM, 0. .
.
(Open Net Environment - ONE)
, Sun Microsystems

. ,
. ONE
. Sun ONE - ,
Sun iPlanet.
(Optional Package)
API Java,
.
,
.
(Object Request Broker - ORB)
, CORBA
.
(OS principal)
(principal), ,
J2EE.
Object Transaction Service (OTS)
, CORBA .
() (overloading)

. JavaTM , ,
.
(overriding)
,
.

P
(package)
. package.
(passivation)
(enterprise bean)
. . .
(peer)
, .
persistence
(entity bean)
.

PersonalJavaTM
Java
(, ).
(pixel)
, , .
.
Portable Object Adapter - POA
CORBA ,
(ORBs).
(Portable Operating System Interface - POSIX)
, UNIX
.
(primary key)
, (entity bean).
(principal)
, .
private
JavaTM,
. ,
.
(privilege)
,
principals. - .
(process)
, .
(property)
, . , .
(Profiles)
Java API, Java
.
. Java Platform
.
.
.
Java 2 Platform, Micro Edition: PersonalJavaTM, Java CardTM.
protected
JavaTM,

. ,
, .
private
JavaTM,
. ,
.

Q
R
(raster)
.
(realm)
. . , ,
HTTP-, .
,
/ .
(re-entrant enterprise bean)
,
, .
(reference)
, .
(Reference Implementation - RI)
Java-.
Java- , Java-
.
(remote interface)
(enterprise bean).
-, .
(remove method)
, ""
(enterprise bean).
(resource adapter)
, EJB-
EIS. EIS.
,
, . .
, , API (
)

EIS. EJB- ,
- , ,
- EIS.
(resource manager)
.
, .

. : EIS , ,
.
(resource manager connection)
, .
(resource manager connection factory)
, .
return
JavaTM,
. , .
(Request for Enhancement - RFE)
RMI
. JavaTM Remote Method Invocation.
(role (development))
, ,
J2EE. : (Application
Component Provider), (application assembler), ""
(deployer), J2EE (J2EE Platform Provider), EJB-
(EJB Container Provider), EJB- (EJB Server Provider), Web (Web Container Provider), Web- (Web Server Provider),
(Tool Provider), (System Administrator).
(role (security))
,
. ,
, principals .
(role mapping)
, , ,
.
"" .
(rollback)
, , , .

(root)
, .
"". . , , .
(Remote Procedure Call - RPC)
, ,
.
(runtime system)
, ,
JavaTM*. ,
, , Java,
"" , , ,
Java.

S
API XML (Simple API for XML - SAX)
, XML .
Sandbox
,
, ,
, Java* Java.
Sandbox , , ,
.
(scope)
, ,
. Java
, - .
, ;
, (
) .
;
.
(Secure Socket Layer - SSL)
, , Web-
.
(security attributes)
, principal. principal
/ J2EE (J2EE Product
Provider).
(security constraint)
.

Web-, ,
.
(security context)
, .
(security permission)
, J2SE J2EE
,
(Application Component Providers).
(security permission set)
,
(Application Component Provider) .
(security policy domain)
,
. :
1. ( principals);
2. (
principals);
3. .
security role
. (role(security)).
(security technology domain)
,
.
.
server principal
, .
(servlet)
Java , Web-,
Web-
-.
(servlet container)
, ,
, .
HTTP-, ,
, HTTPS.
(servlet container, distributed)
, Web-,

Java.
, , .
(servlet context)
, () Web-, .
, , URL-
, ,
.
(servlet mapping)
URL .
. , , JSP-,
URL, .jsp.
(session)
, , Web HTTP-.
(session bean)
(enterprise bean),
- .
.
.

. , EJB , .
.
short
JavaTM,
short.
(single precision)
Java , 32
. . .
(Standardized Generalized Markup Language SGML)
ISO/ANSI/ECMA
.
Smart Web Services
, ,
,
. ", , , , ",
.
The Simple Object Access Protocol - SOAP
XML HTTP ,

,
Internet.
(Structured Query Language - SQL)
,
.
(stateful session bean)
.
, (stateless session bean)
, .
.
static
JavaTM,
(). ,
, . static
.
, (), , ,
.
(static field)
.
(static method)
.
(stream)
, .
, java.io
(InputStream OutputStream).
(subarray)
, .
(subclass)
, "" . . , .
(subtype)
X "" Y, X - Y. . .
(superclass)
, "" . . , .
super
JavaTM, ,
, .

(supertype)
, . .
, .
switch
JavaTM, ,
case
.
Swing
,
, JavaTM.
, ,
JavaTM. . AWT.
synchronized
JavaTM,
, ,
.
(System Administrator)
, ,
.

T
TCP/IP (TCP/IP)
, IP. Internet-,
. .
IP.
(TCK) (Technology Compatibility Kit - TCK)
, , ,
,
. Java- ,
(reference implementation).
"" (Thin Client)
, ,
,
.
this
JavaTM, ,
. this ,
, .

() (thread)
. ,
, ,
,
.
. . .
throw
Java TM,
, "throwable" (..
, ).
throws
JavaTM, ,
, ,
.
(Tool Provider)
, ,
, J2EE .
(transaction)
.
, .
,
().
.
(transaction attribute)
, (enterprise
bean), EJB
.
: Required, RequiresNew, Supports, NotSupported, Mandatory, Never ("",
" ", "", " ", "",
"").
(transaction isolation level)

, ,
.
(transaction manager)
,
, ,
.
transient
JavaTM, ,
. , transient

, transient
.
try
JavaTM, ,
Java.
catch ,
try. finally
, .
type
.

U
UDDI
" " (The Universal Description
Discovery and Integration - UDDI) , , XML,
-, web
. UDDI Internet- .
(Unicode)
16- , ISO 10646. . ASCII.
JavaTM Unicode.
(Uniform Resource Identifier - URI)
. URI
URL URN. URL URN ,
; URI .
(Uniform Resource Locator - URL)
WWW. URL
: ":///_",
, ( HTTP FTP),
Internet- , , _ ( ), .
URL path
URL, HTTP . URL Context Path +
Servlet Path + PathInfo, Context Path ,
. .
, URL Web-,
.
/, /. Servlet Path - ,
, .
/. PathInfo - , Context Path Servlet
Path.

(URN)
, , ,
. URN
Web. Web-
.
(user data constraint)
, .

.

V
(variable)
, .
(, int Object) . . ,
, .
(virtual machine)
,
- .
,
. JavaTM
, , , "" ""
.
(vocabulary)
,
, .
Java- , ,
, ,
.
. , ,
. , -,
,
.
Java ,
.

. Java
,

.
void
JavaTM, ,

. void
.
volatile
JavaTM, ,

.

W
wait
UNIX(r),
.
Web-, (Web application, distributable)
Web-, J2EE ,
Web ,
Java, .
"" .
Web- (Web component)
, , JSP .
Web- (Web container)
, Web ,
J2EE . (runtime environment)
Web-, , ,
, , . ,
JSP API J2EE. Web
Web J2EE .
Web-, (Web container, distributed)
Web-, Web-, ,
Java,
.
Web- (Web server)
, Internet, Intranet, Extranet. Web-
Web-, HTTP
( CGI- ),
. , Web- Web-
HTTP. J2EE , Web Web- , ..
. Web-
Web-.
Web- (Web Services)
,


. ,
() , SOAP (
), UDDI ( ), XML
( ), WSDL ( Web-).
while
JavaTM, ,
. while.
(world readable files)
, ()
. : , Web-
Internet, " ".
wrapper
,
.
Web- (Web Services Description Language - WSDL)
XML , Web-
Web-.
World Wide Web - WWW
" ". , .. Internet. . Internet.

X
(Extensible Markup Language - XML)
( ).
J2EE XML.

Y
Z

Оценить