Открыть Электронные книги
Категории
Открыть Аудиокниги
Категории
Открыть Журналы
Категории
Открыть Документы
Категории
2:
3:
16
4:
31
5:
51
6:
66
7:
85
8:
98
9:
114
10:
11:
146
12:
13:
186
14:
203
15:
228
16:
251
-
3
.
.
..
Java.
.
. . 125
java.awt..
. . 172
java.lang.
java.util..
java.io.
.
2: -
-
, ,
. , ,
, .
,
. , ,
. FOCAL (FOrmula
CALculator) FORTRAN (FORmula TRANslator).
, ,
. ,
.
. - ,
, .
.
. .
. ,
.
, ,
.
, . , Pascal
:
Procedure printGreeting(name: String)
Begin
Print("Hello, ");
PrintLn(name);
End;
- Hello, Name, Name
.
, ,
. . ,
.
, , ,
.
, (),
.
-.
19.701-90. -
(. 2.1).
. 2.1. -.
. ,
goto .
(bowl of spaghetti),
, , ,
. , goto
.
.
,
.
.
, " ".
70- - 80- .
.
, . ,
,
. , .
- "-",
"-". ,
, , .
-
, ,
, .
,
.
,
. " "
, , , .
.
,
. .
, -
. ,
, . 80-
,
. - ().
, , .
-
.
. ,
, , ,
.. ,
(. 2.2 [3]). -
, .. .
. 2.2. ( ) (
) [3].
, ,
. , "", ,
.
.
. () ,
.
- , :
-
, .
-
, , .
- -
.
.
,
, .
:
();
: , "", , 7461, ..
. ,
- , .
:
- ,
[2].
, .
. (): , , ,
- .
, , , - ,
. -
.
" ".
, ( ""), ,
, . , ,
, , .
, , "" :
(, , );
( ).
, , , (
).
(state) - : ,
, ;
( ) ( ) [2].
, . ,
:
, .. ,
, , - ().
- "" ""
"", .
, , ,
. ,
.
- "", "" ""
. .. " ", " " "
- " . .
, , ,
, "" . ,
, . , ,-
, .
(behavior) - ,
; [2].
- , . ,
. () ( , ..)
, - .
.
Identity () , ,
. ,
, , , Identity .
. ,
.. , (
).
, (identity) - ; , (
[2], ).
(
). , , , - .
. ""
"" "", - .
.
, . , , ""
"" : . ,
, ,
-, .. .
.
(, ""), . ,
, .
(record), ;
, ( ).
- ,
. (, )
, .
, .
, - , - ,
().
,
:
(constructor) - ;
(destructor) - .
, ,
.
(encapsulation) -
(). -
- .
.
( ).
, Java, 6.
.
. ,
. , ,
.
, . .
. -,
,
, , .
-, . ,
, ,
, .
, , , . ,
, ,
, .
, .
(inheritance) - ,
( ), ( ) .
"/",
. .
, " "
" ". , . , 4 ,
, .. , ,
, 5- 12-.
, , "" " " "
", .
.
(- ), - (-
).
,
, .
.
.
.
"", "". ..
, .
, , ,
- .
-
.
Java
8.
-
. "" "
". , - ,
.
, ,
- Point, Line, Circle, Box .. draw
.
, ,
, , draw .
, , , (
) ,
draw. :
// ,
// Point
// 1000
Point[] p = new Point[1000];
Line[] l = new Line[1000];
Circle[] c = new Circle[1000];
Box[] b = new Box[1000];
// ,
10
//
//
. ,
, Text, Star ..,
,
.
, . ,
. Point.
, 2.3.
draw ,
.
, , :
p[] , Point.
- ,
. , p[0] Circle, draw
:
p[0].draw()
, .
.
(polymorphism) - , (, )
( ) . , ,
, - [2].
11
,
.
, .
, - (overloading).
.
. 2.3. .
Java PrintWriter, ,
, . println,
/ . :
void println()
//
void println(boolean x)
//
// (true false)
void println(String x)
// -
// .
. Java ,
. .
, , - ,
.
. , ,
. ,
.
(
, ):
(Aggregation);
(Association);
(Inheritance);
(Metaclass).
12
, (aggregation), ,
, .
.
contain . Aquarium
Fish. "", .
, , .
. home
Aquarium ( ), inhabitants Fish (
). .
, . .. Aquarium
() inhabitants, Fish - home.
, , . "0..n" "
". :
"1..n" - ;
"0" - ;
"1" - ;
"n" - ;
"0..1" - .
, , , , :
// Fish
public class Fish {
// home
// ( Aquarium)
private Aquarium home;
public Fish() {
}
}
// Aquarium
public class Aquarium {
// inhabitants
// ( Fish)
private Fish inhabitants[];
public Aquarium() {
}
}
13
, ,
"", ,
(association). , , ,
,- , .
.
, . , ,
- , .
"--".
Programmer Computer
"0..n", .. , , ( ).
, ( ).
, , , , :
public class Programmer {
private Computer computers[];
public Programmer() {
}
}
public class Computer {
private Programmer programmers[];
public Computer() {
}
}
.
.
, , . ,
, , , , ,
.
, , , ,
. , , ,
, ,
. , , (,
, , ..).
, . ,
, , . ,
, .
, , .
, , ,
, (, ).
, (,
, ) (
).
, . ,
, (,
). " "
.
14
, , - . , , .
, ,
Python. , :
, set_XXX get_XXX,
XXX, .
, "--".
Java . , - Class ( ),
java.lang. .
.class-, , JVM Class,
. , Java
. Class (static) . ,
, . .
, .
.
, , . ,
. .
,
, .
, ,
, .
.
,
.
. ,
. ,
, - .
.
.
15
. , ,
. .
. ,
, , ,
.
. ,
.
"" (framework).
, (framework),
, .
- ,
.
, .
, .
,
, .
, , ,
.
,
, .
- , .
, , ,
, . ,
. , , ,
. , , ,
.
. ,
.
, . ,
. , ,
, , ,
.
, , , ,
. , ,
"" .
. ,
. ,
, , .
, . ?
,
, .
1.
. Smalltalk
. , .
Smalltalk- C-.
Oberon-2, Object Pascal C++
. 10%
, .
, .
, : .
,
.
. , (..
, ), .
16
2.
.
.
.
. , -
.
3.
. ,
. ,
. , .
, .
- ,
, .
- .
.
, . ,
, -
. , ,
.
3:
Java, , Internet,
, , ASCII (American Standard Code for Information Interchange,
), ,
(, , ..), .
Unicode.
, Unicode 2 , , , 65535 .
. 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. web- ,
, http://www.unicode.org/.
, ASCII, Unicode.
, Unicode , ,
, : , , .
ASCII-.
17
, , :
(white spaces);
(comments);
(tokens).
, .
(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, ;
CR, LF.
( ,
), (.
""), (
, ). , Java :
18
.
Java :
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*/";
/*
,
getRadius()
*/
circle.get/*comment*/Radius();
:
19
// :
circle./*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;
*/
y = y*y;// + 2*x;
if-else +2*x.
, Unicode, ,
.
, .
. JDK, 1.0,
javadoc. ,
HTML-, , .
, (, ,
,
). ,
. .
, .
/**. :
/**
* .
*
* x.
*/
int getAbs(int x) {
20
if (x>=0)
return x;
else
return -x;
}
.
( ,
).
HTML-, HTML.
, <b> <p> . <h1> <h6> <hr>
, javadoc .
* .
, , , , .
/**
* -
* .
* <p>
* :
* <blockquote>
* <pre>
* if (condition==true) {
* x = getWidth();
* 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 = getWidth();
y = x.getHeight();
}
HTML-:
,
.
, javadoc . @.
. , @see, ,
, Internet-.
/**
* .
*
* .
21
*
* @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.
, , ,
. /** */ , ,
, javadoc. , ( , ,
Java). package.html,
. HTML-, <body> </body>, ,
.
, ( , .. ,
) , .
, .
, , ,
,
. , :
// .
int x = 3 ;
//
int
x
=
3
;
//
int x = 3 ;
/*
*
*
* int x
* .
*/
int/**/x=3;
, , .
.
Java:
22
(identifiers);
(key words);
(literals);
(separators);
(operators).
, .
, , , , , (
). 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
:
Computer, COLOR_RED, _, aVeryLongNameOfTheMethod
, ASCII-
. (48 ):
abstract double
int
strictfp
boolean
else
interface super
break
extends
long
switch
byte
final
native
synchronized
case
finally
new
this
catch
float
package throw
char
for
private throws
class
goto
protected transient
const
if
public
try
continue implements return
void
default import
short
volatile
do
instanceof static
while
goto const , . ,
. , true, false null null (, ,
), .
.
, , null. Java 6 :
23
(integer);
(floating-point);
(boolean);
(character);
(string);
null- (null-literal).
.
,
. ,
. , , , 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 - :
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
24
.
, .
:
3.14
2.
.5
7e10
3.1E-20
, :
( ASCII- );
( ASCII- E
+ -);
- .
, ( L l
long) 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)).
, , :
25
(positive/negative infinity);
. ,
(, 0.0/0.0 NaN),
Float Double, POSITIVE_INFINITY, NEGATIVE_INFINITY NaN.
.
, .
:
float: 3.40282347e+38f
double: 1.79769313486231570e+308
,
:
float: 1.40239846e-45f
double: 4.94065645841246544e-324
(, 1e40F)
. . ,
(, 1e-350) .
. , :
// , 0
0.00000000000000000000000000000000000000000001f
// , 1
1.00000000000000000000000000000000000000000001f
Java , Float
Double , .
true false.
, .
Unicode, ,
(ASCII- single quote, \u0027). :
'a' //
' ' //
'K' //
(. ""). :
'\u0041' // A
'\u0410' //
'\u0391' // A
26
, ,
\. ( , ", ', \)
:
\b
\t
\n
\f
\r
\u0008 backspace BS
\u0009 horizontal tab HT
\u000a linefeed LF
\u000c form feed FF
\u000d carriage return CR
\" \u0022 double quote "
\' \u0027 single quote '
\\ \u005c backslash \
\ \u0000 \u00ff
.
, Java-.
Unicode-.
. \ .
. :
'\101' // '\u0041'
\u0000 \u00ff (.. 0 255), Unicode .
Unicode- (\uhhhh) ,
:
'\u000a' //
\u000a ,
. :
'\n' //
\u000d ( ) \r.
, .
.
. ,
\ (. " ").
"" //
"\"" //, "
" " // 13
. ,
, \n / \r.
, ,
+. :
// -,
//
" " +
" "
/*
* ,
* :
* Hello, world!
* Hello!
*/
"Hello, world!\r\nHello!"
27
,
\u000a \u000d.
String.
, .
Null-
Null- : null. ,
, . , .
.
, .
. :
()[]{};.,
, , ,
. 37 ( ASCII-) Java:
= > < ! ~ ? :
== <= >= != && || ++
-+ - * / & | ^ % << >> >>>
+= -= *= /= &= |= ^= %= <<= >>= >>>=
,
Java ,
.
( Hello, world!),
:
public class Demo {
/**
* ,
* Java .
*/
public static void main (String args[])
{
System.out.println("Hello, world!");
}
}
, , 7 , 5 , 1
, 13 . Demo.java,
. , :
Hello, world!
.
Java. ,
. ,
(, 1/2 0, 1/2. 0.5).
-, , = ==.
x = 1; // x 1
x == 1 // x
//
true false.
. , :
28
//
if (x=0) { //
// ==
...
}
Java . x=0 0, (
), ( x==0).
" " !=. :
if (x!=0) {
float f = 1./x;
}
- = (.
"") . , :
x = x + 1;
x += 1;
+, -, *, /,
%, , .
. 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
IEEE 754 .
Math.IEEEremainder(double f1, double f2). , f1-f2*n, n
, f1/f2, ,
. :
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;
29
int y=++x;
++ x, , ,
x y. x
y 2.
int x=1;
int y=x++;
x y,
. x 2, y 1.
"" "" (& |) . , ,
, ,
. ,
, ,
.
(&, |) , ( &&, || )
, . :
int x=1;
(x>0) | calculate(x) //
//
// calculate
(x>0) || calculate(x) // -
"" ! , , .
.
int x=1;
x>0 //
!(x>0) //
? : .
( ),
. , x:
x>0 ? x : -x
, ,
. , :
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
30
, -1 11111111. ( 1):
0 00000000
-1 11111111
-2 11111110
-3 11111101
10000000, .
8- 01111111 (=127),
10000000 (=-128). 8 28=256 , ,
,
, .
, "", "", " "
. ,
, , , () . , 5&6:
00000101
& 00000110
------------00000100
// 5
// 6
// ""
//
5&6 4.
"" "NOT", ~ (
!). . , ~(-1)=0.
:
n , -n ~(n-1).
, . Java
. .
<< ,
. 2n
, , .
int, .. 32- .
20, -21.
// 20
20 << 00 = 00000000000000000000000000010100 = 20
20 << 01 = 00000000000000000000000000101000 = 40
20 << 02 = 00000000000000000000000001010000 = 80
20 << 03 = 00000000000000000000000010100000 = 160
20 << 04 = 00000000000000000000000101000000 = 320
...
20 << 25 = 00101000000000000000000000000000 = 671088640
20 << 26 = 01010000000000000000000000000000 = 1342177280
20 << 27 = 10100000000000000000000000000000 = -1610612736
20 << 28 = 01000000000000000000000000000000 = 1073741824
20 << 29 = 10000000000000000000000000000000 = -2147483648
20 << 30 = 00000000000000000000000000000000 = 0
20 << 31 = 00000000000000000000000000000000 = 0
// -21
-21 << 00 = 11111111111111111111111111101011 = -21
-21 << 01 = 11111111111111111111111111010110 = -42
-21 << 02 = 11111111111111111111111110101100 = -84
31
32
4:
Java . ,
.
. , , () ,
"" ( bugs) (
), , .
Java .
. 8 , (
primitive), . :
o byte
o short
o int
o long
o char ( )
o
o
float
double
o boolean
, ( reference), . ,
. Java
, . , ,
Java-.
.
.
:
33
;
.
. ,
. , .
(declaration). ,
. , Java ,
. ( ),
.
int :
int
int
int
int
a;
b = 0, c = 3+2;
d = b+c;
e = a = 5;
, , .
( 3+2),
. (, b+c).
,
( ), .
:
. , , , ,
, . ,
.
.
,
. , , ,
.
, final.
, .
, final- - ,
, .
final-:
final double pi=3.1415;
. , , ,
. ?
int:
int a=5; //
//
int b=a; //
//
a=3;
//
print(b); //
, print(...) (, )
( ,
System.out.println(...), ).
34
, b , 5. ,
. ,
:
byte b=3;
int a=b;
( ).
, b 3 byte, a 3
int. , .
. .
, .
, :
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 ,
, .
, .
, .. ,
. . "",
. .
35
garbage collector ,
.
, , , ,
. , ,
, .
.
.
, 8 , (integer),
(floating-point) (boolean).
byte, short, int, long, char. 1, 2,
4 8 , char 2 , , Java
Unicode. .
, Java ,
, .
4 . char , JVM
. , , char
. , .
char , , ,
, .. 4.1 :
4.1. .
()
byte
-128 .. 127
short
-32.768 .. 32.767
int
-2.147.483.648 .. 2.147.483.647
long
char
, int 2 , ,
. long, ,
Java . , 1 1970 .
, long (!), ,
.
, int long? , int
, long, L l.
, 4 8 , . .
, :
1
-2147483648
2147483648L
0L
111111111111111111L
36
( )
o <, <=, >, >=
o ==, !=
( )
o + -
o
o
o
o
+, -, *, /, %
( ): ++ - <<, >>, >>>
~, &, |, ^
? :
+
.
(true false).
, .
+ -, ( ),
( ). ,
. + , (+x x).
-, x, , 0-x.
, .
int x=-2147483648; //
// int
int y=-x;
y 2147483648,
int, x! , -x==x
!
,
, Java .
, , .
, ,
.
int x= 300000;
print(x*x);
:
-194313216
-2147483648, ,
+231, , , 1000 0000 0000 0000 0000 0000 0000 0000 ( 31 ). int
, -2147483648.
, , ,
(. 3). ,
"" .
, -5 .
5 -. , (, 2147483648)
-.
, Java .
8, 16, 32 64 , 32- 64- . ,
.
long,
long. 64 , ,
, .
long , 32 ,
int ( byte, short, char). int. 32-
.
37
, , . :
int i=300000;
print(i*i); // 32
long m=i;
print(m*m); // 64
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- , ,
.
38
, , 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=-b;
"-" 32 .
,
, :
byte b=1;
byte c=(byte)-b;
, int long. .
.
,
( , ,
). , . ( ,
32 ,
.)
byte x=5;
byte y1=x++;
//
byte y2=x--;
//
byte y3=++x;
//
byte y4=--x;
//
print(y1);
39
x 5
x 6
x 5
x 6
print(y2);
print(y3);
print(y4);
:
5
6
6
5
++ -- byte.
, :
byte x=-128;
print(-x);
byte y=127;
print(++y);
:
128
-128
.
? :. ,
.
byte x=2;
byte y=3;
byte z=(x>y) ? x : y;
// , x y
byte abs=(x>0) ? x : -x;
// !
, , , int, ,
int, . byte,
short, int.
, . +
. , ,
.
int x=1;
print("x="+x);
:
x=1
:
print(1+2+"text");
print("text"+1+2);
40
:
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, .
, , .
char .
: 'c' ( 99), '=' ( 61) c (.. 'A' - 65).
- (wrapper classes).
byte, short, int, long, char Byte, Short, Integer, Long, Character.
. , . ,
Math, ,
.
, , Java ,
( / %).
float double. - 4 8 , . .
:
4.2. .
()
float
3.40282347e+38f ; 1.40239846e-45f
double
1.79769313486231570e+308 ; 4.94065645841246544e-324
, .
,
. , ,
, overflow. ,
, underflow.
41
//
float f = 1e40f;
// , overflow
double d = 1e-350;
// , underflow
, F f, float.
double, D d.
:
( )
o <, <=, >, >=
o ==, !=
( )
o + o +, -, *, /, %
o ( ): ++ --
? :
+
,
( % , ++ --
). ,
. ,
.
overflow underflow. , Java
. , .
, . ,
.
. IEEE
754 3:
(positive/negative infinity);
" ", Not-a-Number, NaN;
.
float, double.
:
1f/0f
// ,
// float
-1d/0d // ,
// double
42
0.0
//
//
+0.0 // +, //
-0.0 // -, //
.
, . +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):
double d = 1e-305 * Math.PI;
print(d);
for (int i = 0; i < 4; i++)
43
print(d /= 100000);
:
3.141592653589793E-305
3.1415926535898E-310
3.141592653E-315
3.142E-320
0.0
, , ,
(overflow) (underflow) , (. 3).
,
.
. 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);
print((double)x/y);
print(1.0*x/y);
:
0
0.6
0.6
, .
,
. ( ),
( ).
,
.
44
-, . ,
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
( )
o ==, !=
( )
o !
o &, |, ^
o &&, ||
? :
+
&& || . ? :
boolean. ,
.
"true" "false"
.
, ,
if.
. ,
( ), x!=0.
boolean ref!=null.
45
, null, ,
JVM.
(object) , .
. ,
, .
, .
new, new
( , ). ,
.
( ), ,
, . ,
Point, new Point (3,5) Point,
int. ,
. ,
Point:
class Point {
int x, y;
/**
* 2 ,
* .
*/
Point (int newx, int newy){
x=newx;
y=newy;
}
, new .
, -
. JVM . ,
, (garbage collector).
"" .
- (1,2) , .
new.
String. , .
+, ,
new.
:
"abc"+"def"
String.
, .
46
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 , Child.
:
instanceof ( )
== != ( )
? :
+
.
. (). .
instanceof, , .
. , ,
. :
Parent p = new Child();
47
// 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.
:
class Child2 extends Parent {
}
Parent:
Parent p=new Child();
print(p instanceof Child);
print(p instanceof Child2);
:
true
48
false
, p2 , p1.
, , p3 - .
, new.
= null, , false.
null, true.
equals, .
, :
String s = "abc";
s=s+1;
print(s.equals("abc1"));
? : ,
. .
, . null,
"null". , (
, toString()) , , .
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()
, . ,
, .
49
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 , -
.
:
print(new Object());
:
java.lang.Object@92d342
, ,
-, , .
,
.
finalize()
50
(garbage collector).
Object , - ,
, , ,
.. , .
, .
finalize() , .
JVM .
String
, String Java .
new. String,
( null), .
,
, , .
. , , ,
-,
.
String s="a";
s="b";
, String.
, Java,
.
-, ,
.
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().
51
, :
1.
2.
3.
4.
Point, (1,2);
Class, Point;
Class, Object. Point Object,
;
Class, Class. Java-,
.
Class cl=p.getClass();
// 2
Class cl2=cl.getClass();
// 4
Class cl3=cl2.getClass();
// 4
cl2==cl3 .
Class reflection.
, Java
, ( ,
..).
52
5: .
:
o ;
o ;
o ;
;
;
(member) :
o ;
o ;
o ;
, ,
. , ,
.
, (packages) Java , ,
, .
, .
.
53
.
(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.
.
, , (,
) . , , -
. .
-, (declaration) . ,
.
-,
, , .
:
country.getCity().getStreet();
getStreet , ,
, getCity(). country.getCity
.
, (label). ,
, , .
num:
for (int num = 2; num <= 100; num++) {
int n = (int)Math.sqrt(num)+1;
while (--n != 1) {
if (num%n==0) {
continue num;
}
}
System.out.print(num+" ");
54
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.
, , , .. .
, , ,
.
.
()
, ,
, ,
(scope). , , , , ,
, .
:
class Point {
int x,y;
int getX() {
return x; //
}
}
class Test {
void main() {
Point p = new Point();
p.x=3; //
}
}
, x .
. , ,
.
. ,
, .
Java (packages).
, .
, .
. -, ,
" ". -, . ,
, ,
, . ,
. , ,
, ,
. , .
, ,
. , .
55
, ( ).
, ,
. .
, 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 ""
.
.
, ,
.
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
space\sunsystem\Moon.java
space\sunsystem\Sun.java
space\sunsystem\Test.java
.class-. ,
. () - ( Windows
\).
, .
, Java space\sunsystem
Test, , - .
, Java, , .
56
, , 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
. , ( ).
, . ,
.
, .
classpath , ,
, . ,
- , Java
.
. ,
.
, , -,
Java-, -, , classpath.
,
. , . ,
.java-, ,
. ,
/ / .
(compilation unit) .java-
. :
57
;
import-;
.
, .
, , (
).
Import- , "" .
.
, . "
" , , ,
. ,
, , . .class .
, .. Java
, .
.
.
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 {
58
, , Java-, space
star ( space.star) Java.
, . ,
, Java .
, java.lang java.io, , java, Java-,
, .
-
, - , .
, .
, ,
. (, JDK1.2
com.sun.image.codec.jpeg), ,
.
import-,
. :
;
.
, , , .
, ,
. , , ,
, ,
. , ,
.
, .
, ,
. .
, , import .
:
import java.net.URL;
, URL
java.net. , ,
. , ,
. ,
.
, , .
import java.awt.*;
, java.awt, .
, , .
, . ,
.
:
//
59
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;
, ?
- ?
, .
:
, ;
, , ;
, , .
, , ,
.
:
//
package my_geom;
import java.awt.Point;
class Point {
}
, Point
java.awt.Point, , , .
:
package my_geom;
class Point {
}
60
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. ,
"" ,
.
. " ", ,
"" ,
.
( ) .
:
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 {
}
,
. ,
, . , ,
,
. , ,
61
, ,
.
.
, .
class, interface. ,
. :
package first;
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
62
space\sun\Size.java, Size.class .
Java.
, . ,
:
package test;
/*
* Human,
*/
class Human {
String name;
Car car; //
}
/*
* Car,
*/
class Car {
String model;
Human driver; // ,
//
}
, Car , .
, .
.
Java , Internet,
, ,
.
. .
Java .
, Internet-, , ,
, , company.com, ,
: com.company.
, , , ..
, ASCII-
:
Java, :
, , , ;
, ;
, .
, :
com.sun.image.codec.jpeg
org.omg.CORBA.ORBPackage
oracle.jdbc.driver.OracleDriver
63
, , , Java- Internet-,
. ,
.
,
.
,
.
, .
, .
java.lang lang.
.
( ) , .
, ,
.
, .
, .
,
super this, .
,
.
,
. ,
.
int x;
for (int i=0; i<10; i++) {
int t=5+i;
}
// t ,
// ,
// , ,
// x ,
//
,
.
"" (Shadowing)
, ,
, , , .
.
, . , .
, .
. :
class Human {
int age;
//
int getAge() {
return age;
}
void setAge(int age) {
64
age=age; // ???
, - ,
this , . ,
,
.
"" (Obscuring)
, ,
.
, :
import java.awt.*;
public class Obscuring {
static Point Test = new Point(3,2);
public static void main (String s[]) {
print(Test.x);
}
}
65
class Test {
static int x = -5;
}
( );
;
;
-;
.
.
, , .
, .
. java javax (Java
eXtension) Sun Java.
"" (obscuring) ,
. ,
.
,
. , , , "".
, , :
Human
HighGreenOak
ArrayIndexOutOfBoundsException
( , ,
.)
, .
"able":
66
Runnable
Serializable
Cloneable
"" (obscuring) ,
() , .
, .
, ,
. :
, ,
, get set, , size getSize() setSize();
, , length(), , String;
, , is, , isVisible()
;
, F, toF(), , toString(),
.
, , , , 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;
67
Exception e; // ,
// Java
- Internet.
6:
, Java .
, , .
.
68
.
Java, , .
.
8 Java. .
.
, , ,
. , : public,
, private, ,
.
, ,
, .
: ,
"" . , 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, ,
(, , , ) .
, private,
, :
public class Human {
private int age;
// , age
public int getAge() {
return age;
}
// , age
public void setAge(int a) {
age=a;
}
69
}
, 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
, , , , , .
, , .
.
Human h = getHuman();
int i=h.getAge(); //
, i . ,
. ,
, :
Human h = getHuman();
double d=h.getExactAge();
//
, , .
? ,
, ( , public). ,
, ,
, .
, :
(accessors)
(getters) (setters). . ,
,
70
, . ,
, .
. ,
. ,
:
public void setAge(int a) {
if (a>=0) {
age=a;
}
}
age . (
, ,
, , ;
Java.)
. ,
, , , . persistent storage ( ,
, ) / . ,
, , ,
, , .
. , ,
, ,
. , ,
, .
, .
,
.
, , , ,
, , .
, ,
, , ,
.
, , .
Java (public private),
. Java .
Java
,
. .
Java :
( ) ;
(, , );
.
, , ,
.
. :
71
public;
private;
protected;
, (default).
. ( )
, . Java
, ,
, .
, protected . ,
, .
,
. protected ,
-, .
protected , .
, ( ):
private
(none) default
protected
public
.
, .
, ( , public,
).
( ) .
: public . public,
, . public,
: , .
, , (,
).
.
. public.
. Private-
-, . ,
, .
(
), , , .
.
. :
public class Wheel {
private double radius;
public double getRadius() {
return radius;
}
}
radius , getRadius() .
:
package first;
// Parent
public class Parent {
}
package first;
72
// Child Parent,
//
class Child extends Parent {
}
public class Provider {
public Parent getValue() {
return new Child();
}
}
getValue() Provider , first,
public. Child,
. :
package second;
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, (
instanceof), . ,
, private- !
, , private ,
, .
Java .
.
73
.
. .
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 (
).
.
, , :
//
class A extends B {}
class B extends C {}
class C extends A {}
// !
implements,
( , ) :
public final class String implements
Serializable, Comparable {}
74
, . ,
. implements ,
, .
, .
(members) :
;
( );
, - .
, , ,
. .
. ,
.
- , . .
, . -
.
,
- ( Object , )
. , ,
.
, protected public. private-
.
, ,
.
.
.
, , .
final, ,
. final- - :
final double PI=3.1415;
final- .
,
, :
final long creationTime =
System.currentTimeMillis();
. - transient
volatile. .
75
.
:
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;}
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;
null.
, y getX(),
x, 0. x 3.
. :
( );
void;
;
( );
throws-.
.
. .
, final, ,
. , final-, private- , final.
76
native. , ,
Java. (C/C++, Fortran ..)
(, DLL Windows). JNI (Java Native
Interface), native-.
Java , ,
. Java,
, . , Java-
, , , . 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() {}
void get(int x) {}
void get(int x, double y) {}
void get(double x, int y) {}
}
. :
void get() {}
int get() {}
void get(int x) {}
77
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);
}
get()
. main, ,
. print() ( , , ,
), , ,
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- ,
.
78
, ,
.
, :
public void empty() {}
, void,
return-. , ,
. ,
:
//
public int get() {
if (condition) {
return 5;
}
}
, return-,
. :
public int get() {
if (condition) {
return 5;
} else {
return 3;
}
}
, , return,
( 7).
( void) return -
. :
public void calculate(int x, int y) {
if (x<=0 || y<=0) {
return; //
// ,
}
... //
}
return ( / )
. ,
.
.
. , -, (
). -, , . ,
. ,
, , .
, :
public class Human {
private int age;
protected Human(int a) {
age=a;
}
public Human(String name, Human mother,
Human father) {
age=0;
}
79
}
, , .
throws- ( , . 10 "").
,
. ,
.
(
).
( - , , )
, .
, , .
return- .
, .
.
, ,
.
,
super.
80
:
public class GraphicElement {
private int x, y; //
81
*/
public class Two {
// Two.
// new Two() !
public Two(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 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);
}
, .
, (,
), .
, .
82
, ,
. this super, (
) . ,
, , .
public class Test {
public Test() {
System.out.println("Test()");
}
public Test(int x) {
this();
System.out.println("Test(int x)");
}
new Test(0) :
Test()
Test(int x)
.
private. ,
. private .
:
private- ,
this, -
;
, , Math;
Singleton,
, -private .
, .
.
public class Test {
private int x, y, z;
//
{
x=3;
if (x>0)
y=4;
z=Math.max(x, y);
}
}
, , ,
(, ,
-).
, ,
. ,
, .
:
83
(
), ;
,
;
, .
.
. -, ,
, .
-, final-.
.
:
;
(
);
,
. , this,
final-, 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
Test()
Test(int)
84
Java.
, Java.
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,
:
javac test\first\Test.java
:
java test.first.Test
, :
java test.first.Test Hello, World!
:
Hello, World!
Java .
?
, , .
. - ?
int x=3;
process(x);
85
print(x);
, :
public void process(int x) {
x=5;
}
? ,
, Java.
,
. process(),
x, .
5 . 3
.
:
public int doubler(int x) {
return x+x;
}
public void test() {
int x=3;
x=doubler(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 . , , :
86
(overloaded) .
.
: , ,
, 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());
//
process(new Child(),(Parent)(new Child()));
null:
process((Parent)null, null);
//
process(null,(Parent)null);
87
7:
, Java , ,
.
, , .
:
long a=3;
a = 5+'A'+a;
print("a="+Math.round(a/2F));
,
(conversion) .
3 , int.
long .
int char.
, 32 .
, a 64 .
, long
float, - . Math.round,
int.
, .
, -
-"" ( int Integer),
toString(), .
, ,
. ,
, , .
:
int b=1;
byte c=(byte)-b;
int i=c;
, int
byte. ,
.
, .
Java :
88
(identity);
(forbidden).
(widening primitive);
(narrowing primitive);
(widening reference);
(narrowing reference);
(String);
.
. Java
.
? ,
.
-, , Java
, . , boolean
, .
-, Java , :
print(getCity().getStreet().getHouse().getFlat().getRoom());
getCity(). ,
City.
getStreet(). , , City.
(getHouse()), .
, .
, .
,
. , :
print((MyFlatImpl)(getCity().getStreet().getHouse().getFlat()));
( )
, 7.1.
7.1. .
, ,
? . ,
. , byte ( 1 ) int ( 4 ).
, ,
, .
, :
byte b=3;
89
int a=b;
b byte a ( , int)
, .
19 :
, char (byte,
short), , , short char . , char,
, .
, , - .
, int float
long float double. ,
, .
:
long a=111111111111L;
float f = a;
a = (long) f;
print(a);
:
111111110656
- - , .
. , int 127,
byte . Java
, .. ,
.
23 :
byte char
short byte, char
char byte, short
int byte, short, char
long byte, short, char, int
float byte, short, char, int, long
double byte, short, char, int, long, float
, ,
.
:
print((byte)383);
print((byte)384);
print((byte)-384);
:
90
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), ,
, , ,
. ,
.
,
, 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
91
byte: 0..-1
long int - , ,
. (short, char, byte) , ,
, int, .
, , . ,
1000..000 ( 32 int, 31 ).
- 1111..111 (32 ). ,
0, .
, 1. byte short
-1, char - , 65535.
, char . . , 2
:
float f=2e9f;
print((int)(char)f);
print((int)(char)-f);
:
37888
27648
char . ,
char int , ,
, .
, boolean
.
( )
.
. :
// Parent
class Parent {
int x;
}
// Child
// Parent
class Child extends Parent {
int y;
}
//
// Parent - Child2
class Child2 extends Parent {
int z;
}
.
, .
. Parent
x, , Parent . Child y
x, Parent. ,
Child Parent. :
Parent p = new Child();
, p x . y
, , p.y, , p
92
Child . ,
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-. ,
.
( ) .
, , , . ,
, 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();
93
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
).
( ) .
. , ..
String. , ,
boolean, , ,
.
, .
.
.
-"", toString().
, JVM
.
"true" "false" .
toString(). null,
"null".
null- "null".
. , :
, - (
). - boolean - , boolean (
- ). , ,
, . ,
, Child Child2 . , Child
, Child . ,
Child2.
. ,
, .
.
, .
94
, , ,
.
.
(assignment). , .
. .
, .
. .
. , .
, .
.
.
(numeric promotion).
(). - (promotion),
, .
.
.
, .
.
, . ,
, :
//
//
//
Parent p = 3;
// -""
//
Long a=5L;
//
// +
String s=true;
, ( ),
, :
int i=10;
long a=i;
Child c = new Child();
Parent p=c;
, ,
:
//
int i=10;
short s=i; // ! !
Parent p = new Child();
Child c=p; // ! !
, :
95
int i=10;
short s=(short)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;
, ,
. ,
:
// long
void calculate(long l) {
...
}
void main() {
calculate(5);
}
, int, long, .
, .
, .
//
void calculate(long a) {
...
}
void main() {
calculate(new Long(5));
//
}
, .
96
void calculate(int a) {
...
}
void main() {
long a=5;
// calculate(a);
// ! .
calculate((int)a); //
}
, , ,
.
, , ,
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() {
print(m(12, 2));
}
// !
, (int, int),
. ,
, , ,
, .
,
.
long get() {
return 5;
}
return int, , ,
long. ,
.
, :
short get(Parent p) {
return 5+'A';
//
}
void main() {
long a = 5L;
//
get(new Child());
//
}
. ,
, .
, . :
(byte)5
(Parent)new Child()
97
(Flat)getCity().getStreet(
).getHouse().getFlat()
, .
, , .
. ,
. , null
. - .
Child c=new Child();
// Child2 c2=(Child2)c;
//
Parent p=c; //
Child2 c2=(Child2)p; //
, , ,
. "" .
. ,
. 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
, ,
() 32 64 . ,
.
.
byte, short char int
.
:
98
+ -;
~;
<<, >>, >>>.
, ,
. , 5<<3L int. ,
int long.
.
, double, int, long, float, double
. ,
, :
double, double;
, float, float;
, long, long;
int.
+, -, *, /, %;
? :.
.
, ,
.
, : , , .
.
, .
, .
. ,
.
:
byte b=3;
char c='A'+3; long m=b+c;
double d=m-3F ;
b byte int.
c char ,
, int. m
int long. , d double,
, float.
. -, - ,
, ,
. ( , .)
, null.
, , , .
99
, ? -
, , , , .
, . ,
, - . . ,
, -
. . : 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(),
, .
- Object .
, ( , , )
, , .
4.1. .
null
null
Object
100
8: Java
,
. :
class Human {
private String name;
}
, name, Human,
, - .
. , (
Human, ). , -
, . " ",
" ". static:
class Human {
public static int totalCount;
}
, , :
Human.totalCount++;
//
101
:
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. ,
, .
.
class Human {
private static int totalCount;
.
Human.getTotalCount();
, :
Human h=null;
h.getTotalCount();
//
Human.getTotalCount(); //
//
,
, .
,
. , main() ,
.
, .
, , .
. static:
102
class Human {
static {
System.out.println("Class loaded");
}
}
,
.
, ,
, :
class Test {
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 , .
, .
. ,
..
class Test {
public void process() {
}
103
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;
public Human (String s) {
name = s;
register(this); //
}
:
John is registered.
this "" :
class Human {
private String name;
104
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, .
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.out.println(c.getValue());
}
,
. , 3. ,
Child, getValue() 5, .
.
, ,
. , ,
105
. super.
:
class Parent {
public int getValue() {
return 5;
}
}
class Child extends Parent {
//
public int getValue() {
//
return super.getValue()+1;
}
public static void main(String s[]) {
Child c = new Child();
System.out.println(c.getValue());
}
}
6.
super , ..
, . ,
, .
this super , .. ,
.
abstract
, , abstract.
, , ,
. , , .
. , , , .
, , , ..;
, .. . ,
, . ,
, , ( paint())
-.
. ,
. ,
, , , ..
, , , .. ,
,
.
? - ,
. paint() .
, ,
, .
. , ,
. ,
, ,
.
:
//
106
, main() .
,
. , , .
, , .
.
, , ,
. abstract ,
. - (implements)
( ) ,
.
, abstract final. . ,
private, native, static.
.
abstract class Test {
public abstract int getX();
public abstract int getY();
public double getLength() {
return Math.sqrt(getX()*getX()+
getY()*getY());
}
}
, getLength() .
, Test,
.
. null
, .
. Java
, ,
. , ,
107
, ?
, ?
,
. ,
, .
Java. ,
.
.
. . public
, ,
. abstract ,
. , ,
.
interface .
extends ,
. , ,
.
. , , A B, B
A, C . , ,
A ,
B.
.
public interface Drawble extends Colorable,
Resizable {
}
, - .
public final static,
, . ,
.
public interface Directions {
int RIGHT=1;
int LEFT=2;
int UP=3;
int DOWN=4;
}
public abstract .
public interface Moveable {
void moveRight();
void moveLeft();
void moveUp();
void moveDown();
}
, , .
108
.
, ,
.
,
. ,
:
interface A {
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.
,
, . ,
.
, , ,
, . ,
, , , ,
.
109
. ,
. ,
, .
. ,
, .
, . ,
, , .
, , , , ,
, . , , ""
-.
(, 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) {
...
}
}
//
public class AntEater extends
Mammal implements InsectConsumer {
public void consumeInsect(Insect i) {
...
}
}
, , :
// , ,
//
class FeedWorker extends Worker {
//
// , ,
public void feedOnInsects(InsectConsumer
consumer) {
...
consumer.consumeInsect(insect);
...
}
}
,
. ,
110
, , .
, ( )
( ).
.
, ,
.
.
. .
. , .
, . :
class Parent {
int a=2;
}
class Child extends Parent {
int a=3;
}
, , .
, . , ,
. , 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.
111
:
class Parent {
int x=0;
public void printX() {
System.out.println(x);
}
}
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)
. , .
:
112
class Parent {
static int a;
}
class Child extends Parent {
}
?
Child.a=10;
Parent.a=5;
System.out.println(Child.a);
a Child. ,
:
5
, , .
, , .
. ,
, .
(overriding) :
class Parent {
public int getValue() {
return 0;
}
}
class Child extends Parent {
public int getValue() {
return 1;
}
}
, :
Child c = new Child();
System.out.println(c.getValue());
Parent p = c;
System.out.println(p.getValue());
:
1
1
, , 0 ,
Child.
, . , ,
, -
super.
:
113
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();
, .
, (, 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();
114
Parent.
, . - ,
Child, . ,
, . ,
, protected public. Protected-
, public, public .
private-, , ,
,
..
throws-,
.
, , (implements).
, , , .
(), 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
, ,
.
, .
, .
115
-, , .
:
;
, :
o private-;
o "" ( , );
o () .
-, . ,
, .
, .
, , .
.
8.1. .
null
null
( implements);
- ,
, , :
;
;
, Java ,
. ,
, , , , .
, ,
, ,
. ,
.
Java, -
, .
Java .
116
9:
Java
, , (arrays)
. ,
. , ,
.
, . n,
, 0 n-1.
, .
(, 100 ), (,
100 Car).
, Java char[] String .
,
.
, Java ( Java
), Object,
-.
. ,
.
, , - ,
.. .
117
", 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];
, .
, , .
, , ,
.
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; // !
//
.
, ,
. , :
118
. 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; //
// !
, , , ,
.
,
, 0. boolean,
false.
for.
. , Point.
new Point,
. null.
:
Point p[]=new Point[5];
for (int i=0; i<p.length; i++) {
System.out.println(p[i]);
119
}
null.
, , . ,
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 {
Child
. null,
. new String[2], firstName
lastName . {firstName, lastName} ,
.
:
new String[]{firstName, lastName}
, new, .
.
. ,
int i[][]=new int[3][5];
120
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.
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]. :
( ) , 5 ( ). ,
.
( ) .
:
int x[][]=new int[3][];
null. ,
, x.length 3 .
x[i].length , , i
x.length, x[i] null.
.
, new ,
. ,
. ,
null, .
, , .
, .
, :
121
122
[Ljava.lang.String;@92d342
7051261
, Java, ,
.
( )
. ,
.
, .
Object Cloneable
Serializable. ,
. ,
. , , ,
, , .
, , ,
, .
. , ,
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];
, . , Child[][]
Parent[][], (Child[] Parent[])
( Child Parent ).
, ( ),
.
, .
, , .
, . ,
. , :
//
byte b[]={1, 2, 3};
int i[]=b;
, b[0] i[0] . ,
.
, .
.
new. ,
, .
, ,
System.arraycopy(),
.
ArrayStoreException
123
, ,
.
:
Child c[] = new Child[5];
Parent p[]=c;
p[0]=new Parent();
. .
Parent .
. ,
, . , "",
. ,
Child Parent, .
, , ,
:
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.
, .
, , , .
, null.
" " :
1.
2.
3.
null;
, ;
, , .
124
Object. ,
, .
.
. 9.1.. .
Object
null
null
, :
A, B
, B A
null
, , ,
, . , ,
x, , x.clone(),
x == x.clone()
,
x.clone().getClass() == x.getClass()
,
x.equals(x.clone())
. clone() , :
, , ,
(, private);
, , ,
,
;
,
; ,
;
, , .
.
Object clone(). :
protected native Object clone()
throws CloneNotSupportedException;
125
. .
:
, , .
, ,
, .
clone() Object. ,
native, , . ,
JVM, .
clone() , .
Object.clone(),
Cloneable. ,
, . ,
CloneNotSupportedException.
Cloneable , ,
. ,
. , , ,
. .
, Object Cloneable, new
Object().clone() . clone() ,
super.clone().
:
public;
CloneNotSupportedException;
, .
, Cloneable , , .
, , .
:
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=null;
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
,
. .
126
,
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,
.
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,
. ,
.
, . ,
- , 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};
127
System.out.println(b[0][0]);
} else {
// :
a[0][0]=0;
System.out.println(b[0][0]);
}
, . ,
, . . ,
, .
. ,
, .
1.
, .
0.
, if-else, , ,
, 1,
, .
, Java , ,
.
, .
10: .
.
.
, ,
, ,
.
.
.
, (
). ,
128
break
continue
return
( ,
).
,
.
throw (
) .
. :
break ( );
break ( );
continue ( );
continue ( );
return ( );
return ( );
(). ""
, ..
.
,
(.. ).
, ,
, ( ,
).
- , ,
. ,
.
, . ()
, . - ()
, .
.
.
public class Test {
public Test() {
}
public static void main(String[] args) {
Test t = new Test();
int x;
lbl: {
int x = 0;
System.out.println("x = " + x);
}
}
}
129
, -. ,
.
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.
.
130
First block x = 1
Second block x =2
For cycle x = 0 1 2 3 4
, .
, .
.
, , . break
continue. , , . ,
:
, ,
, .
:
131
static int x = 5;
static {
}
public Test() {
}
public static void main(String[] args) {
Test t = new Test();
int L2 = 0;
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 .
( ) , ,
, .
if
, Java,
, .
:
if ( ) 1
else 2
, .
C,
, , - . Java
.
"", 1,
- 2. (else) .
.. if(x == 5) System.out.println("Five") .
if-else .
132
...
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(" 5");
} else{
System.out.println(" ");
}
" 5" .
switch
switch() .
.
:
switch(int value) {
case const1:
case const2:
case constn:
default:
}
, default .
switch byte, short, int, char .
. case
long Long, String, Integer, Byte ..
switch x ,
case, .
,
case. , case, ,
switch.
case, default, switch.
default case , switch
.
, , if-else, - case ,
switch , .
, case break,
switch.
case , 32-
. , final static.
:
int x = 2;
switch(x) {
case 1:
133
case 2:
System.out.println(" 1 2");
break;
case 3:
case 4:
System.out.println(" 3 4");
break;
default:
System.out.println(
" ");
}
" 1 2". break,
.
.
int x = 5;
switch(x) {
case y: // !
...
break;
}
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.
Java :
while;
do;
for.
while
while :
while( )
, ;
, ,
.
134
continue break . ,
continue, , , .
continue while, .
while, ,
, .
break, .
- ( ),
.
:
.. .
x=1 y=1
x=3 y=2
x=5 y=3
.. if(x % 2 == 0) continue lbl; x ,
y .
while():
135
int i = 0;
while( i++ < 5) {
System.out.println("Counter is " + i);
}
, while() ,
. , ,
while() .
boolean b = false;
while(b) {
System.out.println("Executed");
}
System.out.println("Executed"); .
do
do :
do
;
while( )
do , . while,
, , .
do:
int counter = 0;
do {
counter ++;
System.out.println("Counter is "
+ counter);
} while(counter < 5);
do while, break
continue.
for
-
.
for.
for :
for( ; ;
)
;
,
.
.
(, ).
,
while(). , . while(),
136
. , ""
.
,
. ,
.
for():
...
for(counter=0;counter<10;counter++) {
System.out.println("Counter is "
+ counter);
}
, counter . 10
0 9.
:
for(;;) {
...
}
. while(true){}.
, , .
for().
, .
...
int x = (int)(Math.random()*10);
137
y/x = 8
y/x = 4
y/x = 2
, , , ..
0, 9 for .
138
break . continue,
, break .
. ,
, . 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;
...
}
}
...
break .
break continue . break
, - goto. continue (
) .
:
lbl:{
...
if( val > maxVal) break lbl;
...
}
continue . if
lbl , (),
.
, .
, :
139
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: {
...
}
...
}
return
.
return, ( )
. return , .
( void), return
. , return ,
.
return
140
,
12, .
. (Exceptions)
. ,
- . , /
. , , ,
, , .
:
...
int statusCode = someAction();
if (statusCode){
...
} else {
statusCode = anotherAction();
if(statusCode) {
... ...
}
}
...
Java - .
try{
someAction();
anotherAction();
} catch(Exception e) {
//
}
, , .
.
. , ,
, null, , (class-) , ..
, , -
.
throw . ,
.
.
( ),
stop() Thread.
, .
( stop()), ,
.
, Java . ,
,
. , Java ,
, .
,
( , ),
( , , ,
.).
141
.
. JVM,
, .
(
).
.
, ,
. , ,
- , - .
. 12 .
,
, catch ( ) , Throwable,
(. -),
. , catch
. .
, , ,
.
, , ;
, , ( ,
new);
, ,
, .
.
,
Throwable, .
try-catch
:
try {
...
} catch(SomeExceptionClass e) {
...
} catch(AnotherExceptionClass e) {
...
}
. , try.
,
catch, try.
try ,
.
, catch.
, catch ( ).
, , try
(), catch.
catch , try .
, catch,
try .
142
try-catch-finally
finally , -
. , try, catch,
catch,- finally .
: try ,
finally. , finally , try
.
try catch,
, catch . catch
, , finally. finally ,
try , catch.
catch , ,
finally. , finally , try
, try.
, finally , try
.
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();
}
, / . ,
finally , ,
, .
try-catch-finally catch finally.
try {
...
} finally {
...
}
. finally
,
.
,
.
, ,
.
(, main()),
Java ( - ,
).
throw
143
, Java,
. throw.
:
...
public int calculate(int theValue) {
if( theValue < 0) {
throw new Exception(
"
");
}
}
...
,
; , throw .
( throws Exception -
.)
.
throws,
, .
:
...
public int calculate(int theValue)
throws Exception {
if( theValue < 0) {
throw new Exception(
"Some descriptive info");
}
}
...
, throw
, Throwable.
.
.
:
...
try {
...
} catch(IOException ex) {
...
//
...
//
//
throw ex;
}
.
, throw try-catch.
try {
...
throw new IOException();
...
144
} catch(Exception e) {
...
}
, try,
, try-catch, ,
. catch.
: (checked)
(unchecked).
, Throwable, .
: Throwable - Error Exception, Exception - RuntimeException.
, Exception ( RuntimeException), .
.. , .
, , (, - .),
, . ,
.
, .
, RuntimeException,
.
, , (,
IndexOutOfBoundsException - , java.lang.ArithmeticException - ). ,
,
try-catch.
, Error, . ,
,
( ).
, , , JVM.
StackOverflowError ( ), OutOfMemoryError ( ).
catch,
, . :
try {
...
}
catch(Exception e) {
...
}
catch(IOException ioe) {
...
}
catch(UserException ue) {
...
}
145
. 10.1. .
(, Exception)
catch. .
, UnreachableCodeException ( - ).
:
try {
...
}
catch(UserException ue) {
...
}
catch(IOException ioe) {
...
}
catch(Exception e) {
...
}
146
. ,
, (, AnotherUserException),
catch(Exception e){:}
catch, try-catch .
, .
, java.lang.Throwable ( Throwable).
:
public class UserException extends Exception {
public UserException() {
super();
}
public UserException(String descry) {
super(descry);
}
}
, :
147
LegalOne , method() (
);
LegalTwo , method() (
, , );
LegalTree , method()
( , ,
, );
IlegalOne , method()
(IllegalAccessException IOException, );
IlegalTwo : method() (
), , throws.
, .
:
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 handle stack trace");
ex.printStackTrace();
}
}
148
at java.io.FileInputStream.<init>(FileInputStream.java:64)
at experiment.Test.doFileInput(Test.java:33)
at experiment.Test.main(Test.java:21)
First exception handle stack 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 handle stack trace
Exception,
. ,
, .
:
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();
}
}
149
11: java.awt
Java- ,
(GUI) , , ,
, . ,
GUI . -, Java
, Java-,
. -, ,
. , , , ,
.
AWT Abstract Window Toolkit. abstract ,
,
.
Component
Component AWT .
AWT ,
.
.
( int) x y. Java (
) x , , ,
, , .
Point ().
public int x y, .
Point AWT, .
.
setLocation(),
, Point. getLocation(),
Point, getX() getY(), Java 1.2.
, AWT ,
width () height ().
Dimension (), public int width height,
.
setSize,
, Dimension. getSize(),
Dimension, getWidth() getHeight(), Java 1.2.
. , ,
(x, y, width, height), Point Dimension,
Rectangle (). , public int ,
Point Dimension.
setBounds, ,
Rectangle. getBounds(), Rectangle.
150
, .
visible. setVisible, , isVisible,
.
, .
, .
, .
disabled. , enabled. ,
, (, , ),
, , ( ).
setEnabled, (true
enabled, false disabled), isEnabled.
, .
, , foreground background .
, , .. ,
, , , .
AWT Color.
, .
3 , RGB, , , .
0 255 ( , int). (0, 0, 0)
, (255, 255, 255) .
Color , , , - ,
RGB . Color , :
, , , . , ,
(0, 0, 255), Color.blue Color.BLUE (
).
foreground setForeground getForeground, background
setBackground getBackground.
, ,
.
AWT Font,
, .
. Java.
1.0 , JVM : TimesRoman, Helvetica, Courier.
, .
, Toolkit.
,
:
Toolkit.getDefaultToolkit().getFontList()
- .
151
152
getComponent(int n) ;
getComponents() ;
getComponentCount() ;
, (location) . ,
,
.
, getLocationOnScreen.
size.
. ,
( , , ).
Component, , , ,
. . ,
.
, AWT.
.
?
paint. ,
. , Graphics.
,
, , , ..
Component paint , Graphics,
:
public void paint(Graphics g) {
g.drawLine(0, 0, getWidth(), getHeight());
g.drawLine(0, getHeight(), getWidth(), 0);
}
, :
Graphics
Graphics, .
drawLine(x1, y1, x2, y2)
1 , (x1, y1) (x2, y2).
.
153
154
Graphics
Graphics , . .
, , , .. .
foreground .
setColor.
:
public void paint(Graphics g) {
for (int i=0; i<4; i++) {
for (int j=0; j<4; j++) {
int c = (int)((i+j)*255/6);
g.setColor(new Color(c, c, c));
g.fillRect(i*getWidth()/4, j*getHeight()/4, getWidth()/4, getHeight()/4);
}
}
155
}
:
getColor.
drawString , .
Graphics. ,
setFont. getFont.
Clip ()
Graphics , (
int), clip.
. , drawLine(-100, -100, 1000, 1000),
, .
. clipRect(int x, int y, int width, int height)
clip. . ,
clip. setClip(int x, int y, int width, int height)
. getClipBounds Rectangle.
.
paint, , clip .
.
:
public void paint(Graphics g) {
Color c = new Color(
(int)(Math.random()*255),
(int)(Math.random()*255),
(int)(Math.random()*255));
g.setColor(c);
//g.setClip(null);
g.fillRect(0, 0, getWidth(), getHeight());
}
, paint ,
. Graphics ,
clip, .
156
. ""
- "" ,
( ):
, , . ,
, . ,
"" . , ,
clip, , ,
.
, null setClip.
, , .
,
.
repaint update
paint Component , .
, paint ,
, . ,
. , , .
( ),
.
repaint. ,
Graphics, (, ,
Graphics ). repaint .
. long .
. int (x, y, width, height),
, . , 5
, .
, paint, update.
Graphics (
background), paint. ,
paint? , ,
. ,
,
update .
, update .
, , , .
. -, ,
, , paint,
. -, ,
.
. ,
, .
.
157
, , .
, . paint
.
-, ( visible false), , , paint
.
-, ,
. ,
() .
clip .
,
.
Graphics .
create, Graphics, (int x, int y, int
width, int height). Graphics (x, y), clip-
(0, 0, width, height) (
). create .
paint,
. Graphics
dispose(). , translate
(int x, int y).
, paint . , , , .
AWT , , ,
.
. , ,
Java-.
, , .
Java Window, Container
.
Component
, Component Container,
, .
Component.
Canvas
Canvas Component. ,
.
, sin(x):
public class SinCanvas extends Canvas {
public void paint(Graphics g) {
int height = getHeight(),
width = getWidth();
// ,
//
// 5
double k=2*Math.PI*5/width;
int sy = calcY(0, width, height, k);
for (int i=1; i<width; i++) {
int nsy = calcY(i, width, height, k);
g.drawLine(i-1, sy, i, nsy);
sy=nsy;
158
// ,
//
private int calcY(int x, int width,
int height, double k) {
double dx = (x-width/2.)*k;
return (int)(height/2.*(1-Math.sin(dx)));
}
}
, paint. :
Label
, . ,
String . Component ,
, . Label
setText.
, .
AWT.
Button
.
String . ,
.
Checkbox CheckboxGroup
Checkbox .
, checkbox ,
(, ).
checkbox.
, checkbox:
Checkbox payment = new
Checkbox(" ");
payment.setBounds(10, 10, 120, 20);
add(payment);
Checkbox delivery = new Checkbox("");
delivery.setBounds(10, 30, 120, 20);
add(delivery);
:
159
, Checkbox "",
.
Checkbox "" (radio buttons).
,
. CheckboxGroup. ,
. Checkbox. ,
, :
CheckboxGroup delivery = new CheckboxGroup();
Checkbox fast = new Checkbox(
" (1 )", delivery, true);
fast.setBounds(10, 10, 150, 20);
add(fast);
Checkbox normal = new Checkbox(
" (1 )", delivery, false);
normal.setBounds(10, 30, 150, 20);
add(normal);
Checkbox postal = new Checkbox(
" ( 1 )",
delivery, false);
postal.setBounds(10, 50, 150, 20);
add(postal);
:
Checkbox ,
( ). (
, GUI).
Choice List
Choice (
). :
Choice color = new Choice();
color.add("");
color.add("");
color.add("");
color.add("");
add(color);
160
.
. :
, Choice .
List, Choice,
. , List .
:
List accessories = new List(3);
accessories.add("");
accessories.add("");
accessories.add("");
accessories.add(" ");
add(accessories);
( ):
4 . 3, 3
. .
List .
true (false
), setMultipleMode.
TextComponent, TextField, TextArea
TextComponent Component , ,
TextField TextArea.
TextField .
:
161
( getText
). ( , ).
. Component
enabled, , false, .
editable ( ), isEditable setEditable.
, , , , ,
, .
TextField .
, . TextField
setEchoChar (, setEchoChar('*')).
TextArea .
, ( ).
:
Scrollbar
Scrollbar ,
. .
" " .
"" , .
, , " " .
, , Windows.
Scrollbar.
VERTICAL
HORIZONTAL. , , "",
, .
getValue setValue.
, , Scrollbar.
int height = getHeight(), width = getWidth();
162
Container
AWT.
Panel
, Canvas ,
Panel . ,
Panel, Container, ,
, .
ScrollPane
Scrollbar, . , ,
,
,
, , ..
ScrollPane.
. -,
. -, ,
. , "" .
ScrollPane ( ),
.
ScrollPane.
, .
? Panel.
, , , ScrollPane.
,
, , .
163
Window
,
. Window
, Java. ,
, .
, Window Frame Dialog,
. Window , ,
( splash screen).
Window Window Frame. ,
, .
Frame Dialog
Frame , ,
, . Frame, ,
, , ,
.
.
,
(" ").
public class TestCanvas extends Canvas {
public void paint(Graphics g) {
g.drawLine(0, 0, getWidth(), getHeight());
g.drawLine(0, getHeight(),getWidth(), 0);
}
public static void main(String arg[]) {
Frame f = new Frame("Test frame");
f.setSize(400, 300);
f.add(new TestCanvas());
f.setVisible(true);
}
}
:
, .
.
Frame , Dialog
. , ,
164
, ...
, . .
Dialog ,
. . Frame,
.
. ,
, .
FileDialog
FileDialog ( Dialog)
. (open file), (save file).
, .
, .
LOAD SAVE.
FileDialog . .
getDirectory ( )
getFile ( ). "" ("Cancel"),
null.
" "
. .
, , .
Observer/Observable.
AWT.
-. AWT (listener) ,
Listener. - ,
"" (event), "" . , ,
.
java.util.EventObject. AWT,
, java.awt.AWTEvent.
java.awt.event.
, , , ,
ActionEvent.
ActionEvent
ActionEvent .
, :
Button save = new Button("Save");
add(save);
, , .
AWT ActionEvent. , .
ActionListener. (
), ActionEvent.
, :
class SaveButtonListener
implements ActionListener {
private Frame parent;
public SaveButtonListener(Frame parentFrame)
{
165
parent = parentFrame;
}
public void actionPerformed(ActionEvent e)
{
FileDialog fd = new FileDialog(parent,
"Save file", FileDialog.SAVE);
fd.setVisible(true);
System.out.println(fd.getDirectory()+"/"+
fd.getFile());
}
}
,
FileDialog. actionPerformed ActionListener ,
. , ,
. .
.
addActionListener.
save.addActionListener(
new SaveButtonListener(frame));
.
:
import java.awt.*;
import java.awt.event.*;
public class Test {
public static void main(String args[]) {
Frame frame = new Frame("Test Action");
frame.setSize(400, 300);
Panel p = new Panel();
frame.add(p);
Button save = new Button("Save");
save.addActionListener(
new SaveButtonListener(frame));
p.add(save);
frame.setVisible(true);
}
class SaveButtonListener
implements ActionListener {
private Frame parent;
public SaveButtonListener(Frame parentFrame)
{
parent = parentFrame;
}
public void actionPerformed(ActionEvent e)
{
FileDialog fd = new FileDialog(parent,
"Save file", FileDialog.SAVE);
fd.setVisible(true);
System.out.println(fd.getDirectory()+
fd.getFile());
}
}
"Save". ,
. .
AWT
, AWT XXEvent, XXListener, -
addXXListener.
166
, -
. , ActionEvent
(Button), Enter (TextField),
(List) .. , ,
addXXListener.
, ActionListener, .
, MouseMotionListener mouseMoved (
) mouseDragged ( ).
, . ,
java.awt.event -, , MouseMotionAdapter (
). Object
. , , .
, .
(event) . getSource()
- . AWTEvent .
, MouseEvent , getX getY ,
.
addXXListener removeXXListener. Java
, ,
, .
, ,
. garbage collector, removeXXListener.
AWT , Java
1.1.
MouseMotionListener MouseEvent
. .
mouseMoved mouseDragged
. , MouseMotionEvent (
), MouseEvent, MouseListener.
MouseListener MouseEvent
mouseEntered mouseExited. ,
, .
: mousePressed, mouseReleased mouseClicked.
, , .
, getClickCount MouseEvent . ,
getX getY , . ,
, getModifiers :
(event.getModifiers() &
MouseEvent.BUTTON1_MASK)!=0
, .
KeyListener KeyEvent
: keyTyped, keyPressed, keyReleased.
Unicode- . keyPressed ,
keyReleased . .
, Shift "A",
keyTyped keyPressed/Released.
, , , keyPressed keyTyped,
keyReleased.
KeyEvent , ,
(Ctrl, Alt, Shift ).
167
FocusListener FocusEvent
.
, , , Tab.
FocusListener focusGained focusLost (/).
TextListener TextEvent
- TextComponent TextEvent.
textValueChanged. , , ,
, .
ItemListener ItemEvent
, Checkbox, Choice, List.
itemStateChanged, .
AdjustmentListener AdjustmentEvent
ScrollBar. adjustmentValueChanged,
.
WindowListener WindowEvent
( Window ).
windowClosing. ,
, , .
, Java . , AWT
WindowEvent , :
public class WindowClosingAdapter
extends WindowAdapter {
public void windowClosing(WindowEvent e)
{
((Window)e.getSource()).dispose();
}
}
windowClosing , .
setVisible(false), . Window
, dispose,
, .
, windowClosed.
ComponentListener ComponentEvent
, , visible.
ContainerListener ContainerEvent
.
Java AWT , , .
, .
168
, , ,
. , AWT
.
, , .
. ,
, : , ,
.
:
Button b = new Button();
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
processButton();
}
});
, . ,
addActionListener. . ,
(new ActionListener()), .
, , ,
. Object ActionListener.
actionPerformed, .
processButton. , . ,
.
, . ,
.class- Java, . Test,
Test$1.class.
,
, , , .
,
, . .
import java.awt.*;
import java.awt.event.*;
public class DrawCanvas extends Canvas {
private int lastX, lastY;
private int ex, ey;
private boolean clear=false;
public DrawCanvas () {
super();
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
lastX = e.getX();
lastY = e.getY();
}
});
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
ex=e.getX();
ey=e.getY();
repaint();
}
});
addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
if (e.getKeyChar()==' ') {
clear = true;
repaint();
169
}
});
DrawCanvas , .
. ( repaint),
update. main frame, windowClosing.
- :
170
.
.
init
.
, . , , AWT-,
, ..
start
. .
- , , . ,
( Back), , . ,
,
.
start .
stop
start .
destroy
,
. destroy.
AWT- init
, . ,
. , ,
.
, -, ,
, . ,
, Java. , ,
, .
Java, . ,
MS Internet Explorer Java 1.1,
. Sun Java Plug-in,
JVM .
.
HTML-
HTML-, , - ,
. <applet>. <APPLET> :
<APPLET
CODE = appletFile
WIDTH = pixels
HEIGHT = pixels
[ARCHIVE = jarFiles]
[CODEBASE = codebaseURL]
[ALT = alternateText]
[NAME = appletInstanceName]
[ALIGN = alignment]
[VSPACE = pixels]
[HSPACE = pixels]
>
[HTML-,
Java]
</APPLET>
171
(VSPACE),
(HSPACE).
:
import java.applet.*;
import java.awt.*;
public class HelloApplet extends Applet {
public void init() {
add(new Label("Hello"));
}
}
HTML- :
<applet code=HelloApplet.class
width=200 height =50>
</applet>
HTML . ,
.
HTML :
<applet code=HelloApplet.class
width=200 height =50>
<param name="text" value="Hello!!!">
</applet>
:
import java.applet.*;
import java.awt.*;
172
;
;
;
- (constraint),
.
AWT . null,
. LayoutManager.
constraints (String). (
, ).
LayoutManager2, constraints.
.
. , .
, . .
getInsets Container.
Insets. , top, right, bottom, left,
, , ,
.
FlowLayout
173
Panel. ,
, . "", ,
, , .
(
LEFT, RIGHT, CENTER ),
(vgap) (hgap). 5 .
:
final Frame f = new Frame("Flaw");
f.setSize(400, 300);
f.setLayout(new FlowLayout(FlowLayout.LEFT));
f.add(new Label("Test"));
f.add(new Button("Long string"));
f.add(new TextArea(2, 20));
f.add(new Button("short"));
f.add(new TextArea(4, 20));
f.add(new Label("Long-long text"));
f.setVisible(true);
, , :
BorderLayout
Window Frame Dialog.
BorderLayout . 5 ,
: NORTH, SOUTH, EAST, WEST, CENTER ( ).
. ,
. , .
. ,
, . ,
.
:
final Frame f = new Frame("Border");
f.setSize(200, 150);
f.add(new Button("North"),
BorderLayout.NORTH);
f.add(new Button("South"),
BorderLayout.SOUTH);
f.add(new Button("West"),
BorderLayout.WEST);
f.add(new Button("East"),
BorderLayout.EAST);
f.add(new Button("Center"),
174
BorderLayout.CENTER);
f.setVisible(true);
:
hgap vgap ( ).
GridLayout
( ).
( , ).
:
final Frame f = new Frame("Grid");
f.setSize(200, 200);
f.setLayout(new GridLayout(3, 3));
for (int i=0; i<8; i++) {
f.add(new Button("-"+(i+1)+"-"));
}
f.setVisible(true);
:
hgap vgap ( ).
CardLayout
175
. ,
. , .
12: .
,
. , Java
, .. (threads) .
,
.
Java, .
,
,
. ,
, , . Java
synchronized. .
wait(), notify(), notifyAll() Object.
, ,
.
,
. ,
. .
, , , ?
(time-slicing).
. ,
.
.
, , .
, ( ),
, , . , Windows
, .
.
?
, .
, , .
, ,
() . , ,
, , . ,
.
, , ,
. ,
, .
,
.
176
, .
, .
.
,
. ,
, .
time-slicing, , , , ,
, , ,
, , .
,
. Java ,
.
,
. , .
, , , .. ,
. ,
, ,
, . ,
, ,
. , , ,
, , ,
.
(, ),
, , .
- . ,
, , ,
, , , . ,
, , - (
). ()
( , ),
. , ,
.
(priority) . Java
. , . ,
- .
.
,
. ,
.
, .
. , ,
.
, .
, , . ,
Java () .
, , ,
. , garbage collector' .
(daemon), .
, -.
, Java.
Thread
Java Thread. ,
, run(). ,
177
run() , . ,
- start(),
, run().
MyThread t = new MyThread();
t.start();
:
499500
run() ( , return), .
.
.
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().
178
, Java . Thread
getPriority() setPriority(), :
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();
}
Thread:
getName()
, Thread . Runnable
. , .
. , Java
"Thread-" ( ).
getName(). setName().
currentThread()
Thread,
.
:
Thread 0 started
Thread 1 started
179
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
2
0
1
2
0
1
2
0
2
1
2
0
1
2
0
1
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");
}
}
. , 1, 10,
5. ,
, 3.
:
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
180
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). , ,
. ,
.
( 500000 , 50000,
1000- , 10000-), ,
, .
-
- ,
.
setDaemon() isDaemon().
:
public class ThreadTest implements Runnable {
// ,
// 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 = new Thread[count+10];
181
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) {}
}
}
12.1.
. 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,
12.2.
, - run(), ,
-- .
, :
ThreadGroup
, ThreadGroup.
. , ,
, .
activeCount() enumerate() , ,
.
182
sleep()
Thread
. ,
InterruptedException. , .
, sleep(),
, , interrupt()
. sleep() InterruptedException.
sleep(), yield() . ,
.
, ,
.
,
, .
, .
, ,
.
:
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;
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);
}
12.3.
183
,
, one() two(). a b ,
. , 1 2, , ,
, , . ,
, . :
135 864 1
, 1.
2. .
, 1 2 . ,
, !
, 10000, ,
:
494 9498 8
, :
0 3 997
, .
, ,
, . ,
Thread.sleep().
, .
Java
.
(main storage),
.
, . ,
, .
(working memory),
.
, :
use ;
assign ;
read ;
load , , ;
store
;
write , store.
, - ,
. .
, , use assign
. ,
. .
read, load.
, .. , .
184
store,
write. , ..
, .
,
, ,
(, , ..).
:
, , , .. ;
, , , ..
.
, . ,
, ,
.
.
, .
, , .
volatile
volatile.
.
use volatile , ,
load, load use.
, .
, store volatile , ,
assign, assign
, store. ,
.
, volatile ,
.
. ,
,
, .
64- , double long.
32- ,
. ,
, . volatile
.
(lock),
(lock) (unlock).
. , unlock,
, , .
lock unlock .
lock
. , unlock
.
185
, - . ,
, , , .
, , ,
, unlock.
Java- , ,
synchronized. synchronized-
. .
Synchronized- :
synchronized (ref) {
...
}
, , , ,
ref ( null).
, ,
lock.
. ( , )
unlock, .
:
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() {
186
synchronized (shared) {
shared.process();
}
:
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() {
public void run() {
//
synchronized(two) {
Thread.yield();
//
synchronized (one) {
System.out.println("Success!");
}
}
}
};
//
187
t1.start();
t2.start();
}
12.4.
, .
yield() . ,
, . , "",
. , .
" ", deadlock.
, .
, . (
yield()) (
), ( ""), (-
), .
Java deadlock.
, .
, . ,
(
, ) .
. , , sleep(..),
,
, deadlock.
,
.
wait(), notify(), notifyAll() Object
, Object,
Java.
Java synchronized , waitset, . 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);
188
} catch (InterruptedException e) {}
System.out.println("before notify");
synchronized (o) {
o.notifyAll();
}
}
}
:
before notify
after wait
189
. 1 synchronized-, ,
shared. , , 2 synchronized, 3. , , "" 1
2?
, , wait(),
. , notifyAll(). , wait-set
. ,
, synchronized-!
, notifyAll() .
. synchronized- ,
, . - ,
wait(), notifyAll().
.
, wait() , -,
. .
13: java.lang
java.lang , ,
, Java API. ,
(import java.lang.*;).
, .
Object .
Class JVM.
String , .
StringBuffer () .
Number , -
Java.
Character char.
Boolean boolean.
Math .
Throwable , . ,
, , catch, Throwable.
Thread Java. Runnable
Thread .
ThreadGroup .
.
System .
Runtime , .
Process , Runtime.
ClassLoader JVM.
190
SecurityManager .
Compiler Just-in-Time .
:
Cloneable , JVM;
Comparable (, ) ,
.
Object
Object . ,
Java.
public final native Class getClass() Class, .
4.
public boolean equals(Object obj) , . ==
( ), equals()
( ). Object ,
, true , :
public boolean equals(Object obj) {
return (this == obj);
}
- ,
(, , ).
- ( Integer). true,
int , , .
equals() (, false, , ,
true) , , .
, , ,
:
:
package demo.lang;
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))||
191
(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));
}
}
13.1.
, , :
r1.equals(r1) == true
r1.equals(r2) == false
r1.equals(r3) == true
r2.equals(r3) == false
r1.equals(null) == false
13.2.
equals() Rectangle ,
, ( ).
, .
public int hashCode() - (hash code) . - ,
.
( Java
).
, :
, equals(Object) true,
hashCode() ;
hashCode()
, ,
equals().
, .
Object JVM. -,
. ( )
-.
equals()
hashCode(). , -, , ,
. -, ,
equals(Object) false, -. -
. , , . int 232,
, , int .
, .
public String toString() . Object
:
public String toString() {
return getClass().getName() + "@" +
Integer.toHexString(hashCode());
}
, - .
192
- .
, . ,
, :
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) {
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 )
. String
(this).
wait(), notify(), notifyAll()
12. final -.
protected void finalize() throws Throwable Java- , garbage collector (
) , . 4.
protected native Object clone() throws CloneNotSupportedException .
9.
Class
Java Class. ,
, ..
Class Java-
class-. Class
forName():
public static Class forName(String name, boolean initialize, ClassLoader loader) Class,
, , , name (
), . loader
null, ClassLoader, .
, initialize true .
forName(), : public static Class
forName(String className),
( ).
public Object newInstance() ,
Class. . ,
InstantiationException. , Class
, , - .
193
, , ,
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 class for: " + name);
Class aClass = Class.forName(name);
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);
} catch(InstantiationException e) {
System.out.println("Exception: " + e);
}
}
}
}
13.3.
, :
look for class for: demo.lang.Automobile
creating vehicle...
create vehicle: class demo.lang.Automobile
Automobile go!
look for class for: demo.lang.Truck
creating vehicle...
Instantiation exception: java.lang.InstantiationException
look for class for: demo.lang.Tank
Class not found: java.lang.ClassNotFoundException: demo.lang.Tank
13.4.
reflection . ,
, vehicleNames. Automobile , ,
Vehicle. Truck ,
, java.lang.InstantiationException,
. java.lang.Tank
Class java.lang.ClassNotFoundException.
-
194
, . , ,
.
-. Java
-. ( , ,
), final . -
( Void) Serializable, ( Void) -
. - TYPE, Class,
.
-
, , .
13.1 -.
13.1. -.
-
Byte
byte
Short
short
Character
char
Integer
int
Long
long
Float
float
Double
double
Boolean
boolean
NumberFormatException, , ,
.
:
public static Integer valueOf(String s)
public static Integer valueOf(String s,
int radix)
, -.
Integer:
195
Integer(String s) , ,
.
Integer(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());
}
- .
:
while i==b is true
iObj.equals(bObj) is false
lObj = 1000
The sum = 1002.0
- Float Double,
, ( 4):
196
NEGATIVE_INFINITY ;
POSITIVE_INFINITY ;
NaN .
, MIN_VALUE
( > 0) , .
- ,
Java.
Character
Comparable Serializable.
, char .
equals(), hashCode(), toString(), :
Character ,
. - , char . :
public static boolean isDigit(char c)
// , char .
, , .
Boolean
- boolean.
java.io.Serializable -.
booleanValue().
Void
-, , java.io.Serializable.
. , .
Class, void. TYPE.
-, , :
197
-;
- ,
String, Character, char;
- equals();
-
xxxxValue() ( intValue());
- -, ..
;
- .
Math
Math ,
, , ,
. - (Utility class). ,
, .
, final.
, :
13.2 .
13.2. Math .
abs( a)
double
acos(double a)
double
asin(double a)
double
atan(double a)
double
ceil(double a)
, a
double
floor(double a)
, a
double
IEEEremainder (double a,
double b)
IEEE 754 (
3)
double
sin(double a)
( : )
double
cos(double a)
double
tan(double a)
double
exp(double a)
e a
double
log(double a)
max( a, b)
min( a, b)
double
pow(double a, double b)
a b
double
random()
0.0 1.0
double
rint(double a)
int, a
round( a)
double
sqrt(double a)
double
toDegrees(double a)
double
toRadians(double a)
String
Java . .
, .
String. ,
, :
String abc = "abc";
. ,
.
String s = new String("immutable");
198
, . ,
. :
public class Test {
public Test() {
}
:
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
? ,
Java. ,
.
, .
String , .
, ,
, .
String. .
, , . equals, wait/notify.
.
JVM
. .
Java +. .
String :
public String concat(String s);
-, s.
199
.
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
, ( String, s),
. . trim (
) concat - s . , , .
, Unicode-.
(/, ..).
:
byte[] getBytes() , (
, );
byte[] getBytes(String encoding) encoding.
( ) :
String(byte[] bytes) , ;
String(byte[] bytes, String enc) .
StringBuffer
,
String. char[], , String,
.
StringBuffer:
StringBuffer() StringBuffer;
StringBuffer(String s) s;
StringBuffer(int capacity) StringBuffer ( char[]).
, ,
. ,
.
String StringBuffer :
200
sb.append("-aaa");
System.out.println(s);
System.out.println(sb);
}
:
ssssss
bbbbbb-aaa
, String , StringBuffer .
, StringBuffer, :
, ,
Java String.
( String.valueOf()).
, , , .
, . :
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("abc");
String str = sb.append("e").insert(4,
"f").insert(3,"d").toString();
System.out.println(str);
}
:
abcdef
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.
201
, , JVM
:
ClassLoader ; JVM;
SecurityManager ;
;
System ;
Runtime ;
Process ,
Runtime.
ClassLoader
, .
, . :
class-, .
Class ClassLoader, .
,
ClassLoader. , . defineClass()
Class. newInstance()
. Java.
, ,
:
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() Class. ,
.
, ,
loadClass():
try {
ClassLoader loader =
new NetworkClassLoader(host, port);
Object main = loader.loadClass(
"Main").newInstance();
} catch(ClassNotFoundException e) {
e.printStackTrace();
} catch(InstantiationException e) {
202
e.printStackTrace();
} catch(IllegalAccessException e) {
e.printStackTrace();
}
, ClassNotFoundException, ,
-
InstantiationException, , ,
( ),
IllegalAccessException.
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().
, , ,
SecurityManager . ,
. (, ,
), (
SecurityException). , ,
..
System
System .
.
, , System, ,
System.out. PrintStream (
15). (, .., ,
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();
}
}
203
Study Java
"d:\file2.txt"
Study well
System.in System.setIn(InputStream)
System.err System.setErr(PrintStream) ( in, out,
err ).
System :
, , :
arrayCopy(Object source, int srcPos, Object target, int trgPos, int length)
. ,
, . -"",
, . ,
, . ,
, .
Runtime
Java Runtime.
, Java-.
Runtime.getRuntime().
:
: , native ,
, :
static { System.loadLibrary("LibFile"); }
204
, , native
. ,
, .
Process
exec() Runtime, .
Process .
Process , ,
. Process:
Java Process,
. ,
Process Java.
, Java-
.
Java 12.
.
Runnable
Runnable , - : run().
Thread
.
, Thread :
205
. , ,
millis .
, deprecated . : suspend()
, resume() ( suspend()),
stop() .
stop() , Thread, ThreadDeath.
Error. , ,
, ,
. (,
- ), ,
, . ThreadDeath
Error, Exception,
Exception, .
Thread , :
Name String,
;
Daemon ,
daemon ;
Priority . Thread ,
, MIN_PRIORITY MAX_PRIORITY,
NORM_PRIORITY.
, , start()
Thread.
, , ,
. , :
isAlive() , isInterrupted() .
ThreadGroup
, ,
. , .
ThreadGroup.
. ,
, ThreadGroup, ,
.
ThreadGroup , , ,
daemon .. list() .
10. ,
Throwable. ,
, . Throwable,
Error, Exception, RuntimeException, java.lang.
206
14: java.util
Date
Date - ,
..
Calendar.
Date, :
Date() Date(long date)
207
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.
Calendar GregorianCalendar
Calendar. Calendar
. .
- GregorianCalendar.
getInstance(), GregorianCalendar.
Calendar Date -.
, .
Calendar , "" , ..
, , ..
,
, ..
YEAR = 1970, MONTH = JANUARY, DATE = 1 ..
"" get(int field), set(int field, int value),
add(int field, int amount), roll(int field, int amount), int field ,
. Calendar
int.
.
set(int field,int value).
, - .
.
get(), getTime() getTimeInMillis(). ,
. , .
. , .
. set,
:
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);
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()));
}
}
14.1.
208
:
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
14.2.
,
. 30 , 1 ,
30 , .
, , , :
public class Test {
public Test() {
}
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMMM dd HH:mm:ss");
14.3.
:
Initialy set date: 2002 August 31 23:03:51
Date with day and month changed: 2002 September 30 23:03:51
14.4.
add(int field,int delta).
. ,
set(f, get(f) + delta).
add :
1.
2.
,
, .
, ,
, , "".
209
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()));
}
14.5.
:
Current date: 2002 August 31 19:30:00
Rule 1: 2002 August 31 19:31:15
Rule 2: 2002 September 30 19:31:15
14.6.
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()));
}
14.7.
:
Current date: 2002 August 31 19:30:00
Rule 1: 2002 August 31 19:30:15
Rule 2: 2002 September 30 19:30:15
14.8.
, 1
add, 2 .
TimeZone
TimeZone Calendar DateFormat.
, . getDefault(),
210
TimeZone , ,
JVM. , ,
getTimeZone(String ID),
, TimeZone. ,
getTimeZone, . String[]
getAvailableIds(), getTimeZone.
( ) String[]
getAvailableIds(int offset).
, :
;
;
, .
14.9.
:
Current TimeZone Moscow Standard TimeEurope/Moscow
TimeZones same as for Moscow
Eastern African TimeAfrica/Addis_Aba raw offset=10800000;hour offset=(3)
Eastern African TimeAfrica/Asmera raw offset=10800000;hour offset=(3)
Eastern African TimeAfrica/Dar_es_Sa raw offset=10800000;hour offset=(3)
Eastern African TimeAfrica/Djibouti raw offset=10800000;hour offset=(3)
Eastern African TimeAfrica/Kampala raw offset=10800000;hour offset=(3)
Eastern African TimeAfrica/Khartoum raw offset=10800000;hour offset=(3)
Eastern African TimeAfrica/Mogadishu raw offset=10800000;hour offset=(3)
Eastern African TimeAfrica/Nairobi raw offset=10800000;hour offset=(3)
211
14.10.
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 - ( ).
. 2 ,
- 3 .
:
212
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;
}
}
14.11.
:
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]
14.12.
Observer Observable
Observer , update (Observable o, Object arg), ,
.
Observable MVC (model-view-controller),
, , .
, , - .
. ,
Observer.
213
, - , 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 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");
}
}
14.13.
:
Called update of Observer 2 from Observable with argument Notify argument
Called update of Observer 1 from Observable with argument Notify argument
14.14.
Observer , Java
Observer . ,
, , Observer, .
214
,
(, ). . ,
, , . ,
().
.
Java . ,
: Hashtable Vector. JDK 1.2 ,
, .
-. , ,
, ,
. ,
, . , (
), , - .
, - . .
, , java.util.
Collection
-.
- , , , . ,
Collection, (null) .
AbstractCollection, ,
, Collection.
Set
, , .
null. Set Collection, ,
, Set, , Collection. ,
Set, equals, .
AbstractSet, ,
Set.
List
, , (
, ). JDK 1.2 Vector, ,
List. List Collection, , List,
, Collection, ,
. List ListIterator, ,
.
AbstractList, ,
List.
215
. 14.1. .
Map
, , /.
. Hashtable JDK 1.2 Map.
/ .
Map Collection. AbstractMap, ,
Map.
SortedSet
Set, , .
, Comparable,
Comparator.
216
SortedMap
Map, , .
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
A ,
java.util.AbstractCollection - , Collection,
iterator size, , ,
. public void
add(Object o) ( UnsupportedOperationException).
217
. 14.2. .
: Collection.
, - .
AbstractList AbstractSet.
java.util.AbstractList - AbstractCollection List.
public Object get(int index) public int size().
public void set(int index,Object element)
( UnsupportedOperationException).
AbstractCollection, iterator,
get, set, add, remove.
java.util.AbstractSet - AbstractCollection ,
Set. , ,
AbstractCollection.
java.util.AbstractMap - , Map.
, AbstractMap, entrySet,
218
, AbstractSet. (Set)
. Map
put , entrySet().iterator(),
remove.
java.util.AbstractSequentialList - AbstractList LinkedList.
AbstractList , ,
, get(int index), set(int index, Object element), add(int
index, Object element) remove(int index). , ,
listIterator size. , ,
hasNext, next, hasPrevious, previous index.
set, add, remove.
java.util.ArrayList - AbstractList Vector.
, Vector, ,
. , ArrayList,
:
List l = Collections.synchronizedList(new ArrayList(...));
public class Test {
public Test() {
}
public static void main(String[] args) {
Test t = new Test();
ArrayList al = new ArrayList();
al.add("First 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());
}
}
}
14.15.
:
First element
Second element
Third element
Firts element
Second element
Insertion
Third element
14.16.
java.util.LinkedList - List. List,
, ,
. LinkedList ,
. LinkedList .
public class Test {
public Test() {
}
219
14.17.
:
Element3
Element2
Element1
Element4
Element3
Element2
Element4
Element3
Element2
14.18.
LinkedList ArrayList .
. , ArrayList ( )
() . LinkedList
.
java.util.Hashtable - Dictionary. JDK 1.2 Hashtable
Map. Hashtable /. ,
Hshtable . ,
, .
, , . , ,
, ,
, , , .
.
, , , .
Java Object. , hash ,
Object , , ,
Object. hashCode(). Hashtable
: , , ,
, array.length % hashCode().
, /, ,
, , .
,
220
. , ,
, .
, ,
. , . ,
,
, . , .
, ( ) ,
. ,
, ,
. , ,
, ,
.
. :
Hashtable ht = new Hashtable(1000,0.60)
, 101
( 11) 0.75 .
,
, . , -
, .
java.util.HashMap - AbstractMap Hashtable. HashMap
/. , null.
.
. HashMap get
put.
.
, .
HashMap . ,
, ,
.
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() +
221
14.19.
:
Object value for Key1 = Value 1
Iteration over entrySet
For key = Key3 value = Value 3
For key = Key2 value = Value 2
For key = Key1 value = Value 1
Iteration over keySet
For key = Key3 value = Value 3
For key = Key2 value = Value 2
For key = Key1 value = Value 1
14.20.
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"));
}
:
String1
String2
Collections
Collections -
, . , ,
.. , ,
-. ,
Map :
222
14.21.
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.
223
, . , ,
! #, , .. .
/, . ,
, . ,
.
, \. , ,
.
. , \t, \n, \r, \\, \", \', \ \uxxxx,
. \ ,
, .
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 = Value1 \n");
sw.write(" Key2 : Value2 \r\n");
sw.write(" Key3 Value3 \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);
}
14.22.
:
-- listing properties -Key3=Value3
Key2=Value2
Key1=Value1
-- listing properties -Key4=Added Value4
Key3=Value3
Key2=Value2
Key1=Modified Value1
14.23.
Comparator
224
, Comparator.
compare(Object obj1,Object obj2),
, . compare :
-1 obj1 < obj2
0 obj1 = obj2
1 obj1 > obj2
Arrays
Arrays , , ,
, . Arrays public List aList(a[] arr),
, . List ,
.
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]);
}
}
}
StringTokenizer
(tokens). , ,
StringTokenizer(String str).
, - StringTokenizer(String str, String
delim) StringTokenizer(String str, String delim, Boolean returnDelims).
.
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
225
word3
word4
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();
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.
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();
226
}
void dumpArray(byte[] arr) {
for(int cnt=0;cnt< arr.length;cnt++) {
System.out.print(arr[cnt]);
}
System.out.println();
}
}
14.24.
:
-1193959466 -1139614796 837415749 -1220615319 -1429538713 118249332 -951589224 -1193959466
-1139614796 837415749 -1220615319 -1429538713 118249332 -951589224 81;-6;-107;77;118;17;93;
-98;
14.25.
Locale
Locale .
, . , ,
, - .
Locale:
Locale(String language, String country)
Locale(String language, String country,
String variant)
, ,
ISO.
Locale.getISOLanguages() Locale.getISOCountries(), .
variant, .
, , ,
.
:
Locale l = new Locale("ru","RU");
Locale l = new Locale("en","US","WINDOWS");
getDefault() ,
, JVM.
. , Locale.US Locale.GERMAN.
227
Locale ,
.
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());
}
}
14.26.
:
US United States USA
en English eng
RU Russia RUS
ru Russian rus
WINDOWS WINDOWS
14.27.
ResourceBundle
ResourceBundle , . ,
, , ResourceBundle.
ResourceBundle ,
. , ,
, ..
- , .
, . ,
MyResources, MyResources_en, - MyResources_ru.
, , .
, MyResources_de_CH - . ,
variant (. Locale). , UNIX
: MyResources_de_CH_UNIX .
getBundle.:
ResourceBundle myResources =
ResourceBundle.getBundle("MyResources",
someLocale);
( ), ( )
( JVM) . ,
, .
(, , ) 1, - 2, :
baseclass + "_" + language1 + "_" + country1 + "_" + variant1
228
14.28.
, 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()
protected 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.util.MissingResourceException {
return res.get(key);
}
}
public class MyResource_ru_RU extends ResourceBundle {
private Hashtable res = null;
229
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"));
}
}
14.29.
:
English Variant
, , ResourceBundle .
, , ,
.
public interface Behavior {
public String getBehavior();
public String getCapital();
}
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();
}
230
14.30.
:
14.31.
ListResourceBundle PropertiesResourceBundle
231
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() {
}
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());
}
}
}
14.32.
:
Element 1
Element 2
Element 3
, , ,
ResourceBundle.
232
15: java.io
/. (stream)
. , ,
,
. ,
. , ,
, - . , ,
, , ,
.. , ,
, .. ,
.
, ,
/. Java java.io (input/output). /
,
. , ,
( 4 ),
. (,
HTML-), ( ).
.
Java / (stream).
, , ,
. ,
() . stream ,
,
/.
Java .
java.io. .
, .
. ""
, , , 0 1 (
, ; , 1
, 0 ).
, 8 . , , , 0
28-1=255, , , -128 +127. byte Java
.
, ,
. , java.io ,
.
, double ,
, .
, (.. )
. ,
, .
15.1 /. ,
. InputStream, OutputStream.
233
. 15.1. /.
InputStream OutputStream
InputStream , .. . ,
. , InputStream.
read() ( ). , ,
-.
, int. , ,
0 255 ( int
4 ). ,
-128 +127,
byte Java.
, ,
-1.
- - , ,
java.io.IOException. Exception, .. . ,
, Internet , , ,
, . , ,
.
read() ,
-.
, .
read(), byte[].
read() ( )
. , , .
, , .
, () , .
234
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,
, , , -.
write() . ,
, byte[] int- .
, , ,
, ,
IndexOutOfBoundsException.
, , .
, - , 10 , 200
. 200 ,
2000 .
( ) . ,
, , flush(), OutputStream.
, - ,
.
, . close().
( flush),
. .
OutputStream close() .
, InputStream OutputStream
. . ,
. , , , ,
.. , , , , .
-
ByteArrayInputStream ByteArrayOutputStream
, , , , .
ByteArrayInputStream , . ,
byte[]. , read()
. :
235
236
15.1.
:
: 3
: 3
: 3
1,2,3,
15.2.
FileInputStream available() , ,
. ,
, available() ,
. , , , ,
.
. finally .
...
} finally {
try{inFile.close();}catch(IOException e){};
}
, .
237
PipedInputStream PipedOutputStream
PipedInputStream PipedOutputStream ,
PipedInputStream () PipedOutputStream.
, (,
).
: PipedInputStream PipedOutputStream,
. PipedOutputStream
PipedInputStream, . PipedOutputStream ,
PipedInputStream.
connect() PipedI/OStream (
, PipedInputStream PipedOutputStream),
.
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) {
System.out.println ("Impossible IOException occur: ");
e.printStackTrace();
}
15.3.
( toRead
). PipedI/OStream
. ,
. PipedI/OStream,
. ,
, :
// inStream - PipedInputStream
try {
while(true) {
byte[] readedBytes = null;
synchronized(inStream) {
int bytesAvailable = inStream.available();
readedBytes = new byte[bytesAvailable];
inStream.read(readedBytes);
}
// readedBytes
//
} catch(IOException e) {
/* IOException , inStream,
238
PipedOutputStream, ,
inStream */
System.out.println(" inStream ");
}
15.4.
inStream ,
synchronized ( ), ,
inStream.available() inStream.read()
inStream. inStream.read(readedBytes) ,
, .
StringBufferInputStream
String .
StringBufferInputStream.
String. , read(), .
(, char
).
SequenceInputStream
SequenceInputStream .
, , .
SequenceInputStream , ,
.
Enumeration ( ,
, InputStream ). read(),
SequenceInputStream .
( -1), close()
. , .
, , SequenceInputStream -1.
close() SequenceInputStream .
:
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){};
}
15.5.
file3.txt file1.txt file2.txt
file1.txt, file2.txt. finally.
close() IOException, try-catch . , close()
239
try-catch - ,
. inFile1 inFile2
sequnceStream - ,
sequenceStream close().
SequenceInputStream : Enumeration,
, SequenceInputStream:
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 en = vector.elements();
sequenceStream = new SequenceInputStream(en);
15.6.
sequenceStream , file3.txt,
file1.txt file2.txt, ,
file1.txt file2.txt file3.txt.
FilterInputStream FilterOutputStream
, / - ,
, , ..
.
( )
. ,
/. java.io .
- , , ,
, .
java.io / FilterInputStream (
) FilterOutputStream ( ).
/ InputStream OutputStream, . FilterInputStream
InputStream protected.
FilterI/OStream
. - . ()
.
BufferedInputStream BufferedOutputStream
.
BufferedInputStream BufferedOutputStream.
BufferedInputStream , .
( skip()), , ,
,
read skip. BufferedInputStream mark() reset().
InputStream,
IOException. mark() , reset() ,
, mark(), , ,
.
BufferedOutputStream
. .
, , , ,
. ,
flush(). .
( BufferedInputStream).
:
240
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 time: " + 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 time: " + (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 time: " + (time) + " millisec");
} catch (IOException e) {
System.out.println("IOException: " + e.toString());
e.printStackTrace();
}
15.7.
, , :
Writing time: 359 millisec
Direct read time: 6546 millisec
Buffered read time: 250 millisec
15.8.
, ,
. 10 (!) ,
.
, , ,
BufferedOutputStream.
BufferedI/OStream ,
.
.
LineNumberInputStream
LineNumberInputStream , .
, , getLineNumber().
setLineNumber(int lineNumber).
241
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
DataOutputStream outData = new DataOutputStream(out);
outData.writeByte(128);
// int,
//
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(" : ");
System.out.println("readByte: " + inData.readByte());
System.out.println("readInt: " + inData.readInt());
System.out.println("readLong: " + inData.readLong());
System.out.println("readDouble: " + inData.readDouble());
inData.close();
System.out.println(" :");
242
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();
}
15.9.
:
:
readByte: -128
readInt: 128
readLong: 128
readDouble: 128.0
:
readInt: -2147483648
readDouble: -0.0
readLong: -9205252085229027328
, .
(serialization)
, ..
- (serialization), ,
.
, ,
.., , ,
. , Java , , ,
- .
, (enterprise)
.
DataInput
DataOutput ObjectInput ObjectOutput, . java.io
ObjectInputStream ObjectOutputStream.
, JVM. ,
, , , java.io.Serializable.
. ,
. , ,
java.io.NotSerializableException.
, OutputStream,
. ObjectOutputStream.
writeObject() . :
ByteArrayOutputStream os =
new ByteArrayOutputStream();
Object objSave = new Integer(1);
ObjectOutputStream oos =
243
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
, (
), .
, . , ()
, .
, readObject() ObjectInputStream.
, TestClass
. , JVM
( TestClass.class).
, .
ClassNotFoundException.
java.io.StreamCorruptedException
. , .
( ),
. ,
( read) InputStream.
ObjectInputStream
java.io.StreamCorruptedException.
ObjectOutput DataOutput, ObjectOutputStream
,
. readObject,
, java.io.OptionalDataException. ,
,
.
, . Java
. , , ,
, , .
, .
, . DataOutput
244
( , ).
(,
private). , , , ,
. ?
, . ,
. , ,
, , , , . ?
?
.
set- . ,
. ? ,
? , .
?
-, Serializable. , Object
. , Serializable, . . Serializable,
, , ,
, .
Serializable ,
.
,
, Serializable.
:
// , Serializable
public class Parent {
public String firstName;
private String lastName;
public Parent(){
System.out.println("Create Parent");
firstName="old_first";
lastName="old_last";
}
public void changeNames() {
firstName="new_first";
lastName="new_last";
}
public String toString() {
return super.toString()+",first="+firstName+",last="+lastName;
}
}
// Child, Serializable
public class Child extends Parent implements Serializable {
private int age;
public Child(int age) {
System.out.println("Create Child");
this.age=age;
}
public String toString() {
return super.toString()+",age="+age;
}
}
// Serializable-
public class Child2 extends Child {
private int size;
public Child2(int age, int size) {
super(age);
System.out.println("Create Child2");
this.size=size;
}
public String toString() {
return super.toString()+",size="+size;
}
}
//
245
15.10.
3 . Parent Serializable , ,
. 2 , , "old"
(""). , , . ,
"new" ("). toString(),
.
Parent ,
Serializable. , Child .
toString().
, Child2 Child, .
, , toString().
Test output.bin . ,
changeNames(), ,
Parent.
:
Create Parent
Create Child
Child@ad3ba4,first=new_first,last=new_last,age=2
Create Parent
Create Child
Create Child2
Read objects:
Create Parent
Child@723d7c,first=old_first,last=old_last,age=2
Create Parent
Child2@22c95b,first=old_first,last=old_last,age=3,size=4
15.11.
, . ,
. , , Serializable-,
. -Serializable.
, . , Serializable- (firstName, lastName), . ,
Parent . , Serializable-, .
246
Child2 Child ,
. , .
, . .
, ( ) .
,
.
, ,
- . , , ,
.
, , , .
, , .
transient. ,
:
class Account implements
java.io.Serializable {
private String name;
private String login;
private transient String password;
/*
...
*/
}
password
( null).
. , ,
. static-,
JVM.
, .
, ( ),
. , , . ,
,
, . ,
A B C, , , D.
, B D1, C D2, D1 D2 ,
.
,
. ,
. .
.
, , Serializable.
, java.io.NotSerializableException.
:
import java.io.*;
class Point implements Serializable {
double x;
double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public String toString() {
return "("+x+","+y+") reference="+super.toString();
}
247
}
class Line implements 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{
//
FileOutputStream os = new FileOutputStream(fileName);
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(line1);
oos.writeObject(line2);
// line1
line1.setIndex(3);
//oos.reset();
oos.writeObject(line1);
//
// -
oos.close();
//
System.out.println("Read objects:");
FileInputStream is = new FileInputStream(fileName);
ObjectInputStream ois = new ObjectInputStream(is);
for (int i=0; i<3; i++) { // 3
Line line = (Line)ois.readObject();
line.printInfo();
} ois.close();
} catch(ClassNotFoundException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
}
}
15.12.
Line (), 2 Point (
). Main Line, , .
, ( index). ( 1 2) ,
(3) .
:
248
Constructing line: 1
Constructing line: 2
line 1 = Line@7d39
line 2 = Line@4ec
Read objects:
Line: 1
Object reference: Line@331e
from point (1.0,1.0) reference=Point@36bb
to point (2.0,2.0) reference=Point@386e
Line: 2
Object reference: Line@6706
from point (2.0,2.0) reference=Point@386e
to point (3.0,3.0) reference=Point@68ae
Line: 1
Object reference: Line@331e
from point (1.0,1.0) reference=Point@36bb
to point (2.0,2.0) reference=Point@386e
15.13.
, ,
(- 386e).
, , . ,
index 3, 1.
, , , ,
, .
, , ,
ObjectOutputStream reset().
//oos.reset();
, , 3.
Constructing line: 1
Constructing line: 2
line 1 = Line@ea2dfe
line 2 = Line@7182c1
Read objects:
Line: 1
Object reference: Line@a981ca
from point (1.0,1.0) reference=Point@1503a3
to point (2.0,2.0) reference=Point@a1c887
Line: 2
Object reference: Line@743399
from point (2.0,2.0) reference=Point@a1c887
to point (3.0,3.0) reference=Point@e7b241
Line: 3
Object reference: Line@67d940
from point (1.0,1.0) reference=Point@e83912
to point (2.0,2.0) reference=Point@fae3c6
15.14.
, . ,
. ,
.
.
:
249
250
15.1 .
15.1. .
InputStream
Reader
OutputStream
Writer
ByteArrayInputStream
CharArrayReader
ByteArrayOutputStream
CharArrayWriter
InputStreamReader
OutputStreamWriter
FileInputStream
FileReader
251
FileOutputStream
FileWriter
FilterInputStream
FilterReader
FilterOutputStream
FilterWriter
BufferedInputStream
BufferedReader
BufferedOutputStream
BufferedWriter
PrintStream
PrintWriter
DataInputStream
DataOutputStream
ObjectInputStream
ObjectOutputStream
PipedInputStream
PipedReader
PipedOutputStream
PipedWriter
StringBufferInputStream
StringReader
StringWriter
LineNumberInputStream
LineNumberReader
PushBackInputStream
PushBackReader
SequenceInputStream
, .
, , Java
(DataInput/Output, ObjectInput/Output). -,
: InputStreamReader OutputStreamWriter . FileReader FileWriter.
available() InputStream Reader , ready(),
, ( ).
252
. ,
:
String fileName = "d:\\file.txt";
//,
String data = "Some data to be written and read.\n";
try{
FileWriter fw = new FileWriter(fileName);
BufferedWriter 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();
//
FileReader fr = new FileReader(fileName);
BufferedReader 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();
}
15.15.
- InputStreamReader OutputStreamWriter
. , .
, UnsupportedEncodingException.
( !)
: "Cp1251", "UTF-8", "8859_1" ..
StreamTokenizer
StreamTokenizer , InputStream, Reader.
java.util.StringTokenizer, (token),
. , , InputStream,
deprecated ( InputStreamReader
). , StringTokenizer, ,
nextToken(), .
StreamTokenizer , , .
File
, File
, .
File .
, , .
, exists, true, .
File .
FileI/OStream.
File ( isDirectory). list
( String) ( File
null).
253
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();
}
System.out.println("work finished");
}
}
15.16.
( ) ,
.java, .
, .java, FileFilter
NameFilter. FileFilter accept, ,
, . ,
FilenameFilter, accept :
, File, , ,
. , ,
accept.
FileFilter FilenameFilter. list File
.
File .
254
setReadOnly, setLastModified,
. , createNewFile, mkDir,
mkDirs. , createNewFile ( ), mkDir
, , mkDirs
.
delete deleteOnExit. delete
, deleteOnExit Java- (
) .
, File .
RandomAccessFile
DataInput DataOutput ,
Java. , , .
,
seek(long) ( ).
getFilePointer.
:
. , , String ,
File, . (mode) "r"(
), "rw"( ).
FileNotFoundException. (
FileNotFoundException, ).
RandomAccessFile DataInput DataOutput
. ,
close.
16:
OSI
255
. 80-
.
, .
(,
).
(International Organization for
Standardization, ISO) ,
. 1984 .
OSI (Open Systems Interconnected).
, .
16.1.
16.1. OSI.
Layer 7
(data)
Layer 6
(data)
Layer 5
(data)
Layer 4
(segment)
Layer 3
(packet)
Layer 2
(frame)
Layer 1
(bit)
,
.
.
7 (), .
,
(, , , ,
). , ,
"" (layer 6). ,
7 , 6 ( 6
7).
, , ,
(6-) .
"" , .
.. (
.16.1). ,
(, 3- , .16.2). ,
.
256
. 16.1. .
. 16.2. .
"" (encapsulation).
. ,
0 1. , ,
, 010110101.
, (0 - , 1 - ).
.
/ /.
257
(.16.3).
, , (decapsulation).
. (
1- ) ,
, .
(2-)
. , ,
.
. 16.3. .
web-.
web-. 7
OSI. ,
"" . ()
.
, web-. ,
.
, , .
OSI ,
. web-
Sun Solaris HTML- MS Windows.
, .
, ,
. - - .
, -. , Ethernet
ATM .
,
. , Token Ring Ethernet
.
- - .
.
.
(message) ISO
(Protocol Data Unit, PDU). ,
, . , TCP/IP TCP
, UDP ( , datagram),
IP . .
.
Physical layer (layer 1)
OSI, (Physical layer) .
. ,
(, ..) .
.
258
( ,
, , ). .
:
;
;
;
.
.
.
, , ,
, .
. ,
, Internet .
, ..
, .
, "".
( "", , ),
.
.
, .
. (
75 , 50 ).
( 10 /),
. , ,
, . ,
,
.
("twisted pair") .
,
, , .
. . Cat 3 1991
., 16 ,
. Cat 5,
. 100.
10, 100, 1000 /. Cat5
Cat 3.
. Cat 5 ,
, ( 10 100 100 1000 /).
, ,
, , .
() ,
, , . ,
, .
.
:
;
.
"" .
, .
, .
, .
. :
, .
, ,
.
259
.
, , ,
( ).
(Network adapter),
, . (
) ISA PCI
(, , ..).
, , ,
, , , ( ).
"" (bus) . 16.4.
260
, .
"" . 16.6.
261
"", .
, , , "".
Data layer (layer 2)
. ,
, (, ),
, , ,
. Data layer ( ) .
. Data layer :
LLC .
MAC Physical layer.
.
LLC sublayer
.
() . LLC
,
MAC. , Ethernet, Token Ring, Frame Relay.
MAC sublayer
.
.
, , MAC-.
) . MAC- 48 ,
6 ( 8 ), . 3
OUI (Organizational Unique Identifier), .
IEEE (Institute of Electrical
and Electronic Engineers, ,
). 3 .
, . ,
.
, : 00:00:B4:90:4C:8C, 00-00-B4-90-4C-8C,
0000.B490.4C8C . , ,
0000.1c12.3456. 0000.1 , 12.3456 .
MAC- Ethernet. , ,
CSMA/CD (carrier sense
multiple access/collision detect, ).
, (, ),
. , ,
. CSMA/CD ,
(collision), , .
, .
Data layer.
. MAC- MAC-
. Ethernet
, .
, , , . MAC-,
, MAC-, , ,
262
.
, .
, .
MAC- FF-FF-FF-FF-FF-FF.
(broadcast), .
, .
("bus") ,
Ethernet. (,
; ,
, ).
("ring") Token Ring.
, . ,
Ethernet, .
. (token).
, .
, , ,
. , , . , ,
. , .
"" , ,
, " ". ,
(hub).
" ".
, . , ,
, -. Ethernet
CSMA/CD. ,
"" ( , ).
. ,
10 /, 2 /.
, (switch). ,
, , MAC-
. ,
, .
. , ,
, .
, , , . ,
, ,
, , .
. , ,
(Local area network, LAN).
Network layer (layer 3)
OSI.
"" . ,
MAC-, broadcast-. ,
,
.
. . ,
+7-095-101-12-34 , /(095),
(101-12-34). . 101 ,
, 12-34 .
.
.
263
(Network layer) ,
. IP. , IPX,
, , .
, 3- , (router), .
(LAN), (Wide area network, WAN).
.
, LAN,
. , .
, , , ,
, (, Ethernet).
LAN, .
, .
,
. hop ( ,
). , ,
, , ..
, ,