Professional Documents
Culture Documents
CC++
1) 1991
1991
James Gosling, , Oak -> Java
2) 1993:
1993 ,
Java
Java:
1)
2)
3)
(
()
)
Java
Java C/C++
1.
2
2.
3.
4.
5.
6.
7.
8.
Java
(Application)
(Applet)
, :
JavaTM 2 SDK, Standard Edition
J2SE
: Java 2 SDK
jdk-6-doc.zip
:
http://java.sun.com/
: Java
1) J2SE
2) J2SEJ2SE
3)
(path)
(classpath)
4)J2SE
1: J_HelloJava.java()
// ///////////////////////////////////////////////////////////////////
// :
//
Java!
Java !
//
"Java!"
// ///////////////////////////////////////////////////////////////////
(: UltraEdit)
Java
// : J_HelloJava.java
J HelloJava java; :
public class J_HelloJava
{
public static void main(String args[ ])
{
System.out.println("Java!");
System.out.println("Java!");
} //
main
} // J_HelloJava
10
J_HelloJava.java
compilation unit
java
Java .java
(public)
(public)
11
&
J_HelloJava.java
javac
J_HelloJava.class
java
Java 12
".class
Java3
"/* */"
//
"/** */"
class
l
J_HelloJava
{}
13
2 : J_HelloApplet.java
Applet
Applet
java.applet.Applet javax.swing.JApplet
HTML
appletviewer ()
(IENetscape)
14
2 : J_HelloApplet.java
// ////////////////////////////////////////////////////////
// :
//
"!"
" !"
// ////////////////////////////////////////////////////////
15
(: UltraEdit)
Java
// : JJ_HelloJava.java;
e oJ v .j v ; :
import java.awt.Graphics;
import javax.swing.JApplet;
public class J_HelloApplet extends JApplet
{
public void paint(Graphics g)
{
g.clearRect(0, 0, getWidth( ), getHeight( )); //
g.drawString("!", 10, 20);
} // paint
} // J_HelloApplet
16
(: UltraEdit)
HTML
<!--------!
AppletExample.html
pp e
p e.
:
--------->
<HTML>
<HEAD>
<TITLE>
</TITLE>
</HEAD>
<BODY>
<APPLET CODE="J_HelloApplet.class" WIDTH=200 HEIGHT=40>
</APPLET>
</BODY>
</HTML>
17
&
J_HelloApplet.java
javac
J_HelloApplet.class
appletviewer/IE
18
Java
19
/*
This is a simple
p
Java p
program.
g
Call this file "Example.java".
*/
class Example {
// Your program begins with a call to main().
public static void main(String args[]) {
System out println("This is a simple Java
System.out.println("This
program.");
}
}
20
Java
.
: (1) , (2), (3)
(3)_
(4)$;
(1) ,
(2)
(2)_ (3)
$;
;
falsetruenull;
21
: / ?
myVariable
9pins
MYVARIABLE
i
a+c
testing1-2-3
g
_myvariable
java¨
My Variable
$myvariable
_9p
9pinss
It's
22
Java
public staticclass
23
Java(50)
24
25
26
Java
:
int studentNumber;
//
double velocity, distance; //
studentNumber=30; // 30
int studentNumber=30;//
27
:
int sum = 0;
String s = Hello
Hello World!
World!;;
sum
f789a1
Hello World!
28
Java
Java
(
(String)null
g)
(boolean)true false
c \u0061,
c,
\u0061 \u0051 \u005a
\u005a char.
char
34int
1.5, 45.6, 76.4E8-32.0double
34Llong.
g
1.5F, 45.6f, 76.4E8F-32.0Ffloat
Hello World!String
Hello
null
(null)
29
(char)()
'\b' ()
'\f' ()
'\n' ()
'\r' ()
'\t' ((tab))
'\' ' ()
'\" ' ()
'\\' (())
30
Java
1.
2.
3.
4.
5
5.
6.
7.
31
1
1.
+,
-, *,
* /,
/ ++, --, %
Math.pow(2.0, 3.0); // 2.03.0
7 / 5 1
7 % 5 2
32
-7 / 5
=
-7 % 5
=
7 % -55
=
5.5 % 1.0 =
-1
-2
2
0.5
33
2.
: < ><=>=== !=
:
// false
1 > 2;;
3.5 != 1;
// true
51 5 >= 23.0;
51.5
23 0;
// true
24 == 3*8;
// true
( < 10);
);
// test1= false;;
boolean test1=(10
34
<><=>=
(numberscharacters)
Stringsbooleansarrays
35
3.
:
1)
2)
3)
4)
&
|
^
!
(AND)
(OR)
(XOR )
(NOT)
5) && (AND)
6) ||
(OR)
36
( &&|| )
37
(&| )
()
,
38
4.
&|~^>>>>><<
1) >>
2) <<
3) >>>
SCJP (?)
:
39
5.
=+=-=*=/=
&=|=%=<<=>>=>>>=
op1
op1=op1
op1
op2;
op1= op2;
a=a+b;a+=b;
40
6.
? :op1 ? op2 :
op3
3
op1:
(exp1)(exp2)
41
7.
().[ ]( )
instanceofnew
int a=51;
char c=(char)a;
h )
42
( )
:
a+b+c/3
((a + b + c ) / 3
43
if / else if / else
while
for
do while
switch case
b k
break
continue
44
Java
: ifif/elseswitch
: forwhiledo/while
o w edo/w e
45
if
if:
if ()
( )
if ()
{
if ( grade >= 60 )
System.out.println( "Passed" ); // Here could be {a statement block}.
46
if-else
if-else:
if ()
(
)
11
else
22
if (grade>60)
( d >60)
System.out.println("Passed!");
else
l
System.out.println("Failed!");
47
/*
Demonstrate the if. Call this file
"IfSample.java".
*/
class IfSample {
public static void main(String args[]) {
int xy;
x = 10;
y = 20;
if(x < y) System.out.println("x is less than y");
x = x * 2;
if(x == y) System.out.println("x now equal to
y");
x = x * 2;
if( > y)) System.out.println("x
if(x
i l ( now greater
than y");
// this won't display anything
if(x
( == y) System.out.println("you
y
p
( y won't see
this");
}
}
Ans:
x is less than y
x now
ow equa
equal to y
x now greater than y
48
( ? : )
( cond ? express1 : express2 )
1
System.out.println(studentGrade >= 60 ? "Passed : "Failed");
2
max = ( a > b ? a : b );
if (a > b)
max = a;
else
max = b;;
49
switch
switch:
switch ()
{
case 1:
1
break;
case 2:
2
break;
case n:
n
break;
default:
(n+1)
}
50
for
:
for (1;2;3)
:
1
1;
while (2 )
{
3;
}
51
while
while
while ()
()true
while false
false
52
/*
D
Demonstrate
the
h ffor lloop.
Call this file "ForTest.java".
*//
class ForTest {
ppublic static void main(String
(
g args[])
g )
{
int x;
for(x = 0; x<10; x = x+1)
System.out.println("This is x: " +
x);
}
}
Ans:
This is x: 0
This is x: 1
This is x: 2
This is x: 3
This is x: 4
This is x: 5
This is x: 6
This is x: 7
This is x: 8
This is x: 9
53
do/while
1
int x = 0;
do{{
do
d
System.out.println("This is x: " + x);
{
}
while (x<10);
}
while ();
{ }
54
breakcontinue
breakcontinue
breakcontinue
breakcontinue
55
break
continue
56
break
break Identifier
continue
continue Identifier
57
0 0
0 1
0 1
58
0 0
0 1
1 0
1 1
2 0
2 1
3 1
3
59
(OOP)
()()
(
(classes)
)
(objects):
60
,
:
C
(action)
()
,
: Java
(object)
(class)
()
61
(class)
(class)
(class) ()()
()()
/
/
/
62
63
[] class [extends ] [implements ]
{
class point {
int x , y;
void init(int a, int b ){
x=a;
y=b;
}
}
64
Java
2000
65
box 3
class Box {
double width;
double height;
double depth;
}
Box
// create a Box object called mybox
Box mybox = new Box();
Box mybox; // declare reference to object
mybox
b = new Box();
B () // allocate
ll
a Box
B object
bj
66
class Box {
double width; double height; double depth;
}
class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
double vol;
mybox.width = 10;
mybox.height
y
g = 20;;
mybox.depth = 15;
// compute volume of box
vol = mybox
mybox.width
width * mybox
mybox.height
height *
mybox.depth;
System.out.println("Volume is " + vol);
}
}
67
Box b1 = new Box();
Box b2 = b1;
C++:
C++
:
[] ()
{
}
:
: void
intbytefloatString
:
:
(,)
. ();
69
:
return; //
}
}
:
return ; //
70
Java
71
class loc {
int x=1;
//
void
id printLocVar(
i tL V ( ){
int x=25;
//
System.out.println("\n
System.out.println(
\n x is :"+x);
: +x);
++x;
System.out.println(" x is :"+x);
}
void printInstanceVar( ){
S stem o t println("\n x is :"+
System.out.println("\n
:"+x);
);
x*=10;
System.out.println(x is :"+x);
: x);
}
}
x is :25
x is :26
x is :1
x is :10
72
class Box {
double width; double height; double depth;
public double boxVol(){
return width * height * depth;
}
}
// This class declares an object of type Box.
class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
double vol;
// assign values to mybox
mybox'ss instance variables
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
// compute volume
l
off box
b
vol = mybox.boxVol();
System.out.println("Volume is " + vol);
}
}
73
:
:
()
74
class BoxDemo {
public static void main(String args[]) {
d bl vol;
double
l
Constructing Box
vol = mybox2.volume();
77
78
class Box {
do ble width;
double
idth;
double height;
double depth;
// This is the constructor for Box.
Box(double wdouble hdouble d) {
width = w;
height = h;
depth = d;
}
// compute and return volume
() {
double volume()
return width * height * depth;
}
}
79
class BoxDemo {
public static void main(String args[]) {
double vol;
vol = mybox1.volume();
vol = mybox2.volume();
mybox2 volume();
80
()()
( )
(
)
(!)
81
extends
public class J_HelloApplet extends Applet
{
//
} // J_HelloApplet
82
class point{
int x, y;
point(int x, int y){
this.x=x; this.y=y; }
point( ){ this.x=0; this.y=0; }
}
class circle extends point{
int radius;
circle(int r, int x, int y){
radius=r;
this.x=x;
this.y=y;
}
}
83
this
this
class point {
int x , y;
void init(int x, int y ){
this.x=x;
this.y y;
this.y=y;
}
}
84
Java
this
class point {
int x, y;
point( ){this(-1,-1);}
){this( 1 1) }
point(int a, int b){x=a;y=b;}
}
85
: instanceof
: instanceof
:
if (p instanceof Circle)
true, p
Ci l ()
Circle()
86
Java
Java
(interface)
87
88
1)
2)
89
overloaded2
2
Java
90
class Overload {
public static void main(String args[]) {
double result;
// call
ll all
ll versions
i
off test()
()
ob.test();
ob.test(10);
b t t(10)
ob.test(1020);
result = ob
ob.test(123.25);
test(123 25);
()
:
public int square(int x)
{
return x * x;
}
public double square(double x)
{
return
t
x * x;
}
93
94
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
// Overload test for two integer parameters.
void test(int aint b) {
System.out.println("a and b: " + a + " " + b);
}
// overload test for a double parameter
void test(double a) {
System out println("Inside
System.out.println(
Inside test(double) a: " +
a);
}
}
class Overload {
public
bli static
i void
id main(String
i (S i
args[]) {
OverloadDemo ob = new
OverloadDemo();
int i = 88;
ob.test();
();
ob.test(1020);
ob.test(i);
ob test(123 2);
ob.test(123.2);
}
}
()
96
: J_Teacher.Java
// : J
J_Teacher.java;
Teacher java; :
class J_Employee
{
public int m_workYear; //
public J_Employee( )
{
m workYear = 1;
m_workYear
} // J_Employee
public void mb_printInfo( )
{
S
System.out.println(""
i
("" + m_workYear);
)
} // mb_printInfo
} // J_Employee
J Employee
97
: J_Teacher.Java
public class J_Teacher extends J_Employee
{
public int m_classHour; //
public J_Teacher(
J Teacher( )
{
m_classHour = 96;
} // J_Teacher
public void mb_printInfo( )
{
System.out.println(""
System.out.println(
+ m_workYear);
m workYear);
System.out.println("" + m_classHour);
} // mb_printInfo
public
bli static
t ti void
id main(String
i (St i args[[ ])
{
J_Employee a = new J_Employee( );
a.mb printInfo( );
a.mb_printInfo(
a = new J_Teacher( );
a.mb_printInfo( );
} // main
} // J_Teacher
J T h
98
&
99
Java recursion
Java
100
// A simple
i l example
l off recursion.
i
class Factorial {
// this is a recursive function
int fact(int n) {
int result;
if(n==1) return 1;
// fact(1)
1
result = fact(n-1) * n; // fact( n-1 ) n
return result;
F
Factorial
i l off 3 is
i 6
}
}
Factorial of 4 is 24
class Recursion {
Factorial of 5 is 120
public static void main(String args[]) {
Factorial f = new Factorial();
System out println("Factorial of 3 is " + f.fact(3));
System.out.println("Factorial
f fact(3));
System.out.println("Factorial of 4 is " + f.fact(4));
y
p
(
of 5 is " + f.fact(5));
( ))
System.out.println("Factorial
}
101
}
i
// Another example that uses recursion.
recursion
class RecTest {
int values[];
RecTest(int i) {
values = new int[i];
}
// display array recursively
void printArray(int i) {
if(i==0) return;
else printArray(i
printArray(i-1);
1);
System.out.println("[" + (i-1) + "] " + values[i-1]);
}
}
class Recursion2 {
public static void main(String args[]) {
R T t obb = new RecTest(10);
RecTest
R T t(10)
int i;
for(i=0; i<10; i++) ob.values[i] = i;
ob.printArray(10);
b i tA
(10)
}
}
[0] 0
[1] 1
[2] 2
[3] 3
[4] 4
[5] 5
[6] 6
[7] 7
[8] 8
[9] 9
102
(package)
Java
103
Java
Java
/
import
:
import javax.swing.JApplet;
104
java.lang
java.lang.Object
java.lang.Math
java.util
java.util.Random
105
():
1) public
2) private
3) protected
4) d
default()
f lt()
106
107
abstract
Java(abstract)
(abstract)
(abstract)(abstract)
:
public abstract class J_Vehicle
J Vehicle
{
public abstract void fuel();
108
static
:
t ti
(static)(static)
(static)
: System.out
(static)
: main( )
:
Math.sqrt( )
public static double sqrt(double a)
109
static
static
i ()
static
i
static main( )
static
i
static
110
static
static
static
this super
super
static static
static
static
111
System.out.println("in
y
p
( meth: a = " + a);
);
in meth: a = 3
b = a * 4;
// UseStatic,
}
public static void main(String args[])//{:
// a->3static(
a >3 static(
// th(42)
//meth(42);
}
)b->a*4=12
}
()
( )
// ->main()->meth(42)
112
: final
:
1) final
2) final
3) final
113
final
final
fi l int
final
i FILE_NEW = 1;
final int FILE_OPEN = 2;
final int FILE
FILE_SAVE
SAVE = 3;
final int FILE_SAVEAS = 4;
final int FILE_Q
QUIT = 5
final
final
114
(interface)
(interface)
: abstract
: finalstatic
(interface)
public
bli
.java
115
1:
public
bli interface
i t f
J C t t
J_Constants
{
public static final int ONE = 1;
public static final int TWO = 2;
public static final int THREE = 3;
} // J_Constants
2:
interface J_Shape
{
public abstract void mb_draw(Graphics2D g);
} // J_Shape
J Shape
116
public
abstract
public
staticfinal
117
:
public class A extends B implements C, D
{
}
118
119
(GUI)
120
(
)
:
121
{
}
122
}
:
123
// : J_Primitive.java;
J Primitive java; :
public class J_Primitive
{
public static void mb_method(
mb method( int a )
{
System.out.println("a++a=" + a);
a++;
System.out.println("a++a=" + a);
} // mb_method
public static void main(String args[ ])
{
int i=0;
System.out.println("i=" + i);
mb method(i);
mb_method(i);
System.out.println("i=" + i);
} // main
} // J_Primitive
J Primitive
124
&
j
javac
J P i iti j
J_Primitive.java
:
j
java
J P i iti
J_Primitive
:
i=00
i
a++a=0
++ 1
a++a=1
i=0
125
// ////////////////////////////////////////////////////////
//
//
// ////////////////////////////////////////////////////////
126
J_Shape.javaJ_Shape
J Ci l j
J_Circle.javaJ_Circle
J Ci l
J_Shape
3. J_Rectangle.javaJ_Rectangle
J_Shape
4. J_Area.javaJ_Area
J_CircleJ_Rectangle
1.
2
2.
127
: J_Shape.java
J Shape java
// : J_Shape.java; :
public interface J_Shape
{
//
public abstract double mb_getArea( );
} // J_Shape
J Sh
128
: J_Circle.java
J Circle java
// : J_Circle.java; : ()
public class J_Circle implements J_Shape
{
public double m_x,
m x m
m_y;
y; //
public double m_radius; //
public J_Circle(double r)
{
m_x = 0;
0
m_y = 0;
m radius = r;
m_radius
} // J_Circle
129
: JJ_Circle.java
Circle java
// : J_Circle.java; : ()
public J_Circle(double x, double y, double r)
{
m x = x;
m_x
m_y = y;
m_radius = r;;
} // J_Circle
//
public
i double mb_getArea(
A ()
{
return (Math.PI
(Math PI*m
m_radius
radius*m
m_radius);
radius);
} // mb_getArea
} // J_Circle
130
: J_Rectangle.java
J Rectangle java
// : J_Rectangle.java; : ()
public class J_Rectangle
J Rectangle implements J_Shape
J Shape
{
public double m_minX, m_minY; //
public double m_maxX, m_maxY; //
public J_Rectangle(double x1, double y1, double x2, double y2)
{
if (x1<x2)
{
m_minX = x1;
m_maxX = x2;
}
else
{
m minX = x2;
m_minX
m_maxX = x1;
} // if-else
131
: J_Rectangle.java
J Rectangle java
// : J_Rectangle.java; : ()
if (y1<y2)
{
m_minY = y1;
m_maxY = y2;
}
else
{
m minY = y2;
m_minY
m_maxY = y1;
} // if-else
} // J_Rectangle
//
public double mb_getArea( )
{
return ( (m_maxY-m_minY) * (m_maxX-m_minX) );
} // mb_getArea
} // J_Rectangle
132
: J_Area.java
J Area java
// : J_Area.java; :
public class J_Area
J Area
{
public static void main(String args[ ])
{
J_Shape a = new J_Circle( 5 );
System.out.println("5" + a.mb_getArea( ));
a = new J_Rectangle(0 , 0, 3, 4);
System.out.println("" + a.mb_getArea( ));
} //
main
} // J_Area
133
:public
Vector
134
int[ ] c = new int[12];
c
?
c.length
0
c[ 0 ] = 3;
c[ 0 ] += 5;
c[ 0 ]
-45
45
c[ 1 ]
c[ 2 ]
c[ 3 ]
72
c[ 4 ]
1543
c[ 5 ]
-89
c[ 6 ]
c[ 7 ]
62
c[ 8 ]
-3
c[ 9 ]
c[ 10 ]
6453
c[ 11 ]
78
c.length
l
th
12
135
, :
c[11]
: :
if (x == 3)
tt= (c[ 5 - 2 ] == c[ 3 ]) &&( c[ x ]]== c[ 3 ]); // tt=true
true
136
:
(1)
(2)
[]
[ ];
:
int [ ] c;
String[ ] names;
int c[ ];
String names[ ];
137
Java
new
:
int[ ] c;
//
c = new int[12]; //
0false
ll
null
:
double[ ] squares;
squares = new double[100];
for (int i=0; i < squares.length; i++)
{
squares[i] = i*i;
}
139
Java
:
int[ ] n = { 10, 20, 30, 40, 50 };
0, 1, 2, 3, 4
new
140
Java
A
ArrayIndexOutOfBoundsException
I d O tOfB
dE
ti
141
int[ ][ ] a = new int[3][4];
a[ 0 ][ 0 ]
a[ 0 ][ 1 ]
a[ 0 ][ 2 ]
a[ 0 ][ 3 ]
a[ 1 ][ 0 ]
a[ 1 ][ 1 ]
a[ 1 ][ 2 ]
a[ 1 ][ 3 ]
a[ 2 ][ 0 ]
a[ 2 ][ 1 ]
a[ 2 ][ 2 ]
a[ 2 ][ 3 ]
142
1
()
class J_FillArray
{
public static void main (String args[])
{
int[[ ][ ] matrix = new int[4][5];
[ ][ ];
for (int row=0; row < 4; row++)
{
for ((int col=0;; col < 5;; col++))
{
matrix[row][col] = row + col;
} //
for
} // for
} // main
} // J_FillArray
J FillArray
143
2
:
double[
d
bl [ ][ ] c =
{
{1.0, 2.0, 3.0, 4.0},
{0.0, 1.0, 0.0, 0.0},
{0.0, 0.0, 1.0, 0.0}
};
144
Java
:
int a[ ][ ];
a = new int[ 3 ][ ];
a[ 0 ] = new int[ 3 ];
a[[ 1 ] = new int[
i t[ 2 ];
]
// allocate rows
// allocate row 0
// allocate
ll t row 1
a.length
a[[ i ].length
]
g i
145
:
class
l
J Fill3DA
J_Fill3DArray
{
public static void main (String args[])
{
int[ ][ ][ ] M = new int[4][5][3];
for (int row=0; row < 4; row++)
{
for (int col=0; col < 5; col++)
{
for ((int ver=0;; ver < 3;; ver++))
{
M[row][col][ver] = row + col + ver;
} // for
} // for
} // for
} // main
} // J_Fill3DArray
J Fill3DA
146
Java:
147
String
String
C: (char)(String)
String'\u0000'
String \u0000
String a
String b
Hello World!
String c
148
String
String
: Hello "
String c = "blue";
cString
"blue"String
149
String
String
11
( p
(deprecated)
)
docs\index.html
150
// J_StringConstructors.java;
J StringConstructors java; :
s1
//
public class J_StringConstructors
String:
g
{
public static void main(String args[ ])
{
String:
String s1 = null;
Stringg s2 = new String(
g );
String s3 = "!";
String s4 = new String( s3 );
System out println("s1: " + s1);
System.out.println("s1:
System.out.println("s2: " + s2);
System.out.println("s3:
y
p
(
" + s3);
);
System.out.println("s4: " + s4);
} // main
} // J_StringConstructors
J St i C t t
151
String :
length( ), charAt( ) getChars( )
length( )
String
S i
: Strings length
charAt(int
h A (i index)
i d )
getChars(int
tCh (i t srcBegin,
B i int
i t srcEnd,
E d
char[ ] dst, int dstBegin)
152
(String)
153
==
Java()
s1 = hello;
//
s2 = new String( "hello"
hello );
s1 == "hello";
// true
// false
s2 == "hello";;
154
(String)
: s1.equals( "Hi" );
(String)
int compareTo(String anotherString)
:
0 :
0:
anotherString
0:
anotherString
(String)
indexOf
indexOf
-1
:
String
St
i name = "CoolTools";
"C lT l "
System.out.println (name.indexOf("oo"));
157
lastIndexOf
public int lastIndexOf(int ch, int fromIndex)
:
(this.charAt(k) == ch) && (k <= fromIndex)
-1:
1
158
substring
substring(int beginIndex)
:
(String)
concat
s1.concat( s2 )
s1s2
String s1 = "ABC";
String s2 = "XYZ";
s1 = s1.concat(s2); // s1 = s1 + s2;
160
StringvalueOf
(static)valueOf
valueOf(char[ ] data)
return new String(data);
valueOf: boolean
charintlongfloatdoubleObject
toString
161
String
String
s1.replace( char1, char2 )
s1char1char2
s1char1, s1
:
mesquite in your cellar.replace(e, o)
"mosquito
mosquito in your collar
collar"
JonL.replace(q, x)JonL ()
162
String
s1.toUpperCase
s1.toLowerCase
:
toUpperCase
pp
?
163
St i
String
s1.trim(
i )
s1.toString( )
s1s1
toString
toString
s1.toCharArray(
s1 toCharArray( )
164
String
g
intern
: intern
st st(s.equals(t))
st(s.intern()
== t.intern())
165
StringBuffer
String
(String)
(read-only)
(
y)
StringBuffer
StringBuffer
St i B ff
166
StringBuffer
buf1 = new StringBuffer();
StringBuffer16
String StringBuffer
String StringBuffer
(String)
(StringBuffer)
String StringBuffer
StringBuffer
g
Stringg
toString()
g()
168
StringBuffer
length()
StringBuffer
capacity()
StringBuffer
setLength(int newLength)
St
StringBuffer
g u e
169
ensureCapacity
C
it (i
(intt minimumCapacity)
i i
C
it )
ensureCapacity
C
it
StringBuffer
(minimumCapacity)
:
minimumCapacity
i i
C
it .
2.
minimumCapacity
170
St i B ff
StringBuffer
charAt(int index)
StringBuffer
reverse( )
StringBuffer
171
11 append
StringBuffer
:
public String reverseIt(String source)
{
int c;
len = source.length();
StringBuffer dest = new StringBuffer(len);
for (c = (len - 1); c >= 0; c--)
{
dest.append(source.charAt(c));
}
return dest.toString();
}
172
insert delete
insert
StringBuffer
173
J
Java
(E
(Exception)
ti )
(Exception)?
(Exception)
174
try
catch
catch
catchfinally
try
{
//
}
catch (ExceptionType ref)
{
//
}
finallyy
{
//
}
175
?
/
/
:
if-else
176
177
1.
2.
3.
4.
System.exit()
178
(Exceptions)
0
()
179
(Exception)
180
(RuntimeExceptions)
ArrayIndexOutOfBoundsException
NullPointerException
(object)
ClassCastException
p
181
throws
th
throws
(Errors) (RuntimeExceptions)
182
(Exception)
catch
catch
183
finally
finally
:
: finally catch
try
try
t
184
throws
( ) throws 1,
1 2,
2
{
//
}
:
public static void g( ) throws Exception
{
throw new Exception( );
} // g
185
: --
(throws)
throws
186
catch
:
throw e;
tryt
catch
t h
187
java.io I/O
: java.io.InputStream
java io InputStream
: java.io.OutputStream
:
java.io.Reader
:
j
i R d
: jjava.io.Writer.
188
?
: System.inSystem.out System.err
System.in - ()
System.out
y
()
System.err ()
(: )
189
(Exception)
(
p
)
U
Unix,
i Control-D
C t l D
Windows,
Control-Z
190
?
()
191
Java
Java
192
InputStream
java.io.InputStream (abstract)
:
public abstract int read( ) throws IOException
public int read(byte[ ] data) throws IOException
public int read(byte[ ] data, int offset, int length) throws IOException
public long skip(long n) throws IOException
public int available( ) throws IOException
public void close( ) throws IOException
public
bli void
id mark(int
k(i t readlimit)
dli it)
public void reset( ) throws IOException
public boolean markSupported( )
193
InputStreamread( )
(unsigned byte)
( )( )
(int)()
: 0255
-1
public abstract int read(( ) throws IOException
p
p
194
read( )
java io InputStream
java.io.InputStream
public int read(byte[ ] data) throws IOException
public int read(byte[ ] data, int offset, int length) throws IOException
195
available( )
java.io.InputStream
java io InputStream
public int available( ) throws IOException
196
197
InputStreamOutputStream abstract
:
()flush(
)
(/)
198
Print
java.io.PrintStream
FilterOutputStream
: System.out System.err
PrintStream
(th
(throws)(IOException)
)(IOE
ti )
(traps)
(IOExceptions)
199
Print
java.lang.Object
|
+--java.io.OutputStream
|
+--java.io.FilterOutputStream
|
+--java.io.PrintStream
200
java.lang.Object
|
+--java.lang.System
1) static
t ti P
PrintStream
i tSt
err
2) static
t ti I
InputStream
tSt
i
in
java.io
FileInputStream
FileOutputStream
FileReader
FileWriter
RandomAccessFile
202
java.io.FileInputStream
(InputStream)
:
public FileInputStream(String name) throws FileNotFoundException
public
bli FileInputStream(File
Fil I
tSt
(Fil file)
fil ) throws
th
Fil
FileNotFoundException
N tF
dE
ti
public FileInputStream(FileDescriptor fdObj)
public native int read( ) throws IOException
public int read(byte[ ] data) throws IOException
public int read(byte[ ] data, int offset, int length) throws IOException
public native long skip(long n) throws IOException
public native int available( ) throws IOException
public native void close( ) throws IOException
public final FileDescriptor getFD( ) throws IOException
203
java.io.FileOutputStream
(OutputStream)
:
public FileOutputStream(String name) throws IOException
public FileOutputStream(String name, boolean append) throws IOException
public FileOutputStream(File file) throws IOException
public
bli FileOutputStream(FileDescriptor
Fil O t tSt
(Fil D
i t fdObj)
public native void write(int b) throws IOException
public void write(byte[ ] data) throws IOException
public void write(byte[ ] data, int offset, int length) throws IOException
public native void close( ) throws IOException
public final FileDescriptor
p
p
getFD() throws IOException
g
p
204
Data()/
java.io.DataInputStream
java.io.DataOutputStream
(String)
(
g)
()
DataInputStream
DataOutputStream
205
DataOutputStream
public DataOutputStream(OutputStream out)
public void write(int b) throws IOException
public void write(byte[] data, int offset, int length) throws IOException
public final void writeBoolean(boolean b) throws IOException
public final void writeByte(int b) throws IOException
public final void writeShort(int s) throws IOException
public final void writeChar(int c) throws IOException
public final void writeInt(int i) throws IOException
public
bli final
fi l void
id writeFloat(float
it Fl t(fl t f) th
throws IOE
IOException
ti
public final void writeDouble(double d) throws IOException
public final void writeBytes(String s) throws IOException
public final void writeChars(String s) throws IOException
public final void writeUTF(String s) throws IOException
public final int size( )
p
public void flush( ) throws IOException
206
/(I/O):
/(I/O)
/(I/O)
/(I/O)
//
()
()
java.io.BufferedInputStream
j
i B ff dI
tSt
java.io.BufferedOutputStream
/
207
:
public BufferedInputStream(InputStream in)
public BufferedInputStream(InputStream in, int size)
public BufferedOutputStream(OutputStream out)
public BufferedOutputStream(OutputStream out, int size)
208
/
RandomAccessFile
DataInputStreamDataOutputStream
RandomAccessFileDataInputDataOutput
DataInputStreamDataInput
DataOutputStreamDataOutput
209
RandomAccessFile
java.lang.Object
|
+--java.io.RandomAccessFile
j
public class RandomAccessFile
extends Object
implements DataOutput, DataInput;
210
RandomAccessFile
RandomAccessFile
: // J_RandomAccessFile.java
// J_RandomAccessFile.java; :
//
import java.io.IOException;
import java.io.RandomAccessFile;
public
bli class
l
J R d A
J_RandomAccessFile
Fil
{
public static void main(String args[ ])
{
try
{
RandomAccessFile f=new RandomAccessFile("test.txt", "rw");
d bl d;
double
d
}
for (int i=0; i<10; i++)
catch (IOException e)
f.writeDouble(0.5*i);
{
f.seek(16);
System err println(":" + e);
System.err.println(":"
f.writeDouble(0);
e.printStackTrace( );
f.seek(0);
} // try-catch
for (int i=0; i < 10; i++)
} //
main
{
} // J_RandomAccessFile
d=f.readDouble( );
System.out.println("[" + i + "]: " + d);
} // for
f.close( );
212
, &
213
ReaderWriter()
/
java.io.Reader
java.io.Writer
java.io.Reader java.io.Writer (abstract )
(superclasses)
( p
)
/
214
ReaderWriter
java.io.Reader
java.io.InputStream
java.io.Writer
java io Writer
java.io.OutputStream
215
: Writerwrite
public void write(int c) throws IOException
(:
065535)
write:
public void write(char[ ] text) throws IOException
public abstract void write(char[ ] text, int offset, int length) throws
IOException
public void write(String s) throws IOException
public void write(String s, int offset, int length) throws IOException
216
Reader
java.io.BufferedReader java.io.Reader
java.lang.Object
java
lang Object
|
+--java.io.Reader
|
+--java.io.BufferedReader
:
BufferedReaderReader(:
FileReader)BufferedReader
:
BufferedReader br = new BufferedReader(new FileReader("test"));
217
java.io.LineNumberReader
j
java.io.BufferedReader
i B ff dR d
java.lang.Object
|
+--java io Reader
+--java.io.Reader
|
+--java.io.BufferedReader
|
+--java.io.LineNumberReader
LineNumberReader
public LineNumberReader(Reader in)
public LineNumberReader(Reader in, int size)
public void setLineNumber(int lineNumber)
public int getLineNumber( )
218
InputStreamReader
java.io.InputStreamReader
Reader
:
InputStreamReader isr = new inputStreamReader(System.in);
219
OutputStreamWriter
java.io.OutputStreamWriter
Writer
:
OutputStreamWriter osw = new OutputStreamWriter(System.out);
220
FileReader
java.lang.Object
|
+--java.io.Reader
|
+--java.io.InputStreamReader
|
+--java
+
java.io.FileReader
io FileReader
:
FileReader fr = new FileReader("test");
221
java.io.FileWriter
java.lang.Object
|
+--java.io.Writer
|
+--java.io.OutputStreamWriter
|
+--java
+
java.io.FileWriter
io FileWriter
:
FileWriter fw = new FileWriter(test");
222
PrintWriter
java.io.PrintWriter java.io.Writer
java.lang.Object
|
+--java.io.Writer
|
+--java.io.PrintWriter
java.lang.Object
|
+--java.io.OutputStream
|
+--java.io.FilterOutputStream
|
+--java.io.PrintStream
java.io.PrintStreamjava.io.PrintWriter
PrintWriter
223
:
(RMI)socket
224
:
// J_SerialData.java;
j ; :
// :
import java.io.Serializable;
public class J_SerialData implements Serializable
{
static final long serialVersionUID = 123456L;
int m_id = 111;
serialVersionUID
:
// J_ObjectOutputStream.java; :
//
i
import
t java.io.FileOutputStream;
j
i Fil O t tSt
import java.io.ObjectOutputStream;
public class J_ObjectOutputStream
J ObjectOutputStream
{
public static void main(String args[ ]) throws Exception
{
Obj tO t tSt
ObjectOutputStream
f = new ObjectOutputStream
Obj tO t tSt
(new FileOutputStream("object.dat"));
J_SerialData s = new J_SerialData( );
j ( );
f.writeObject(s);
f.writeObject("");
f.close( );
} // main
} // J_ObjectOutputStream
J ObjectOutputStream
226
:
// J_ObjectInputStream.java; :
//
import
p
jjava.io.FileInputStream;
p
;
import java.io.ObjectInputStream;
public class J_ObjectInputStream
{
public static void main(String args[ ]) throws Exception
{
j
p
f = new ObjectInputStream
j
p
ObjectInputStream
(new FileInputStream("object.dat"));
J_SerialData d = (J_SerialData)(f.readObject( ));
d.mb_output( );
String s = (String)(f
(String)(f.readObject());
readObject());
System.out.println(s);
f.close( );
} // main
} // J_ObjectInputStream
227
, &
228
File
java.io.File
:
File f1 = new File("/etc/passwd");
File f2 = new File(
File("/etc",
/etc , "passwd");
passwd );
229
Fileexists( )
exists()
File
FileOutputStream
File
Fil
230
File
File
232
/ (Unix) \ (Windows)
Java
/ \\
233
?
HTML
(Hypertext Markup Language)
Java
java.applet.Applet (
javax swing JApplet)
javax.swing.JApplet)
appletviewerHTML
234
java.lang.Object
|
+--java.awt.Component
|
+ j
+--java.awt.Container
t C t i
|
+--java awt Panel
+--java.awt.Panel
|
+--java
+
java.applet.Applet
applet Applet
|
+--javax.swing.JApplet
j
g
pp
235
JAppletApplet
JApplet java.applet.Applet
JApplet
Swing
JApplet BorderLayout.
Applet FlowLayout.
JAppletcontentPane
:
Applet,
:
applet.add(child);
Japplet,:
J
l t
japplet.getContentPane( ).add(child);
236
:
public void init( ):
public
bli void
id start(( ):
)
public
bli void
id stop(
t ( ):
)
237
Init
()
Start
Stop
Start
destroy
238
239
API
/
240
HTML
Code codebase
JARARCHIVE
241
Code Codebase
CODE
class
.class
CODEBASEURL(
).class/
)
class/
1:
<APPLET CODE= "J_Clock.class" codebase="..\..\a005Clock"
WIDTH= 200 HEIGHT= 200>
</APPLET>
2:
<APPLET
APPLET CODE
CODE= "J
J_Clock.class
Clock.class"
codebase="http://cgcad.thss.tsinghua.edu.cn/~junhai/java/"
WIDTH= 200 HEIGHT= 200>
</APPLET>
/A
242
JARARCHIVE
.class
classJAR
JAR
HTTP
243
: (ARCHIVE)
javac *.java
* java
jar -cvf all.jar *.class
<!--------- AppletExample.html
<!
AppletE ample html : --------->
>
<HTML>
<HEAD> <TITLE> An applet Example </TITLE> </HEAD>
<BODY>
<APPLET code="J_MainCircle.class" ARCHIVE="all.jar
WIDTH= 300 HEIGHT= 100>
</APPLET>
<P>
<APPLET code="J_StaticClock.class" ARCHIVE="all.jar
WIDTH= 200 HEIGHT= 200>
</APPLET>
<P>
<APPLET code="J_Clock.class" ARCHIVE="all.jar
WIDTH= 200 HEIGHT= 200>
</APPLET>
</BODY>
</HTML>
AppletExample.html
244
HTML
<PARAM NAME="name" VALUE="value">
<APPLET
APPLET ...
...> </APPLET>
/APPLET
public
bli String
St i getParameter(String
tP
t (St i name))
java.applet.Applet
245
: J_Applet.java
import
p
jjava.awt.*;;
import javax.swing.*;
public class J_Applet extends JApplet
J_Applet.java
{
public void paint(Graphics g)
{
g s= getParameter("TestPara");
g
(
);
String
g.drawString("Value of \"TestPara\" is " + s + ".", 10, 50);
} // paint
} //J_Applet
<!--------- AppletExample.html : --------->
<HTML>
<HEAD> <TITLE> An applet Example </TITLE> </HEAD>
<BODY>
<APPLET CODE= "J_Applet.class" WIDTH= 280 HEIGHT= 140>
<PARAM NAME="TestPara" VALUE="TestValue">
</APPLET>
</BODY>
AppletExample.html
</HTML>
Value of "TestPara" is TestValue.
246
.class
247
// J_List.java; :
:
//
import
p
jjava.awt.BorderLayout;
y ;
import java.awt.Container;
import java.awt.Image;
import java.io.File;
import javax.imageio.ImageIO;
javax imageio ImageIO;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
p
jjavax.swing.Icon;
g
;
import
import javax.swing.ImageIcon;
import javax.swing.JApplet;
import javax.swing.JFrame;
import javax.swing.JLabel;
javax swing JLabel;
import javax.swing.JList;
J_List.java
p
public
class J_List
_
extends JApplet
pp
{
private String m_items[ ]
= { "snow.gif", "flag.gif" , "rain.gif"};
private JList m_list
m list = new JList(m_items);
JList(m items);
private JLabel m_label = new JLabel( );
private Icon
m_icons[ ] = new ImageIcon[3];
private Image
p
g
m_image[
_
g ] = null;
Container m_container = null;
248
m_container.add(m_label, BorderLayout.EAST);
m_label.setIcon(m_icons[0]);
} //
init
J_List.java
:
J Li t j
public static void main(String args[ ])
{
JFrame f = new JFrame("");
J List app = new J_List(
J_List
J List( );
app.m_container= f.getContentPane( );
app.m_image = new Image[3];
y
try
{
for (int i=0; i< 3; i++)
app.m_image[i] = ImageIO.read( new File(app.m_items[i]) );
}
catch (Exception e)
{
y
p
(
+ e);
);
System.err.println(":"
e.printStackTrace( );
} // try-catch
app.init( );
f setSize(250 110);
f.setSize(250,
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
} // main
} // J_List
250
AppletExample.html
:
A l tE
l ht l
<!--------- AppletExample.html :
--------->
<HTML>
<HEAD>
<TITLE>
</TITLE>
/TITLE
</HEAD>
<BODY>
<APPLET CODE= "J_List.class" WIDTH= 250 HEIGHT= 65>
</APPLET>
<BR>
</BODY>
</HTML>
251
&
,
snow.gifflag.gifrain.gif
252
12
Internet
InternetIP (Internet
Protocol)
: 216.239.53.100
: www.google.com
java.net.InetAddressInternet
j
t I tAdd
I t
t
253
InetAddress
InetAddress class public
:
static InetAddress getByAddress(byte[ ] addr)
static InetAddress getByName(String host)
254
URL
URL (Uniform
Resource Locator), (World
Wide Web))
/
(search engine)
255
URL
(Protocol)(Host)[:Port][File][#Reference]
http://www.ncsa.uiuc.edu:8080/demoweb/urlprimer.html#INSTALL
p
p
http://www.tsinghua.edu.cn/
http://localhost:8080/index html#bottom
http://localhost:8080/index.html#bottom
ftp://166.111.233.143/java/
mailto:yongjunhai@tsinghua.org.cn
256
URL:
Protocol
Host
Port
Fil
File
Reference, section anchor
257
: Port
(Port)
: 0-65535 (16 bits)
1024: (: telnet,
SMTP, ftp)
258
: java.net.URL
java.net.URL URL
public final class URL
j
java.net.URL:
public URL(String u) throws
MalformedURLException
public URL(String protocol, String host, String file)
throws MalformedURLException
public URL(String protocol, String host, int port,
String file) throws MalformedURLException
259
URL
java.net.URL
URL:
TCP
TCP (Transfer Control
Protocol)
TCP
TCP, , IP
IP
261
TCP/IP
ServerSocket(port#)
Socket(host, port#)
ServerSocket.accept()
OutputStream
OutputStream
InputStream
InputStream
Socket.close()
Socket.close()
262
java.net.Socket
java.net.Socket
1.
2.
3
3.
4.
263
java.net.Socket
getInputStream(): socket
getOutputStream():socket
264
Socket
Socket()
Socket(InetAddress address, int port)
Socket(InetAddress address, int port, InetAddress localAddr, int localPort)
Socket(String host, int port)
Socket(String host, int port, InetAddress localAddr, int localPort)
:
Socket javaSite = new Socket("java.sun.com", 80);
265
// J_Server.java; :
// TCP
import
p
jjava.io.DataOutputStream;
p
;
import java.net.ServerSocket;
import java.net.Socket;
: J_Server.java
public class J_Server
{
public static void main(String args[ ])
{
y
try
{
ServerSocket server = new ServerSocket(5000);
while (true)
{
Socket s = server.accept( );
System.out.println ("");
DataOutputStream
p
dataOut
= new DataOutputStream(s.getOutputStream( ));
dataOut.writeUTF("");
dataOut.close( );
s.close( );
} // while
}
catch (Exception e)
{
} // try-catch
} // main
} // J_Server
266
: J_Client.java
// J_Client.java;
j
;
:
// TCP
import java.io.DataInputStream;
import java.net.Socket;
public class J_Client
{
public static void main(String
p
(
g args[
g [ ])
{
try
{
Socket s = new Socket("localhost",
Socket("localhost" 5000);
DataInputStream dataIn
= new DataInputStream(s.getInputStream( ));
y
p
(
" + dataIn.readUTF(( ));
System.out.println(":
dataIn.close( );
s.close( );
}
catch (Exception e)
{
} // try-catch
} // main
} // J_Client
267
14
268
269