You are on page 1of 399

W

W
K

? ? ? ?
K

W
K

K
J J

Java language
EF

EloopingFK
E branchingF
K

--

W
W

W
W
J

J
J

W

--

K
K

KKKKKKKKK

( Computer Programmer)
K
(Hardware) (Software)

J W
Operating SystemJ

K VMSLinuxUnixDos EwindowsF

K

WindowsUnix
KDos

--

Application Programs J

J W

J Oracle J

Access J Excel Autocad

K Fotoshop

Programming Languages J

J W
Machine languages
Assembly languages

High level languages

Machine Language
K

10

KEF

K
--

Assembly Languages

KSubStoreAdd

Load

Add

Store


assembler



K

High Level Languages


Compilers

KEF
Sum = A + B+ C

C++ C
K Java ADABasic FortranPascal

Interpreter

--

compiler K
EInterpreter)
K


J W

KJ
J
K

KJ
C . Windows UnixJ
KUnix

KJ

--


-1
KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKJ

J W J
KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK

KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK

KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK

KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKJ
KKKKKKKKKKKKKKKKKKKKKKKKKKKKKK
KKKKKKKKKKKKKKKKKKKKKKKJ

EFEF-2

EF
EF

-
-

EF

EF

EF

--


Problem Solving

W

W

-1

-2
-3

-4

W
100

8W

--



Problem Solving


J W

K J

K J
J
K

K J

J W


K

K

--

J W

K ?

EF
K

K
EF KKKKKKK
EFK
K


K
- -

K
K

?
?

top-down

K Kdesign

K

K

??
K

- -

K
KKKKKKKKKKKKKKKK
Algorithm and Pseudo Code

KE1-F

Algorithm K
flowchart


KK

- -

Definition of
Problem

Problem Analysis

Algorithm

Program


Errors List

Data
Checking

Byte Code

O utput Results

E1-1F

- -

Execution of
Program

Compiler

K
EAlgorithmsF

K


K

EF

WK
W

T3,T2,T1 ,W

T3,T2,T1 WW

WAVW
AV = (T1 + T2 +T3) / 3

W
- -

W
CM Z

2.5% W
W
CM W
Z = .025 CMZ W

ZW

Flow charts

E1-2F
W
W
K
K

K
K

- -

(1)

STRRT / STOP )

(2)

( INPUT / OUTPUT )

(3)

( CALCULATION AND STORE )

(4)

( DECISON )

(5)

( LOOPING )

(6)

( CALL SUBROUTINE )

(7)

(8)

( FLOW LINE )

( CONNECTOR )

(9)

( COMMENT )

E1-2F

- -

KKKKK

W
System Flowcharts E

K

K
K
K

J
J
J
J

Programs Flowchart E

- -

Simple Sequential FlowchartsJ

Branched FlowchartsJ

Simple Loop Flowcharts J


Multi Loop FlowchartsJ

(1-3)K

Kb a

K (1-3)a
:(1)

K
W

W (1-4)

-1
-2

-3

- -

START

START

Order
book

Event
a

Receive
bill

Event
b

Pay bill
& Leave

Event
c

STOP

STOP

E1-4F

E1-3F

- -

START

Eflow chartF

ERF

READ
R

R2Z
2 R =

{ Z
R

PI = 3.14

A = Pi(R)

{Zpi Z

AZ R2A

C = 2PI (R)

CZ2 RC

A, R, CW

E1-5F

PRINT
R, A & C

STOP

E1-5F
- -

K EF
KE1-6F

?X

NO

YES
Event ?

E1-6-bF

E1-6-aF

1-F
W
E 1-7-aFKE7

KEbFWKEaF

EaFWE1-7-bF
WKEbF

EbF

- -

NO

YES

YES
Condition
?

Condition
?

Event a

NO

Event a

Event b

Event b

(1- 7 - b )

(1- 7 - a )

WF(x) Eflow chartF

F ( x) = { x x x 0
x0

WE1-8F
X J
X J

F(x) =X F(x) J
F(x) F(x) J

X , F(x) J

- -

START

Read X

NO

YES
X0

F (x) = - X

Print
X & F (x)

STOP

(1-8)

- -

(x) =

EF
W

E1-9F
START

Read

Green
Color

Yellow

STOP

Pass
Wait

STOP

(1- 9 )

- -

START

W
X


Read X

X +1
if x > 0
W = sin(x) +5
if x = 0
2X -1
if < 0

X?

W

WE1-10F

W = 2X - 1

W = SinX + 5

X -

W =X+1

X
X

W= X+1 W J

Print
X &W

W= sin (X) +5 W J

W=2X -1 W J

STOP

( 1-10 )

X, WJ

- -

KE1-11F

Condition
?

Yes

Event a

No

Event a

Yes

No

Condition
?

Yes

Yes

( 1-11 )

WE1-12FW

R J
A

A,R J

- -

EF
K

WE1-13FW

W
??

- -

START
START

READ
R

Take next
person

No

A = R2

Age 20

Yes
Print
R, A

Get him
married

Yes
More Circles

More people?

No
No
STOP

( 1-13 )

STOP

( 1-12)

- -

E F

W
E F

W(1-14)

-1
(2)

START

(4)

Is
Level < 1
?

K-2

Yes

K-3

KE F-4
(1)-5

Open
Feeding
Tap

No

Fill tank

Keep Tap
Closed

( 1-14 )


- -

K(1-15)
K

N1

(1-16a)

1 7WE7NF

3NN = N + 3 W
E(1-16b)
F14N

4 = 7N

W 7N

WN

NW
7N

- -

START

N=1
(a)

N
1

Print
N
N= N+3
(b)

N
4

No
N = 7?

Yes

(c)

N
7

( 1- 16 )

STOP

( 1- 15 )

(1-17)(1-15)


N(1-15)

NEN = 7F
7W7N
- -

K
START

N=1

N= N+3

No
N=7
?

Yes

Print
N

STOP

( 1- 17 )

- -


m
(X1, X2, ..., Xm)

T = Xi
i =1

TW
W

T0 = 0
T1 = T0 + X1 = 0 + X1 = X1
T2 = T1 + X2 = X1 +X2
Tm = Tm-1 + Xm = X1 + X2 + ... + Xm-1 + Xm

W
(1)
m1 iT0 = 0

Ti = Ti-1 + Xi

TTm. T1

(1)K X
Ti = T + Xi

i = 1, m

W
(2)
K T

(2)
(1)(2)
K

E100mF(1-18)

- -

STAR
T

T=0
I=1
m = 100

F
(1)E(1-19)
Inner Loop

Read
X

(2)

Outer Loop

T= T+X

I=I+1

No

I> M

Yes

nested

Print
T

STOP

( 1-19 )

( 1-18 )

- -

START

Take a
Piece

K5

W(1-20)

-1

Cut off a
5m Length

5-2
5-3

(2)

Yes

Is Remainder
> 5m

(4)

-4
(1)

No

Yes

More
Pieces ?

(1-20)W
No

STOP

( 20 )

- -

WJ

W(1-21)

I =1
Loop
I=1,N,

I=I+

Process to
be repeated

Process to be
repeated
I N?

E1-21F

- -

(I)
Ei = 1FI
ENFI
( )
(1-21-a)
W
KI-1
K-2
NIW-3
(4)
-4
(2)-5
(1-21-a)(5,4,3,1)
(1-21-b)
K
K
1 W

Loop
I = 1, n

E1-22F(1-21-b)
. 1
( 1- 22 )


(6)

(1-23)

K(11)
m = 100
(1-24)
- -

START

T =0
I=1
m = 100

START

Loop
I = 1, m

Loop
I = 1, n

Read
X

Read
R

T = T +X

A = R2

1
Print
R, A

Print
T

STOP

STOP

( 1-24 )

( 1-23 )

- -


E)

( )

Kx=3 , Y=5

S T AR T

R ead
X, Y

Y ES

YES

F=

X
X-Y

NO

X < 0

Y ES

NO

X > Y
?

F=

Y
X -Y

F = X2

X < Y

NO

F = Y2

Print
X, Y , F

STOP

( )

- -

START

I=1
S=0
N=0

Read
X

START

No

X > 0?

K=1
I=I+1

S=S+X
N= N+1

Y = K2 + 1

Y = K2 + 2
No

Print
Y

I = 20

Yes

Print
S, N

K 100

STOP

STOP

( )

( )

- -

W -

EF

1 N SUM -1
SUM N -2

1 N 1 N<6 -3

SUM -4

EF

X -1

(5) X 0 -2
(5) W =

x 2 + 5x 4

W -3

W = -X + 13 W W -4

W X -5
W -3
f(X) = | X-3 |

EF

SUM = i EF
i =1

F = n! = n(n-1) (2)(1)

EF

WS EF
S = [A, B, C ]
K S EF
WEF
a1, a2, a3, .., an-1, an
KEF
W EF
a1b1, a2b2, a3b3, .., an-1bn-1, anbn
- -

K EF
K3 5200EF
WEF
1, 3, 5, 7, .
WpolyWEF
POLY = 1+Z+Z2+ +Z10

Kz

- -

J J J J J J J J J J J J

J J J J J J J J J

J J J J J J J J J J J J J J J J J J J J J J J J J J J J W

J J J J J J J J J J J J J J J J J J J J J J J J J J J W

J J J J J J J J J J J J J J J J J J J J J J J J J J J J J J J

- -




K
W
EF

E F

??

- -

W
code

W
W

J
J
J
J

J
J
J

W
100

W
W


W

--

Components of Java programming languages


(java)
EReserved Words F EConstantsF EVariablesF
arithmetic FK

Relational FEassignmentFElogicFEoperation

KEString FEoperation

W

K
K
J W

(Application Program)

K?Java Interpreter?

Applet Program

Netscape NavigatorInternetExplorer

KEF

Applet
K??

--



Welcome to Java Programming!
W
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.

// Fig. 2-1: Welcome1.java


// A first program in Java.

E2-1 F

public class Welcome1 {


// main method begins execution of Java application
public static void main( String args [ ] )
{
System.out.println( "Welcome to Java Programming!" );
} // end method main
} // end class Welcome1
Welcome to Java Programming!
E2-1F

Welcome to Java Programming! E2-1F


J W
capital small -1

sum, Sum

K

Capital Letters
KSmall Letters

--

-2

// Fig. 2-1: Welcome1.java

Comment Statement

LL

K
LL

delimiter / *
Kdelimiter / *

/* This is a multiplier line


comment it can be split
into several lines */
Compiler/*KKKKKKKKKKKK*L


/***/

Javadoc

// A first program in Java

K
--

public class Welcome1 {


K(identifier) class

K
KUser defined classes

KEF Welcome1 class


class
K(identifier)

class
K .Welcome1

KidentifierSampleClassName

identifier
$_(0 9) (a-z, A-Z)
J W
K J
K J

K J

KEE2-2FF J
K J

K J


Welcome1, $Value, _Value.S identified, etc
J W
K

7button Ea

Input filed1 Eb

K?H?

Sum+total Ec

public Ed

--

Java Keywords
abstract
boolean
break
byte
case
catch
char
class
continue
default
do
double
else
extends
false
final

finally
float
for
if
implements
import
instanceof
int
interface
long
native
new
null
package
private
protected

public
return
short
static
super
switch
synchronized
this
throw
throws
transient
true
try
void
volatile
while

E2-2F
K
KpublicEclassF
?Kjava? class

?Kjava?
KjavaK

(class) {
K} (class)

--

W
(class) K
K

KKjava K
W

// main method begins execution of Java application


EF6-11

public static void main( String args[ ] )


main(Java Application)

(block) mainmain

(method)
EclassFKEFmethod

main

main K
(methods) K
K

FmethodE Fvoid
EKKKKKKKKKKKKKKJ
--

method main
K

Kmethod main{
Kmethod main}

class

Kmain

System.out.println( "Welcome to Java Programming!" );


Welcome to Java Programming!

StringStringK??
K

KStandard Output Object System.out


K

System.out.println Method
Command Window
KEnter

K (Java Statement) ;
K

KStatement Terminal

--

W
E F

Kmethodclass
K method
} // end method main
} // end class Welcome1 .

--


(class)

Java

K Kawa, Forte
K


J
Javac Welcome1.Java
ESyntax Errors F

K No Errors
.Byte code Welcome1.class
K byte code

K java Welcome1

K .class

main method

Byte CodeK
Kclass

K??Forte

K Println

--


Welcome to Java Programming!

KEF

Welcome to Java Programming! W



1. // Fig. 2-3: Welcome2.java
2. // Printing a of text line with multiple statements.
3.
4. public class Welcome2 {
5.
6. // main method begins execution of Java application
7. public static void main( String args[ ] )
8. {
9.
System.out.print( "Welcome to " );
10. System.out.println( "Java Programming!" );
11. } // end method main
12. } // end class Welcome2
E2-3F

E2-1F
K

// Printing a of text line with multiple statements.

public class Welcome2 {


KWelcome2

Kmethod main
System.out.print( "Welcome to " );
System.out.println( "Java Programming!" );

--

Welcome toK


KtoJava Programming!
print println, print
Kprintln

KNewLine Character? \n?

1.
2.

// Fig. 2-4: Welcome3.java


// Printing multiple lines with a single statement.
3.

4. public class Welcome3 {


5.
6. // main method begins execution of Java application
7. public static void main( String args[ ] )
8.
9. {
10. System.out.println( "Welcome\nto\nJava\nProgramming!" );
11. } // end method main
12. } // end class Welcome3

Welcome
to
Java
Programming!
E2-4F

E2-4F
\n

--

Welcome t o Java Programming! :

// Printing multiple lines with a single statement.

public class Welcome3 {

K Welcome3

System.out.println( "Welcome\nto\nJava\nProgramming! );
K
Kn, \

K escapeE\F

\n escape sequence escape sequence


K

Kescape sequenceE2-5F

\n

\t

Kcarriage return

\r

?\?K

\\

\?

escape sequenceE2-5F

--

Microsoft internet explorer, Netscape Navigator

methods JOptionPane class


K

Welcome to Java Programming!


1. // Fig. 2-6 : Welcome4.java
2. // Printing multiple lines in a dialog box
3.
4. // Java extension packages
5. import javax.swing.JOptionPane; // import class JOptionPane
6. public class Welcome4 {
7.
8. // main method begins execution of Java application
9. public static void main( String args[ ] )
10.

11.

JOptionPane.showMessageDialog(

12.

null, "Welcome\nto\nJava\nProgramming!" );

13.
14.

System.exit( 0 ); // terminate application

15.

} // end method main

16.

} // end class Welcome4

--

E2-6F

K .message Dialog E2-6F



K
( packages )
(classes)
API Kjava Application Programming Interface (java API)
.(Extension packages) (Core packages)
Kjavax java
K
KJava.sun.com
JOptionPane E2-6F
javax.swing

// Java extension packages

Kimport

J Wimport
K(Java)import K
K(Javax)import K

KDeitelimport K

--


import javax.swing.JOptionPane; // import class JOptionPane
importimport
KJOptionPane

K API

API import
K

API

Java . sun . com/ j2se/1.3/docs/api/index.html


Java.sun.com/ j2se/1.3/docs.html
W
Kimport

JOptionPane

K javax.swing
GUI graphical user interface
K

JOptionPane.showMessageDialog(
null, "Welcome\nto\nJava\nProgramming!" );

show.Message.Dialogmethod

K??(two arguments) methodKJOptionPane


? null? (first argument)

E? null?F
K secondargument
--

JOptionPane method showMessage method


methodKStatic Method

method
class name . method name (arguments)

KE2-7F11-12
Message

OKK
KOK

E2-7F

Kmethod


K
K(Identifier)

System.exit( 0 ); // terminate application

exit method

GUI K System
K

K method method

system KCapital
--

Java.lang Java.lang

Kimportmethods

Kmethodexit(0) (argument)
K

E2-8F

1. // Fig. 2-8 : Addition.java


2. // An addition program.
3.
4. // Java extension packages
5. import javax.swing.JOptionPane; // import class JOptionPane
6.
7. public class Addition {
8.
9. // main method begins execution of Java application
10.
public static void main( String args[ ] )
11.
{
12.
String firstNumber; // first string entered by user
13.
String secondNumber; // second string entered by user
14.
int number1;
// first number to add
15.
int number2;
// second number to add
16.
int sum;
// sum of number1 and number2
17.
18.
// read in first number from user as a string
19.
firstNumber =
20.
JOptionPane.showInputDialog( "Enter first integer" );
21.
--

22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.

// read in second number from user as a string


secondNumber =
JOptionPane.showInputDialog( "Enter second integer" );
// convert numbers from type String to type int
number1 = Integer.parseInt( firstNumber );
number2 = Integer.parseInt( secondNumber );
// add the numbers
sum = number1 + number2;
// display the results
JOptionPane.showMessageDialog(
null, "The sum is " + sum, "Results",
JOptionPane.PLAIN_MESSAGE );
System.exit( 0 ); // terminate application
} // end method main
} // end class Addition

E2-8F

--

// Fig. 2-8 : Addition.java


// An addition program.
K

import
KEF

import javax.swing.JOptionPane; // import class JOptionPane

JOptionPane

K javax.swing

public class Addition {

classEF

KAddition.java Addition

} {

method main K

EWF
Kmain


String firstNumber; // first string entered by user
String secondNumber; // second string entered by user
Kdeclaration statements
--

declaration statements
Variables

method

J W identifiers

$(0 9)A-Za-zJ

J
_$ J

secondNumberfirstNumberK
E Java.lang F String

F? ;?KString
E
K


K

String firstNumber, // first string entered by user
secondNumber; // second string entered by user

14
15
16

int number1;
int number2;
int sum;

// first number to add


// second number to add
// and sum of number1 numbe

--

int number1, number2 and sum


KEKKKKKKKKKKK 200, 11, 7F

Primitive data type E2-9F

KEbitsF

EtypeF
boolean
char

ESize in bitsF

16

byte
short
int

8
16
32

long

64

float

32

double

64

ErangeF
EvalueF
True or false
to FFFF

-128 to +127
-32,768 to +32767

-2,147,483,648 to

+2,147,483,647

-9,223,372,036,854,775,808 to
+9,223,372,036,854,775,807
-3.40292347 E+38 to

+ 3.40292347 E+38

-1.79769313488231570 E+308

to
+1.79769313488231570 E+308

E2-9F

18// read in first number from user as a string


K

--

19 firstNumber =
20 JOptionPane.showInputDialog( "Enter first integer" );
methodString

KE2-10F JOptionPane.showInputDialog

E2-10F
showInputDialog(argument)

Kprompt

EnterOK

K firstNumber
22

// read in second number from user as a string



J
23 secondNumber =
24
JOptionPane.showInputDialog( "Enter second integer" );

secondNumber

// convert numbers from type String to type int
--

26 number1 = Integer.parseInt( firstNumber );


27 number2 = Integer.parseInt( secondNumber )

KfirstNumber, secondNumber

EInteger method F Integer.parseInt method

java.lang Integer K
number1, Kimport

Knumber2

WDouble
variable1= Double.parseDouble (variable2)
Kdouble , String variable1, variable2

// add the numbers


sum = number1 + number2;
?H? number1, number2
K?Z? sum

number2 number1

WEHFKsum
number1, number2

K
--

JOptionPane.showMessageDialog(
null, "The sum is " + sum, "Results",
JOptionPane.PLAIN_MESSAGE );

JOptionPane.showMessageDialog method
J W
(Four arguments)
K null J
J
sum?+ ? "The sum is " + sum
K"The sum is "
?+ ?
KEF
J
K( 2-8) " ) Results"
K JOptionPane.PLAIN_MESSAGE J

E2-11F

JOptionPane. ERROR_
MESSAGE

JOptionPane.
INFORMATION_ MESSAGE

JOptionPane. WARNING_
MESSAGE

JOptionPane. QUESTION_
MESSAGE

JOptionPane. PLAIN_
MESSAGE

E2-11F
--

Assignments
=
W

x1
x1.5

W
x=1;

radius = 1.0 ;
a = A ;

aA
x=1.0W

intx

Kdouble

K1 = x

W
area = radius * radius * 3.14159 ;

x=x+3;
x + = 3

--

c=c+7
c+=7
d=d-4
d-=4
e=e*5
e*=5
f=f/3
f=f/3
g=g%9
g%=9
E12F

+=
-=
*=
/=
%=


- -+ +
c + ++ +

c + = 1;
c = c + 1;

1a

++a

++a

++

--b

--

b--

--

a

a

HH

1a
1b
b

a

E13F
--

K
1. // Fig. 2.14 Increment.java
2. // Preincrementing and postincrementing
3.
4. public class Increment {
5. public static void main( String args[] )
6. {
7. int c;
8.
9. c = 5;
10. System.out.println( c ); // print 5
11. System.out.println( c++ ); // print 5 then postincrement
12. System.out.println( c ); // print 6
13.
14. System.out.println();
// skip a line
15.
16. c = 5;
17. System.out.println( c ); // print 5
18. System.out.println( ++c ); // preincrement then print 6
19. System.out.println( c ); // print 6
20. }
21. }

E2.14F

--


10

5c

System.out.println( c ); // print 5

11

system . out . println( c + + );


55c
c = 6c

12

6c

System.out.println( c ); // print 6

14

System.out.println ( );

16

c = 5 ;

c5

17

5c

System.out.println( c ); // print 5

18

System.out.println( ++c ); // preincrement then print 6


6 c

6c19

System.out.println( c ); // print 6
--

f+7
f-7
b*m


f+7
H
f-7
J
bm

x/y

r%s

r mod s

E2.15F

KEFELFEGF

7 / 4

K317 / 5

EF

37 % 4
217 % 5

KEF

syntax errorEF

--

a * (b+c)a

J
K

J
KKKK

EFJ
K
K

J
K


y=mx+b
z= pr % q + w/x
y=x +bx +c

y=m*x +b;

Km*x
z = p * r % q + w / x - y ;
J
612435

y = a * x * x + b * x + c

J
612435
--

W
a=2 , b=3 , c=7 , x=5

2 * 5 = 10

10 * 5 = 50

3 * 5 = 15

50 + 15 = 65

y = 2 * 5 * 5 + 3 * 5 + 7;
y = 10 * 5 + 3 * 5 + 7;
y = 50 + 3 * 5 + 7;
y = 50 + 15 + 7;
y = 65 + 7;

65 + 7 = 72

y = 72;


Y = (a * x * x) + ( b * x ) + c ;

--


java

&&

And
Or

||

Not

>

E2.16F
falsetrue

.false true

.truetrue &&
.false&&

java
.
.

||true&&

falsetrue.true
.java

.>

!atruea
java.false

..a=!a

--

1. // Fig. 2.17 : Logical.java


2. // Logical Operator
3. public class Logical
4. {
5. public static void main ( String [] args )
6. {
7. //declare & initialize test variable
8. boolean a = true , b = false ;
9. boolean c1 =(a && a);
// test if both are true
10. boolean c2 =(a && b);
11. boolean c3 =(b && b);
12.
13. boolean c4 =(a || a) ;
//test if either is true
14. boolean c5 =(a || b);
15. boolean c6 =(b || b);
16.
17. boolean c7 = !a;
// invert initial values
18. boolean c8 = !b;
19.
20. // display the results
21. System.out.println (and:\n1:+c1+2:+c2+3:+c3);
22. System.out.println (or:\n4:+c4+5:+c5+6:+c6);
23. System.out.println (not:\n7:+c7+8:+c8);
24. }
25. }

E2.17F
--


true ba boolean 8
Kfalse

9,10,11

&&c1,c2,c3

13,14,15
||c4,c5,c6

17,18

> c7,c8
21,22,23

.c1,c2,c3,c4,c5,c6,c7,c8

--

W
if
K

Kifif
Kif W

if

yx

x==y

==

yx

x!=y

!=

E2.18F

>

yx

x>y

>

yx

x<y

<

<

yx

x>=y

>=

yx

x<=y

<=

E2.19F
W

!= >= <===>=< ===!=

Ksyntax error

syntax error =! =>=<

if6
K
--

if Knumber1number2
K

K
1. // Fig. 2.20: Comparison.java
2. // Compare integers using if structures, relational operators
3. // and equality operators.
4.
5. // Java extension packages
6. import javax.swing.JOptionPane;
7.
8. public class Comparison {
9.
10. // main method begins execution of Java application
11. public static void main( String args[] )
12. {
13. String firstNumber;
14. String secondNumber;
15. String result;
16. int number1;
17. int number2;
18.
19. // read first number from user as a String
20. firstNumber =
21. JOptionPane.showInputDialog( "Enter first integer:" );
22.
23. // read second number from user as a String
24. secondNumber =
25. JOptionPane.showInputDialog( "Enter second integer:" );
26.
27. // convert numbers from type String to type int
28. number1 = Integer.parseInt( firstNumber );
29. number2 = Integer.parseInt( secondNumber );
30.
31. // initialize result to empty String
32.
33. result = "";
34. if ( number1 == number2 )
35. result = number1 + " == " + number2;
36.
37. if ( number1 != number2 )
38. result = number1 + " != " + number2;
39.
--

40. if ( number1 < number2 )


41. result = result + "\n" + number1 + " < " + number2;
42.
43. if ( number1 > number2 )
44. result = result + "\n" + number1 + " > " + number2;
45.
46. if ( number1 <= number2 )
47. result = result + "\n" + number1 + " <= " + number2;
48.
49. if ( number1 >= number2 )
50. result = result + "\n" + number1 + " >= " + number2;
51.
52. // Display results
53.
54. JOptionPane.showMessageDialog(
55. null, result, "Comparison Results",
56. JOptionPane.INFORMATION_MESSAGE );
57. System.exit( 0 ); // terminate application
58.
59. } // end method main
60.
61. } // end class Comparison

--

E2.20F
--


8 Comparison

public class Comparison {

5911 main

String firstNumber;
String secondNumber;
String result;
int number1;
int number2;

1713

main

String

firstNumber
secondNumber
result

int
number1

number2


String firstNumber , secondNumber , result;
firstNumber =
JOptionPane.showInputDialog( "Enter first integer:" );

--

20-21

firstNumber
string

24-25

secondNumber =
JOptionPane.showInputDialog( "Enter second integer:" );

StringsecondNumber

28-29

number1 = Integer.parseInt( firstNumber );


number2 = Integer.parseInt( secondNumber );
int String

firstNumber 28
number1
secondNumber 29
number2 .
33
result = "";
result empty string

method
:K

method:
syntax error
34-35

if ( number1 == number2 )
result = number1 + " == " + number2;
ififif

if

(;)
. 34
--

number2number1
result = result + number1 + == + number2;

result + number1 + == + number
Kresult
number2number1

stringstring
string concatenation

number2number1
result.
:
syntax errorif(==)(=)

if(number1 == number2);

--

EF

KLL

J J J J J J J J J J J J J J J J J J J J J J J J J J J J J J J
J J J J J J J J J J J J J J J J J J J J J J J J J J J J J J J

EF

J J J J J J J J J J J J J J J J J J J J J J J J J J J J J J J
J J J J J J J J J J J J J J J J J J J J J J J J J J J J J J J

EF* , / , %, + , - J
J J J J J J J J J J J J J J J J J J J J J J J J J J J J J J J

J J J J J J J J J J J J J J J J J J J J J J J J J J J J J J J

EF stringint Integer.parseInt J
J J J J J J J J J J J J J J J J J J J J J J J J J J J J J J J

J J J J J J J J J J J J J J J J J J J J J J J J J J J J J J J

--

W
integerString

age

K value

J J J J J J J J J J J J J J J J J J J J J J J J J J J J J
J J J J J J J J J J J J J J J J J J J J J J J J J J J J J

J J J J J J J J J J J J J J J J J J J J J J J J J J J J J
10number J

The variable number is not equal to 10


J J J J J J J J J J J J J J J J J J J J J J J J J J J J J

J J J J J J J J J J J J J J J J J J J J J J J J J J J J J
J J J J J J J J J J J J J J J J J J J J J J J J J J J J J

WE
if ( c < 7 );
JoptionPane.showMessageDialog (null, c is less than 7);
J J J J J J J J J J J J J J J J J J J J J J J J J J J J J
J J J J J J J J J J J J J J J J J J J J J J J J J J J J J

J J J J J J J J J J J J J J J J J J J J J J J J J J J J J

if ( c => 7 )
JoptionPane.showMessageDialog (null,c is equal or greater than
7);
J J J J J J J J J J J J J J J J J J J J J J J J J J J J J

J J J J J J J J J J J J J J J J J J J J J J J J J J J J J
--

J
K?is larger ?

K? these number are equal ?

J
K

J
K

= 3.14159

Math. PIW
3.14159

5 J
K

KW

J
K

2W
K20 2

J
K

5 J
K
4 2 3 3 9 42339W
--

W
code

W
W
K

ifif/elseif K
switch K

K
while K

do/while K
for K

K
K
W
100


W

- -

Kif

if

If (number1 == number2 )
result = result+ number1 == number2 ;
if selection structure if

if10060 :
If (studentGrade > = 60 )
System.out.println ( passed );
( passed )
60

grade > 60

true

Print "Passed"

false

ifE3-1F

( passed )J

KJ

- -

if \else

false
Print "Failed"

grade > 60

true

Print "Passed"

if/elseE3-2F

if \ else

if ( studentGrade > = 60 )
System.out.println ( passed );
else
System.out.println ( failed );
60

failed 60passed

(? : )
( ?: )if \ else
if \ else
= 60 ? passed : failed ) ; >System.out.println (studentGrade
else:if?
- -

if \ else
if \ else

b 90a:
6069 d7970c80

:f

if (studentGrade >= 90 )
System.out.println ( a );
else if ( studentGrade >= 80 )
System.out.println ( b );
else if ( studentGrade >= 70 )
System.out.println ( c );
else if ( studentGrade >= 60 )
System.out.println ( d );
else
System.out.println ( f );
.

{ }

you must take this course again f

else
{

System.out.println ( f );
System.out.println ( you must take this course again );
}

:

syntax error

syntax error

compile
you must take this course f60

- -

logical error ( ; )
syntax error ifif

switch

if/else switch

Wswitch

switch (switch-expression)
{ case value1: statement(s)1;break;
case value2: statement(s)2;break;

case valueN: statement(s)N;break;


default :
statement(s)- for default;
}
E int short byte char Fswitch expression
switch value1,value2,,valueN
expression
switch valuestatement(s)EF
switchbreakexpression

default

Kswitch
case a

case b

true

true

case a action ( s )

break

case b action ( s )

break

false

.
.
.

case z

true

case z action ( s )

false

break

default action ( s )

switchE3-3F
- -

1. // Fig. 3.4 : Month.java


2. // Class Month program with switch statements.
3. // Java extension packages
4. import javax.swing.JOptionPane;
5.
6. public class Month {
7. // main method begins execution of Java application
8. public static void main( String args[] )
9. {
10. int month; // number of month number entered
11. String input; // month number typed by user
12. String name;
// name of month
13.
14. // Processing phase
15. // prompt for input and read Month number from user
16. input = JOptionPane.showInputDialog(
17. "Enter Month number" );
18. // convert grade from a String to an integer
19. month = Integer.parseInt( input );
20. switch ( month )
21. {
22. case 1:name="JAN";break;
23. case 2:name="FEB";break;
24. case 3:name="MAR";break;
25. case 4:name="APR";break;
26. case 5:name="MAY";break;
27. case 6:name="JUN";break;
28. case 7:name="JUL";break;
29. case 8:name="AUG";break;
30. case 9:name="SEP";break;
31. case 10:name="OCT";break;
32. case 11:name="NOV";break;
33. case 12:name="DEC";break;
34.
35. default :name=" invalid Month number ";
36. }
37.
38. // display name of month number
39. JOptionPane.showMessageDialog( null,
40. "the Month is " + name ,
41. "Class Month", JOptionPane.INFORMATION_MESSAGE );
42.
43. System.exit( 0 ); // terminate application
44.
45. } // end method main
46.
- -

switchE3-4F


switch
switch
case 2:
Kname FEB name="FEB";
Kswitchbreak;

35
default :name= invalid Month number ;
Kname
Kswitch}

JOptionPane.showMessageDialog( null,"the Month is " + name ,
"Class Month", JOptionPane.INFORMATION_MESSAGE );

- -

while

true
i<= 3

Print "Hello world"

false

whileE3-5F

hello world

int i= 1 ;
While ( i < = 3 )
{
System.out.println ( hello world ) ;
i+=1;
}
while
: J

i: J
i: J

- -

int sum = 0 ;
int i = 1
While ( i < = 10 )
{
sum + = i ;
i+=1;
}
System.out.println ( sum )

while:

i
.

Whilewhile

reserved keywords
if else while -
.

- -


1. // Fig. 3.6: Average1.java
2. // Class average program with counter-controlled repetition.
3. // Java extension packages
4. import javax.swing.JOptionPane;
5.
6. public class Average1 {
7. // main method begins execution of Java application
8. public static void main( String args[] )
9. {
10. int total,
// sum of grades input by user
11. gradeCounter, // number of grades entered
12. gradeValue, // grade value
13. average;
// average of all grades
14. String grade;
// grade typed by user
15.
16. // Initialization Phase
17. total = 0;
// clear total
18. gradeCounter = 1; // prepare to loop
19.
20. // Processing Phase
21. while ( gradeCounter <= 10 ) { // loop 10 times
22.
23. // prompt for input and read grade from user
24. grade = JOptionPane.showInputDialog(
25. "Enter integer grade: " );
26. // convert grade from a String to an integer
27. gradeValue = Integer.parseInt( grade );
28.
29. // add gradeValue to total
30. total = total + gradeValue;
31.
32. // add 1 to gradeCounter
33. gradeCounter = gradeCounter + 1;
34.
35. } // end while structure
36.
37. // Termination Phase
38. average = total / 10; // perform integer division
39.
40. // display average of exam grades
41. JOptionPane.showMessageDialog( null,
42. "Class average is " + average, "Class Average",
43. JOptionPane.INFORMATION_MESSAGE );
44. System.exit( 0 ); // terminate the program
45. } // end method main
46. } // end class Average1
- -

whileE3-6F
- -

import javax.swing.JOptionPane ;

JOptionPane

6 public class Averagel {

mainAveragel
1410(458) main


total , gradeCounter , gradeValue , average
integer
String grade

gradegradeValue
.
main
.main
K

18,17

total = 0;
// clear total
gradeCounter = 1; // prepare to loop
gradeCounter , total

.10
21

while ( gradeCounter < = 10 ) {


gradeCounterwhile
.10

K {
- -

variable may not have been initialized

gradeCounter
24gradeCounter
25

grade = JOptionPane.showInputDialog("Enter integer grade: " );

27gradeValue grade
gradeValue = Integer . parseInt ( grade ) ;

java.langInteger
.import

30

total = total + gradeValue ;

gradeCounter = gradeCounter + 1;

total
33
35

while
}
10gradeCounter 3521
38
average = total / 10;
.10 total
- -

4241

43 JOptionPane.showMessageDialog( null, "Class average is " + average,


"Class Average", JOptionPane.INFORMATION_MESSAGE );

10 =

while ( gradeCounter < = 10 )
.10


while ( gradeCounter ! = - 1 )
{
//
}


1. // Fig. 3.7: Average2.java
2. // Class average program with sentinel-controlled repetition.
3. // Java extension packages
4. import javax.swing.JOptionPane;
5. public class Average2 {
6. // main method begins execution of Java application
7. public static void main( String args[] )
8. {
9. int gradeCounter, // number of grades entered
10. gradeValue, // grade value
11. total;
// sum of grades
12. double average; // average of all grades
13. String input;
// grade typed by user

- -

14. // Initialization phase


15. total = 0;
// clear total
16. gradeCounter = 0; // prepare to loop
17. // Processing phase
18. // prompt for input and read grade from user
19. input = JOptionPane.showInputDialog(
20. "Enter Integer Grade, -1 to Quit:" );
21. gradeValue = Integer.parseInt( input );
22. while ( gradeValue != -1 ) {
23. total = total + gradeValue;
24. gradeCounter = gradeCounter + 1;
25.
26. // prompt for input and read grade from user
27. input = JOptionPane.showInputDialog(
28. "Enter Integer Grade, -1 to Quit:" );
29.
30. // convert grade from a String to an integer
31. gradeValue = Integer.parseInt( input );
32. }
33. if ( gradeCounter != 0 ) {
34. average = (double) total / gradeCounter;
35.
36. // display average of exam grades
37. JOptionPane.showMessageDialog( null,
38. "Class average is " + average,
39. "Class Average", JOptionPane.INFORMATION_MESSAGE );
40. }
41. else
42. JOptionPane.showMessageDialog( null,
43. "No grades were entered", "Class Average",
44. JOptionPane.INFORMATION_MESSAGE );
45. System.exit( 0 ); // terminate application
46. } // end method main
47. } // end class Average2

- -

whileE3-7F


21J 19

input = JOptionPane.showInputDialog(
"Enter Integer Grade, -1 to Quit:" );
gradeValue = Integer.parseInt( input );

while

while (gradeValue ! = -1 )
{
//
}

J
23gradeValue ! = -1
total = total + gradeValue ;
total

- -

24
gradeValue = gradeValue + 1 ;
input = JOptionPane.showInputDialog(
"Enter Integer Grade, -1 to Quit:" );

31J 27

// convert grade from a String to an integer


gradeValue = Integer.parseInt( input );
Kint

4033

if ( gradeCounter != 0 ) {
average = (double) total / gradeCounter;
JOptionPane.showMessageDialog( null,
"Class average is " + average,
"Class Average", JOptionPane.INFORMATION_MESSAGE );
}
gradeCounter

(double )

intgradeCounter , total
.(double )

K
44J 42

JOptionPane.showMessageDialog (null , no grades were entered


( class average , JOptionPane.INFORMATION_MESSAGE ) ;

45

System.exit ( 0 ) ;

JOptionPane
- -

W
while

.while

doLwhile
while dowhile
:

Do
{
//

} while ( ) ;

action (s)

true

condition

false

do/whileE3-8F

true while
while.false

do Lwhile

while false
K
do/while

- -


1. import javax.swing.JOptionPane ;
2. public class TestDo {
3. public static void main ( String [ ] args )
4. {
5. String input ;
6. int data ;
7. int sum = 0 ;
8. do
9. {
10. input = JOptionPane.showInputDialog ( " enter number " ) ;
11. data =Integer.parseInt ( input ) ;
12. sum += data ;
13. } while ( data != 0 ) ;
14. JOptionPane.showMessageDialog ( null , " the sum is " + sum ) ;
15. System.exit ( 0 ) ;
16. }
17. }

do/whileE3-9F
- -

.
do Lwhile

data =Integer.parseInt ( input ) ;

intString

sum += data ;

sum

} while ( data ! = 0 ) ;
}


JOptionPane.showMessageDialog ( null , the sum is + sum ) ;
sum

System.exit ( 0 )
JoptionPane

KW

- -

for

for(; ;)
{
//
}

i = 0.01f

true
i <= 1.0f

false

sum = sum + i

i = i+1

forE3-10F
1. class TestSum
2. {
3. public static void main ( String [ ] args )
4. {
5. float sum =0;
6. for ( float i = 0.01f ; i <= 1.0f ; i = i + 0.01f )
7. sum += i ;
8. System.out.println ( " the summation is " + sum ) ;
9. }
10. }

forE3-11F
- -


1.00.01

5
float sum =0;
floatsum
6

for ( float i = 0.01f ; i <= 1.0f ; i = i + 0.01f )

:for

float i = 0.01f

0.01

i < = 1.0f

1.0i

.1.0

i = i + 0.01f

0.01i

sum += i ;

sum i
System.out.println ( the sum is + sum ) ;

sum

0.01 + 0.02 + 0.03 + ----------- + 0.1

- -

for
11001J
= 100 ; i + + )<for ( int f = 1 ; i
7777 J
= 77 ; i + = 7 )<for ( int i = 1 ; i
2220J
= 2 ; i - = 2 )>for ( int i = 20 ; i
20 , 17 , 14 ,11 , 8 , 5 , 2 J
= 20 ; i + = 3 )<for ( int i= 2 ; i
11,22, 33 , 44 , 55 , 66 , 77 , 88 , 99J
= 0 ; 0 - = 11 )>for ( int j = 99 ; j


for

Ksyntax error

for

- -

1. class TestMultable
2. {
3. public static void main ( string [ ] args )
4. {
5. // display the title
6. System.out.println ( "
multiplication table " ) ;
7. System.out.println ( " ---------------------------------------------- " );
8. // display the number title
9.
10. System.out.print ( " | " ) ;
11. for ( int j=1 ; j <= 9; j ++ )
12. System.out.print ( " " + j ) ;
13. System.out.println ( " " ) ;
14.
15. // print table body
16. for ( int i = 1 ; i <= 9 ; i ++ )
17. {
18. System.out.print ( i + " | " ) ;
19. for ( int j = 1 ; j <= 9 ; j ++ )
20. {
21.
22. // display the product and align properly
23.
24. if ( i * j < 10 )
25. System.out.print ( " " + i* j ) ;
26. else
27. System.out.print ( " " + i * j ) ;
28. }
29. System.out.println ( " " ) ;
30. }
31. }
32. }

E3-12F
- -


System.out.println ( "

multiplication table " ) ;


multiplication table

System.out.println ( " ---------------------------------------------- " );


J J J J J J J J J J J J J

for ( int j=1 ; j <= 9; j ++ )


System.out.print ( " " + j ) ;

91


.jifor
jj*ii

9 1

if ( i*j < 10 )
10jiif

System.out.print ( + i*j ) ;

.i*j
10i*j
- -

else
System.out.print ( + i*j ) ;

System.out.println ( ) ;


break continue

break

switch , do/while , for , while

break
.switch

break

- -


1.
2.
3.
4.
5.
6.
7.

// Fig. 3.13: BreakTest.java


// Using the break statement in a for structure
// Java extension packages
import javax.swing.JOptionPane;
public class BreakTest {

8. // main method begins execution of Java application


9. public static void main( String args[] )
10. {
11. String output = "";
12. int count;
13.
14. // loop 10 times
15. for ( count = 1; count <= 10; count++ ) {
16.
17. // if count is 5, terminate loop
18. if ( count == 5 )
19. break; // break loop only if count == 5
20.
21. output += count + " ";
22.
23. } // end for structure
24.
25. output += "\nBroke out of loop at count = " + count;
26. JOptionPane.showMessageDialog( null, output );
27.
28. System.exit( 0 ); // terminate application
29.
30. } // end method main
31.
32. } // end class BreakTest

breakE3-13F
- -

:
for18if

195countif

break ;

25
output + = in broke out of loop at count = + count ;
countoutput
26
JOptionPane.showMessageDialog ( null , output ) ;

continuecontinue

breakbreak
continuecontinue
.

continue5 count

29
Output + = count + ;
6count
breakcontinue

- -


1. // Fig. 3.14: ContinueTest.java
2. // Using the continue statement in a for structure
3. // Java extension packages
4. import javax.swing.JOptionPane;
5.
6. public class ContinueTest {
7.
8. // main method begins execution of Java application
9. public static void main( String args[] )
10. {
11. String output = "";
12.
13. // loop 10 times
14. for ( int count = 1; count <= 10; count++ ) {
15. // if count is 5, continue with next iteration of loop
16. if ( count == 5 )
17. continue; // skip remaining code in loop
18. // only if count == 5
19. output += count + " ";
20. } // end for structure
21. output += "\nUsed continue to skip printing 5";
22. JOptionPane.showMessageDialog( null, output );
23. System.exit( 0 ); // terminate application
24. } // end method main
25. } // end class ContinueTest

continueE3-14F
- -

continue break
break

switchdo/whilefor while

do/whilefor whilelabeled break


switch
F

Stop : {
//

}
labeled break
switchdo/whilefor while

- -


1. // Fig. 3.15: BreakLabelTest.java
2. // Using the break statement with a label
3.
4. // Java extension packages
5. import javax.swing.JOptionPane;
6.
7. public class BreakLabelTest {
8.
9. // main method begins execution of Java application
10. public static void main( String args[] )
11. {
12. String output = "";
13.
14. stop: { // labeled block
15.
16. // count 10 rows
17. for ( int row = 1; row <= 10; row++ ) {
18. // count 5 columns
19. for ( int column = 1; column <= 5 ; column++ ) {
20.
21. // if row is 5, jump to end of "stop" block
22. if ( row == 5 )
23. break stop; // jump to end of stop block
24.
25. output += "* ";
26.
27. } // end inner for structure
28.
29. output += "\n";
30.
31. } // end outer for structure
32.
33. // the following line is skipped
34. output += "\nLoops terminated normally";
35.
36. } // end labeled block
37.
38. JOptionPane.showMessageDialog(
39. null, output,"Testing break with a label",
40. JOptionPane.INFORMATION_MESSAGE );
41.
42. System.exit( 0 ); // terminate application
43.
44. } // end method main
45.
46. } // end class BreakLabelTest
- -

breakE3-15F

F3614

EW

14

stop: { // labeled block

for

output += "\nLoops terminated normally";


Loop terminated normallyoutput.

5row

- -


if ( row == 5 )
break stop; // jump to end of stop block
for for


K
rowF4for W
for E5
K
continue
labeled continuecontinue

K structurelabeled repetition
K

1. // Fig. 3.16: ContinueLabelTest.java
2. // Using the continue statement with a label
3.
4. // Java extension packages
5. import javax.swing.JOptionPane;
6.
7. public class ContinueLabelTest {
8.
9. // main method begins execution of Java application
10. public static void main( String args[] )
11. {
12. String output = "";
13.
14. nextRow: // target label of continue statement
15.
16. // count 5 rows
17. for ( int row = 1; row <= 5; row++ ) {
18. output += "\n";
19.
20. // count 10 columns per row
21. for ( int column = 1; column <= 10; column++ ) {
22.
23. // if column greater than row, start next row
24. if ( column > row )
- -

25. continue nextRow; // next iteration of


26.
27. // labeled loop
28.
29. output += "* ";
30.
31. } // end inner for structure
32.
33. } // end outer for structure
34.
35. JOptionPane.showMessageDialog(
36. null, output,"Testing continue with a label",
37. JOptionPane.INFORMATION_MESSAGE );
38.
39. System.exit( 0 ); // terminate application
40.
41. } // end method main
42.
43. } // end class ContinueLabelTest

continue E3-16F

- -


switch default

switchdefaultbreak

a < b x > y (x > y && a < bF_

_
.


sumfor991_
.Count

while20 1_

x

x % 5W

for_

- -

1 public class printing {


2
3
public static void main ( String args [ ] )
4
{
5
for ( int i = 1; i <= 10; i++ ) {
6
7
for ( int j = 1; j <= 5; j++ )
8
System.out.print ('@' );
9
10
System.out.println ( );
11
12
}
13
14
}
15
16 }

J 4

for ( i = 1; i <= 5; i++ ) {


for ( j = 1; j <= 3; j++ ) {
for ( k = 1; k <= 4; k++ ) {
System.out.print ( ' * ' );
System.out.println ( );
}
System.out.println ( );
}
J
K

- -

151J
K

8!F8J
K81 E8

51
K

W J
(a)

(b)

*
**
***
****
*****
******
*******
********
*********
**********

(c)

**********
*********
********
*******
******
*****
****
***
**
*

=4-

4
7

W
(d)

**********
*********
********
*******
******
*****
****
***
**
*

*
**
***
****
*****
******
*******
********
*********
**********

J
-

4
5

+ 4+
3

4
9

4
11

+ .....


3.14159
- -

1 public class Mystery2 {


2
3
public static void main ( string args [ ] )
4
{
5
int count = 1;
6
7
while ( count <= 10 ) {
8
System.out.println (
9
count % 2 = = 1 ? "****" : "++++++++" );
10
++count;
11
}
12
}
13 }

1 public class Mystery3 {


2
3
public static void main ( String args [ ] )
4
{
5
int row = 10, column;
6
7
while ( row >= 1 ) {
8
column = 1;
9
10
while ( column <= 10 ) {
11
System.out.print (row % 2 = = 1 ? "<" : ">" );
12
++column;
13
}
14
15
--row;
16
System.out.println( );
17
}
18
}
19 }
- -

JDKJava 2 Software Development KitW


K1.4

IDEIntegrated Development EnvironmentW


K

Sun Forte

F Microsystems

JDKIDEE
KJDKForte

Forte

Forte J

EA-1F
- -

New fileJ

NewEA-2F
K

EA-2F

TemplateJ

EA-3F

KKK

Classes

Main
K

Name

EA-3F
Finish Next
EA-4F

Yes

EA-4F
- -

EA-5F


Main
K

Main

EA-5F

CompilationJ

F9CompileBuildEA-6F


EA-6F

Test Error CompilingTest


EA-6FK

EA-6F
- -

Finished Test
Kclass

Shift+f10BuildBuildBuild

EA-7F

EA-7)

F6BuildExecute

EA-8F

EA-9FOutput Window

EA-9F

JApplet
Classes
EA-10F

- -

JApplet

SwitchTest

Finish
EA-10F

EA-11F

EA-11F

Yes

EA-12F

EA-12F
- -

Buildcompile
HTMLForte
appletviewer

WEA-13)
1. // Fig. A.13: SwitchTest.java
2. // Drawing lines, rectangles or ovals based on user input.
3.
4. // Java core packages
5. import java.awt.Graphics;
6.
7. // Java extension packages
8. import javax.swing.*;
9.
10. public class SwitchTest extends JApplet {
11. int choice; // user's choice of which shape to draw
12.
13. // initialize applet by obtaining user's choice
14. public void init()
15. {
16. String input; // user's input
17.
18. // obtain user's choice
19. input = JOptionPane.showInputDialog(
20. "Enter 1 to draw lines\n" +
21. "Enter 2 to draw rectangles\n" +
22. "Enter 3 to draw ovals\n" );
23.
24. // convert user's input to an int
25. choice = Integer.parseInt( input );
26. }
27.
28. // draw shapes on applet's background
29. public void paint( Graphics g )
30. {
31. // call inherited version of method paint
32. super.paint( g );
33.
34. // loop 10 times, counting from 0 through 9
35. for ( int i = 0; i < 10; i++ ) {
36.
37. // determine shape to draw based on user's choice
38. switch ( choice ) {
39.
40. case 1:

- -

41. g.drawLine( 10, 10, 250, 10 + i * 10 );


42. break; // done processing case
43.
44. case 2:
45. g.drawRect( 10 + i * 10, 10 + i * 10,
46. 50 + i * 10, 50 + i * 10 );
47. break; // done processing case
48. case 3
49. g.drawOval( 10 + i * 10, 10 + i * 10,
50. 50 + i * 10, 50 + i * 10 );
51. break; // done processing case
52. default:
53. g.drawString( "Invalid value entered",
54. 10, 20 + i * 15 );
55.
56. } // end switch structure
57.
58. } // end for structure
59.
60. } // end paint method
61.
62. } // end class SwitchTest

- -

EA-13F

- -

141


Applets
Application
Applet

Applet container
Java 2 Software Development Kit

KApplet Viewer

KNetscape 6

Java Plug-inW

K(Converter)

1. // Fig. B.1: WelcomeApplet.java


2. // A first applet in Java.
3.
4. // Java core packages
5. import java.awt.Graphics; // import class Graphics
6.
7. // Java extension packages
8. import javax.swing.JApplet; // import class JApplet
9.
10. public class WelcomeApplet extends JApplet {
11.
12. // draw text on applets background
13. public void paint( Graphics g )
14. {
15. // call inherited version of method paint
16. super.paint( g );
17.
18. // draw a String at x-coordinate 25 and y-coordinate 25
19. g.drawString( "Welcome to Java Programming!", 25, 25 );
20.
21. } // end method paint
22.
23. } // end class WelcomeApplet
- -

141

X
Applet

Appletviewer



(0,0)

.
x

y



...
.

( 25, 25)

EB.1F

19
Welcome to Java Programming!



2 1

// Fig. B.1: WelcomeApplet.java


// A first applet in Java.
//

import java.awt.Graphics; // import class Graphics

classes

import5Kpackages
Graphics Kjava.awtGraphics
KKKK
- -

141

Import javax.swing.JApplet; // import class JApplet

JAppletimport
KKjavax.swing

java.appletApplet W

extends

Object
10JavaApplet
Public class WelcomeApplet extends JApplet {

{KWelcomeApplet
23
SuperclassJApplet

subclassWelcomeApplet

WelcomApplet

KWelcome To Java Programming !

JApplet W

200W

K200

- -

141

13

Public void paint( Graphics g )

paint

(init , start , paint)

start initW
Kpaint

paint

14 J 13

paint
JoptionPane showMessageDialog

paint


gGraphics

KGraphics paint
paintpublic

public

16

super.paint( g );
JApplet
g.drawString( "Welcome to Java Programming!", 25, 25 );

- -

19

141

gGraphicsdrawstring
K

drawString
Welcome To Java Progamming !

K0 , 025 ,25

HTML compilation

.htm.htmlHTMLappletviewer

EB-2FKHTML
KHTML

1.
2.
3.
4.

<html>
<applet code = "WelcomeApplet.class" width = "300" height = "45">
</applet>
</html>

HTMLEB-2F
WelcomeApplet.class2

EF

HTMLW
K

- -

141



Java plug-in HTML converter
HTML
K

HTMLConverter.bat
WEB-3FK

HTML

ConverterEB-3F
- -

References

WW



K&K

WW

Wilson, Thomas C and Shortt Joseph, Pascal from begin to end, J

Deitel and Deitel , Java How to Program, Prentice Hall, 2002 J


Liang Y. Daniel, " Introduction to Java Programming", Que J
E&T, 1999

- -

K K K K K K K K K K K K K K K K K K K K K K K K K

K K K K K K K K K K K K K K K K K K K K K K K K K K K
K K K K K K K K K K K K K K K K K K K K K K K W

K K K K K K K K K K K K K K K K K K K K K K K W
K K K K K K K K K K K K K K K K K K K K K K

K K K K K K K K K K K K K K K K K K K K K K
K K K K K K K K K K K K K K K K K K K K K

K K K K K K K K K K K K K K K K K K K K K K

K K K K K K K K K K K K K K K K K K K K K K K K

K K K K K K K K K K K K K K K K K K K K K K K
K K K K K K K K K K K K K K K K

K K K K K K K K K K K K K K K K K K K K

K K K K K K K K K K K K K K K K K K K K K K K K

K K K K K K K K K K K K K K K K K K K K

K K K K K K K K K K K K K K K K K K K K

K K K K K K K K K K K K K K K K K K K K K K K K

K K K K K K K K K K K K K K K K K K K K K K
K K K K K K K K K K K K K K K K K K K K K
K K K K K K K K K K K K K K K K K K K K

K K K K K K K K K K K K K K K K K K

K K K K K K K K K K K K K K K K K K K K K K

K K K K K K K K K K K K K K K K K K K K K K
K K K K K K K K K K K K K K K K K K K K

K K K K K K K K K K K K K K K K K K K K K
K K K K K K K K K K K K K K K K K K K

K K K K K K K K K K K K K K K K K K K K

K K K K K K K K K K K K K K K K K K K
K K K K K K K K K K K K K K K K K K

K K K K K K K K K K K K

K K K K K K K K K K K K K K K K K K K K K K K K

K K K K K K K K K K K K K K K K K K K W
K K K K K K K K K K K K K K K K K K K K
K K K K K K K K K K K K K K K K K K K K

K K K K K K K K K K K K K K K K K K K K K K

K K K K K K K K K K K K K K K K K K K K K K

K K K K K K K K K K K K K K K K K K K K K K

K K K K K K K K K K K K K K K K K K K K K

K K K K K K K K K K K K K K K K K

K K K K K K K K K K K K K K K K K K K K K

K K K K K K K K K K K K K K K K K
K K K K K K K K K K K K K K K K K K K K K

K K K K K K K K K K K K K K W
K K K K K K K K K K K K K K K K K K K K K K K K

K K K K K K K K K K K K K K K K K K W
K K K K K K K K K K K K K K K K K K K
K K K K K K K K K K K K K K K K K K K K K

if/ else

K K K K K K K K K K K K K K K K K K K K K K K E?WF

K K K K K K K K K K K K K K K K K K K

if/ else

K K K K K K K K K K K K K K K K K K K switch

K K K K K K K K K K K K K K K K K

K K K K K K K K K K K K K K K K K

while

do- while

K K K K K K K K K K K K K K K K K K K K

for

K K K K K K K K K K K K K K K K K K K K for
K K K K K K K K K K K K K K K K K K

break, continue

K K K K K K K K K K K K K K K K

break, continue

K K K K K K K K K K K K K K K K

K K K K K K K K K K K K K K K K K K K K

Forty??

K K K K K K K K K K K K K K K K K K K K K K K K
K K K K K K K K K K K K K K K K K K K K K K K K

??


EF
GOTEVOT appreciates the financial support provided by BAE SYSTEMS


]<gj]<]<j<^]<]

??? ?
K


]<gj]<]<j<^]<]

W
K

W
W
K J

K J
K J

K J
K J

K J
K J

K J
W
K

K W

W
K
K

W
K

--

K
KK

W
E F

K(Index)

F
K(Variable)E
WK
1. int array1[];
2. array1[] = new int[9];

intint array1EF
F EFK

K E
W

int array1[] = new int[9];

int[] array1 = new int[9];

WE-Farray1

--

array1

Index

8 6

0
0

0
1

0
2

0
3

0
4

0
5

E-F

WF
k array1[k]

nKE

Kn-1

(Default Value)

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

String
Boolean

0
0.0
\u0000

null
false

int ages[]= {20, 18, 34, 42, 28};

ages
KE-FK
--

ages

20 18
Index

34

42

28
4

E-F

ages[3] W ages 42
W42

System.out.println(ages[3]);

W18531

ages[1]=53;

// array1.java
1. public class array1{
2.
public static void main(String args[]){
3.
double a[]=new double[10];
4.
for(int i=0; i<10; i++){
5.
a[i]=i*2.5;
6.
System.out.println(a[i]);
7.
} // end for
8.
} // end main
9. } // end class array1

W-W

W
--

KdoubleaEF
ii*2.5EF

EF K

WE-FKa

E-F

// array2.java
1. import javax.swing.*;
2. public class array2{
3. public static void main(String args[]){
4. int b[]=new int[5];
5. String s;
6. for(int i=0; i<5; i++){
7.
s=JOptionPane.showInputDialog("Enter a number:");
8.
b[i]=Integer.parseInt(s);
9. } // end for
10. for(int i=0; i<5; i++)
--

W-W

11. if(b[i]>=60)
12.
System.out.println(b[i]);
13. } // end main
14. } // end class array2
W
E-FKbEF
Kb E-FKb

b
WE-FK

E-F

WE-F

--

E-F

K (Index) J

K J

(new) J
K

(Default J
K K(Type)Value)

array1.lengthW)Klength
K(array1

W J
1. int array[]=new int[5];
2. int array[];
array=new int[5];
3. int [] array = new int[5];
4. int [] array;
array=new int[5];
--

W J
1.
int array[]={5, 3, 8, 9, 2};
2. int array[]=new int[] {5, 3, 8, 9, 2};

W-W

//array3.java
1. import javax.swing.*;
2. class array3{
3. public static void main(String args[]){
4.
String s, output, title, str1, str2;
5.
str1="Enter how many number you want to store in the array:";
6.
str2="Enter number # ";
7.
int n, odd=0;
8.
s=JOptionPane.showInputDialog(str1);
9.
n=Integer.parseInt(s);
10. int [] arr=new int[n];
11. output= " ";
12. for(int i=0; i<arr.length; i++){
13. s=JOptionPane.showInputDialog(str2+(i+1)+":");
14. arr[i]=Integer.parseInt(s);
15. output+=arr[i]+"\n ";
16. } //end for
17. for(int i=0; i<arr.length; i++)
18. if(arr[i]%2==1) odd++; // end for
19. title="The results of the example (1-3)";
20. output+="\nThere are "+odd+" odd numbers in the array";
21. JOptionPane.showMessageDialog(null, output, title,
JOptionPane.INFORMATION_MESSAGE);
22. System.exit(0);
23. }
//end main
24. } //end class array3
--

KnE-F
F n arrEF

nE-FKE

KEarr.lengthF arr
oddarrEF
E-FKEFK EF
W

E-F

WE-F

--

E-F

W-W
// array4.java
1.
2.
3.
4.
5.
6.

import javax.swing.*;
class array4{
public static void main(String args[]){
int a[]={2, 4, 5, -5, 3, 10, 4, 11, 1, 7, -2};
String title="The results of the Example (1-4)";
String results="";

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


{
switch(a[i]){
case 1: results=results+"One\n"; break;
case 2: results=results+"Two\n"; break;
case 3: results=results+"Three\n"; break;
case 4: results=results+"Four\n"; break;
case 5: results=results+"Five\n"; break;
default: results=results+"More than Five OR Less than One\n";
}
}
JOptionPane.showMessageDialog(null, results, title,
JOptionPane.INFORMATION_MESSAGE);
19. System.exit(0);
20. }
21. }
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.

- -

W
E-FK aEF
switch

K More than Five OR Less than One

WE-F

E-F

W-W
// array5.java
1.
2.
3.
4.
5.
6.
7.
8.

import javax.swing.*;
class array5{
public static void main(String args[]){
double marks[] = new double[6];
String names[] = new String[6];
String s;
String t1 = Enter the Student's name:;
String t2 = "Enter his mark:";
- -

9.
for(int i=0; i<6; i++){
10.
s=JOptionPane.showInputDialog(t1);
11.
names[i]=s;
12.
s=JOptionPane.showInputDialog(t2);
13.
marks[i]=Double.parseDouble(s);
14.
}
15.
String title = "The passed students";
16. String results="The following students are passed the exam:\n";
17.
for(int i=0; i<6; i++){
18.
if(marks[i]>=60)
19.
results=results+names[i]+"\n";
20.
}
21. JOptionPane.showMessageDialog(null, results, title,
JOptionPane.INFORMATION_MESSAGE);
22.
System.exit(0);
23. }
24. }

W
double marksEF

String namesEFK

E-FK
E-FK

K
EF
WE-FK

- -

E-F
- -

E-F

WE-F

E-F
- -

W-W
// array6.java
1. import javax.swing.*;
2. class array6{
3.
public static void main(String args[]){
4.
int num[] = new int[]{4, 6, 2, 3, 9, 5, 7, 2, 4, 7};
5.
String output="The Contents of the array are:\n";
6.
String title="The results of the Example (1-6)";
7.
for(int i=0; i<=num.length-1; i++)
8.
output+=num[i]+" ";
9.
output+="\nThe Contents of the array in reverse order are:\n";
10.
for(int i=num.length-1; i>=0; i--)
11.
output+=num[i]+" ";
12. JOptionPane.showMessageDialog(null, output, title,
JOptionPane.INFORMATION_MESSAGE);
13.
System.exit(0);
14. }
15. }

E-F
FnumK
E-F KE num.length-1
W

E-F
W(Sorting)
- -

K
K

.(Bubble Sort)

W-
// array7.java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.

import javax.swing.*;
class array7{
public static void main(String args[]){
int num[] = new int[] {4, 6, 2, 3, 9, 5, 8, 1, 10, 7};
int temp;
String title="The results of the Example (1-7)";
String output="Array contents in original order:\n";
for(int i=0; i<num.length; i++)
output+=num[i]+" ";
for(int i=1; i<num.length; i++)
for(int j=0; j<num.length-1; j++)
if(num[j]>num[j+1]){
temp=num[j];
num[j]=num[j+1];
num[j+1]=temp;
}
output+="\n\nArray contents in ascending order:\n";
for(int i=0; i<num.length; i++)
output+=num[i]+" ";
JOptionPane.showMessageDialog(null, output, title,
JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
}

- -

W
numE-F
EF

K
F E- F

E-F K(Ascending) KE-


W

E-F

W-
// array8.java
1.
2.
3.
4.
5.

import javax.swing.*;
class array8{
public static void main(String args[]){
JTextArea outArea= new JTextArea();
int mark[] = new int[] {78, 81, 52, 92, 48, 90, 66, 40, 96,84};
- -

6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.

String name[]= {"Ahmad", "Mohammed", "Naser", "Saleem",


"Adel", "Khaled", "Ali", "Kareem", "Jamil",
"Nader"};
int temp_mark;
String temp_name;
String title="The results of the Example (1-8)";
String output="The students' marks in original order:\n";
output+="Name\tMark\n------------------\t--------\n";
for(int i=0; i<mark.length; i++)
output+=name[i]+"\t"+mark[i]+"\n";
for(int i=1; i<mark.length; i++)
for(int j=0; j<mark.length-1; j++)
if(mark[j]<mark[j+1]){
temp_mark=mark[j];
mark[j]=mark[j+1];
mark[j+1]=temp_mark;
temp_name=name[j];
name[j]=name[j+1];
name[j+1]=temp_name;
}
output+="\n\nStudents' Marks in descending order:\n";
output+="Name\tMark\n------------------\t--------\n";
for(int i=0; i<mark.length; i++)
output+=name[i]+"\t"+mark[i]+"\n";
outArea.setText(output);
JOptionPane.showMessageDialog(null, outArea, title,
JOptionPane.PLAIN_MESSAGE);
System.exit(0);
}
}

E-F K(Descending)
E-F
- -

E-F K E-F
W

E-F

- -

W(Searching)

K(Binary Search)(linear Search)W

W-
// array9.java
1.
2.
3.
4.
5.
6.
7.

import javax.swing.*;
class array9{
public static void main(String args[]){
int n[] = new int[10];
int num, k=-1;
String title="The results of the Example (1-9)";
String s, output="";

8.
9.
10.

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


n[i]=i*2;
s=JOptionPane.showInputDialog("Enter the number which you
want to search for:");
num=Integer.parseInt(s);
for(int i=1; i<n.length; i++)
if(n[i]==num){
k=i;

11.
12.
13.
14.

- -

15.
16.
17.
18.
19.
20.
21.
22.
23.
24.

break;
}
if(k!=-1)
output+="Found value in index "+k;
else
output+="Value not found";
JOptionPane.showMessageDialog(null, output, title,
JOptionPane.PLAIN_MESSAGE);
System.exit(0);
}
}

W

numE-FK

KJ kk

k E-F
kJ

E-FK k
W

EJ F

WE-F
- -

EJ F

W-

// array10.java
1.
2.
3.
4.
5.

6.
7.
8.
9.

import javax.swing.*;
class array10{
public static void main(String args[]){
int id[] = new int[] {2, 10, 1, 7, 4, 6, 3, 8, 5, 9};
String name[]= {"Ahmad", "Mohammed", "Naser", "Saleem",
"Adel", "Khaled", "Ali", "Kareem", "Jamil",
"Nader"};

10.

String s, stdName, title="The results of the Example (1-10)";


String output="The student's name is:--> ";
int no, index=-1;
s=JOptionPane.showInputDialog("Enter the student's ID to
display his name:");
no=Integer.parseInt(s);

11.
12.
13.
14.
15.
16.
17.

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


if(id[i]==no){
index=i;
break;
}
if(index!=-1)
output+=name[index];
- -

18.
19.
20.
21.
22.
23.

else
output="There is no student with this ID !!!";
JOptionPane.showMessageDialog(null, output, title,
JOptionPane.PLAIN_MESSAGE);
System.exit(0);
}
}

id E-F K
id(no)

index id
E-Fname

There is no student id

Kwith this ID !!!


KE-F

E-F
K E-F

- -

E-F

W-
// array11.java
1.
2.
3.
4.
5.

import javax.swing.*;
class array11{
public static void main(String args[]){
int id[] = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
String name[]= {"Ahmad", "Mohammed", "Naser", "Saleem",
"Adel", "Khaled", "Ali", "Kareem", "Jamil",
"Nader"};

6.
7.
8.
9.
10.
11.
12.
13.

String s, stdName, title="The results of the Example (1-11)";


String output="The student's name is:--> ";
int no, index=-1;
int low=0;
int high = id.length-1;
int middle;
s=JOptionPane.showInputDialog("Enter the student's ID to display
his name:");
no=Integer.parseInt(s);

14.

while(low <=high){

15.
16.

middle=(low+high)/2;
if(no==id[middle]){
- -

17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.

index=middle;
break;
}
else if(no<id[middle])
high=middle-1;
else
low=middle+1;
}
if(index!=-1)
output+=name[index];
else
output="There is no student with this ID !!!";
JOptionPane.showMessageDialog(null, output, title,
JOptionPane.PLAIN_MESSAGE)
System.exit(0);
}
}

EF idE-F

K
E-F

(while) id

Kid

WE-F

- -

E-F
WE-F

E-F

W-

// array12.java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.

public class array9{


public static void main(String[] args) {
int[] testArray = new int[50];
testArray[43] = 10;
int testArray2[] = { 35, 23, 8, 34, 66, 88, 5, 2, 85, 33 };
int key, index=-1;
key=10;
System.out.println("Searching for element == 10");
for(int i = 0; i < testArray.length; i++) {
if(testArray[i] == key)
index = i;
- -

12.

13.
14.
15.
16.

if(index != -1)
System.out.println("Element found at " + index);
else
System.out.println("Element (10) does not found at the array
testArray");
index=-1;
key=88;
System.out.println("Searching the second array for element ==
88");

17.
18.
19.
20.
21.
22.
23.

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


if(testArray2[i] == key)
index = i;
}

24.
25.
26.
27.

if(index != -1)
System.out.println("Element found at " + index);
else
System.out.println("Element (88) does not found at the array
testArray2");
}
}

28.

W
E-FE-F

key

KE-F

- -

E-F

- -

W(Two-Dimensional Arrays)
W

WKE-F

1. int b[][];
2. b = new int[ 3 ][ 4 ];

bE-FK

K
0

b[0][3] b[0][0]

1 b[1][0]
2 b[2][0]

2
b[0][1]

3
b[0][2]

b[1][1]

b[1][2]

b[1][3]

b[2][1]

b[2][2]

b[2][3]


E-F

W
int b[][] = { { 1, 2 }, { 3, 4 } };

- -

b
K
WbE-FK

E-F

W
int c[][] = { { 1, 2, 3}, { 4, 5 } };

KcE-F

1 2
4 5

E-F


1.
2.
3.
4.

int a[][];
a = new int[ 2 ][ ];
// allocate rows
a[ 0 ] = new int[ 5 ]; // allocate row 0
a[ 1 ] = new int[ 3 ]; // allocate row 1
- -

EFaEF
EF EF

KaE-FK

A[0][4]

A[1][2]

E-F

- -

W-

// array13.java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.

public class array13 {


public static void main(String[] args) {
int array1[][] = { { 1, 2, 3 }, { 4, 5, 6 } };
int array2[][] = { { 1, 2 }, { 3 }, { 4, 5, 6 } };
System.out.println("The contents of the array1 are:");
for(int i=0; i<array1.length; i++){
for(int j=0; j<array1[i].length; j++)
System.out.print("\t"+array1[i][j]+"\t");
System.out.println();
}
System.out.println("The contents of the array2 are:");
for(int i=0; i<array2.length; i++){
for(int j=0; j<array2[i].length; j++)
System.out.print("\t"+array2[i][j]+"\t");
System.out.println();
}
}
}

array1 EF
EFK

array2
K

array1E-F
array1.length array1
- -

K i array1[i].length
KE-FKE-Farray2

E-F

W-
// array14.java
1.

public class array14{

2.
3.
4.
5.

public static void main(String[] args) {


int grades[][] = { { 77, 68, 86, 73 },
{ 96, 87, 89, 81 },
{ 70, 90, 86, 81 } };

6.
7.

int sum;
System.out.println("The array is:");
- -

8.

System.out.println("\t\t[0]\t[1]\t[2]\t[3]");

9.
10.
11.
12.
13.
14.

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


System.out.print("grades["+i+"]"+"\t");
for(int j=0; j<grades[i].length; j++)
System.out.print(grades[i][j]+"\t");
System.out.println();
}

15.

System.out.println();

16.
17.
18.
19.
20.
21.
22.
23.

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


sum=0;
for(int j=0; j<grades[i].length; j++)
sum+=grades[i][j];
System.out.println("Average for student "+i+" is "
+(double)sum/grades[i].length;
}
}
}

E-FKE-F grades

K grades

EF E-F

sumEF
grades[i].length
sum KEF i

KE-FKEF

- -

E-F

4.
5.
6.
7.
8.
9.
10.
11.

W-

// array15.java
1.
2.
3.

public class array15{


public static void main(String[] args) {
int nums[][]= { {21, 24, 43, 54}, {15, 63, 27, 84}, {29, 10, 17, 42}, {28,
33, 41, 67}
};
int sum=0;
System.out.println("The contents of array nums are:");
for(int i=0; i<nums.length; i++){
for(int j=0; j<nums[i].length; j++)
System.out.print(" "+nums[i][j]+" ");
System.out.println();
}
for(int k=0; k<nums[1].length; k++)
- -

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

sum+=nums[1][k];
System.out.println("\nThe sume of elements on the 2nd row is:
"+sum);
sum=0;
for(int k=0; k<nums.length; k++)
sum+=nums[k][2];
System.out.println("\nThe sume of elements on the 3rd column is:
"+sum);
sum=0;
for(int i=0; i<nums.length; i++)
for(int j=0; j<nums[i].length; j++)
if(i==j) sum+=nums[i][j];
System.out.println("\nThe sume of elements on the main diagonal
is: "+sum);
sum=0;
for(int i=0; i<nums.length; i++)
for(int j=0; j<nums[i].length; j++)
if(i+j==nums.length-1) sum+=nums[i][j];
System.out.println("\nThe sume of elements on the secondary
diagonal is: "+sum);
System.out.println();
}
}

FEF

E F

KEF

E-FKE-F
KE F

KEFE-F

nums
- -

EFE-F
E-FK


KE-FKEF

E-F

- -

W
K

KEH

W
K
WFK
KE

F W
F E
KE

N W
K

KNot found in the array

K W
F

KE
K

- -

W
K

WW

KJ
KJ

KJ
KJ

- -


]<gj]<]<j<^]<]

K(Math)K(String)

W
W

KEF -

K(Math Class) -
K(Life Time) -

K(Scope) -

K(Recursion) -

K(Overloading) -
K(String) -

W
K

K W

W
K

W
K

- -

W
K

(Methods)
(Method Body)

(Signature) K
K


K(Math Class)

W(Math Class)

K K K K
W
Class_Name.method_Name(Argument List)

System.out.println(Math.sqrt(9.0)) ;

E9.0F (Math)( sqrt)


E-F K3.0K(Double)
.(Math)

- -

Math.abs(6.2) 6.2
Math.abs(-2.4) 2.4

Kx abs(x)

Math.ceil(5.1) 6
Math.ceil(-5.1) -5

x ceil(x)
Kx

Math.floor(5.1) 5
Math.floor(-5.1)-6

x floor(x)
Kx
Kyx max(x,y)
Kyx min(x,y)

Math.max(7,6) 7
Math.min(-7,-8) -8
Math.pow(6,2)62 36
Math.sqrt(9)

Kyx

pow(x,y)

Kx sqrt(x)

9 3

Math.random() 0.23121

random()
K

E-F
W-
// UseMath.java
1.
2.
3.
4.
5.
6.
7.
8.
9.

public class UseMath{


public static void main( String args[]){
System.out.println("The square root of 100 = " + Math.sqrt(100));
System.out.println("The absolute value of 20 = " + Math.abs(20));
System.out.println("The absolute value of -20 = " + Math.abs(-20));
System.out.println("The absolute value of 0 = " + Math.abs(0));
System.out.println("4 to the power 2 = " + Math.pow(4,2));
}
// end of main
}
// end of class UseMath

- -

W
E-F(Math)E-F

E-F


E-F K
K

WE-F

// RollDie.java
1.
2.
3.
4.
5.
6.
7.
8.
9.

public class RollDie{


public static void main( String args[]){
int face ;//variables to store the result
for (int i = 1;i<=5;i++){
face = 1+(int)(Math.random()*6);
System.out.println("The Face in Try " + i + " is " + face);
} // end for loop
} // end of main
} // end of class RollDie
- -

W
EF

Mathrandom
(Math.random())

(int)

KE-FKEF
K

E-F

KE-F

E-F
- -

(Divide and Conquer)??

Software )

(Math Class)(Reusability


(Method)

W
(Method F
(Signature) KBody)

KE-F

[Access_Specifier][static][Returen_Type] Method_Name([parameters]

Method
Body

E-F
- -

statement_1;
statement_2;
statement_3;

.
Signature .
.
statement_n;
[retuen]

?[??]?

W (Access_Specifier)J

(Method)??W(private)J
K(Class)
K??W(public)J

(Access_Specifier)J
K

K
??( static)J
KE (Object) F K
K

(Return_Type)J

(Data Types)

K(Return) E K K K char intWF -


Kvoid

(Method_Name)J
K

(parameters)J
(Formal Parameters)

K (Local Variables)
K(Actual Parameters)

(Method_Body)J
K

return void
K
- -

EvoidFE-F
Ksum1
[Access_Specifier][static][Returen_Type] Method_Name([parameters]

public

static

void

sum1(int num1, int num2)


{

int sum;

sum = num1 +Signature


num2;
System.out.println(sum);

Method
Body

E-F
sum1E-F
K

[Access_Specifier][static][Returen_Type] Method_Name([parameters]

public

static

int

sum1(int num1, int num2)

int sum;

sum = num1 +Signature


num2;
return sum;

Method
Body

E-F
- -

K W

WE-F
// Methods.java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.

public class Methods {


// instance variable declaration . . .
public void method1(){
//body
}
public void method2(int i , double j){
//body
}
public int method3(){
//body
return 0; //integer expression
}
public int method4(int i ,String s ){
//body
return 0; //integer expression
}
}

KE-F

E-FK (Method1)E-F

Kdouble j int i W (Method2)

K(int) (Method3)E-F
- -

sintiW (Method4)E-F
K(int)KString

K
K

KE-F

Method_Name ( [Parameters_List] );

E-F

W(Method_Name)J
K

(Actual Parameters) W(Parameters_List)J


W
Ksum1(5, 6)WJ

Ksum1(x, y)WJ

Ksum1(sum2(z, 4), y)W(Method)J

(void) J
K

WJ
KJ
KJ

WJ
KSystem.out.println( )

- -

WE-F
// MethodCall.java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.

public class MethodCall {


public static void main(String args[]){
int x = 5, y = 6, z = 0, s = 0;
sum1(10, 5);
sum1(x, y);
s =sum2(5, 6);
System.out.println("sum = " + sum2(5, 6));
z = 12 + 3 * sum2(x, 10);
sum1(sum2(3, 4), 5);
} // end of main
// defining the method sum1
static void sum1(int num1,int num2){
int sum=0;//local variable
sum= num1+num2 ;
System.out.println("sum = "+ sum);
} // end of sum1
// defining the method sum2
static int sum2(int num1,int num2){
int sum=0; // local variable
sum= num1+num2 ;
return sum ;// returned value
}
// end of sum2
}// end of class MethodCall
W

EFEFK

sum1
- -

void
EF int sum2K

ssum2
sum2 EF K

K sum2EFKSystem.out.println()
Ksum1sum2EF

KE-FE-F

E-F
(method)

(parameters Formal)(Actual parameters) -


K

K
K -

K -

sum1(10,5)E-F
sum1num2num1
- -

K(return)
E-F KEF sum1

KEFEFsum1
public class MethodCall {
public static void main(String args[] ){
.
.
.
5); 10, sum1(
.
.
.
10
5 }
.
static void sum1(int num1, int num2) .
{.
int sum = 0; }
sum= num1 + num2 ;
System.out.println("sum = " + sum)
}

E-F

:(Variable Life Time)

(RAM) W

WStatic Variables K
K
K

- -

(Block) WLocal Variables K


K

K (block)

.(Method)WParameter Variables K
K(Method)

EFWInstance Variables K
KE F
K

W(Variable Scope)
Instance )K

(Method) (Variables
( Block) K

K
K

// VariableScope.java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.

public class VariableScope{


static int i;
//instance variable
public static void main(String args[]){
int x = 5, y = 6;
//local variables
i = 10;
System.out.println(i = + i);
i = method1(x, y);
System.out.println(i = + i);
i = method2(x, y);
System.out.println(i = + i);
}
//end main
- -

WE-F

12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.

static int method1(int arg11 ,int arg12 ){


double num11 ,num12;
for(int counter = 0; counter <= 5; counter++){
i+= counter;
} //end of for counter loop
return i+arg11+arg12;
}
//end method1
static int method2 (int arg21, int arg22){
int num21, num22, i=0; //local variables
{
String s; //local variable
}
return i+arg21+arg22;
}
//end method1
}
//end of class VariableScope

W
(Variable Scope)

i EF K
VariableScope

main()

y xEFKE i
main() (Local Variables)

method1 arg12 arg11EFK main()


num12num11EFK
K method1

for counterEF
K (block)
- -

imethod2EF
iEF
K

s EF K

EFEF(Block)
K

i EF
EFKiEFK

KyxMethod1

KEF iKi

method2EF
Kmethod2i KiEF i

KE-F

E-F
W
:
:(Pass-By-Value) J

KEF EF
K EF
- -


KKKKfloatdoubleintW(Primitive Data Types)

F :(Pass-By-Reference) J
(Method) E
K
K

KKKKStringArraysEFW (Objects)
WE-F

// Passing_Parameters.java
1. public class Passing_Parametres{
2. public static void main(String args[]){
3. int x;
4. int a[] = {1, 2, 3, 4};
5. x = a[1];
6. System.out.println("The value of x before change is" + x) ;
7. System.out.println("The value of a elements before change is: ");
8. printArray(a);
9. change(a, x);
10. System.out.println("The value of x after change is" + x);
11. System.out.println("The value of a elements after change is: ");
12. printArray(a);
13. } //end of main
14. static void change(int b[], int i){
15.
i *= 2 ;
16. for (int index=0; index < b.length; index++)
17. b[index]*= 2;
18. }
//end of method change
- -

19. static void printArray(int c[]){


20. for (int index=0; index < c.length; index++)
21. System.out.print(c[index] + "\t");
22. System.out.println();
23. }
//end of method print
24. }
//end of class Passing_Parametres
W
EF K

F a Eint F x change

KEint

x (Primitive Data Types)


K i
K

K change a
(Objects)

EFbab
E-F K
KEFchange

- -

Change

a b
1
2
3
4

Change

ax

1
2
3
4

Change

main()

ax

2
4
6
8

a b

2
4
6
8

Change

x
i

E-F

- -

KE-FE-F

E-F

W(Recursion)


.
W(factorial)

WE-F
// factorial.java
1.
2.
3.
4.

import javax.swing.JOptionPane;
public class factorial {
public static void main (String args[ ]){
String snum1;
- -

5.
6.

int num1, fac_of_num1;


snum1 = JOptionPane.showInputDialog("Enter num1:") ;

7.
8.
9.

num1 = Integer.parseInt(snum1);
fac_of_num1 = fact(num1);
JOptionPane.showMessageDialog(null, num1 + "! = " +
fac_of_num1);
}
//end of main

10.
11.
12.
13.
14.
15.
16.
17.
18.

static int fact(int n){


if (n == 0 || n ==1)
return 1;
else
return n * fact(n-1);
}
//end of fact method
}
//end of class factorial

EF K (Factorial) EF

fact

E-F Wfact Kfac_of_num1


F

K E

EFK
(n-1)

E-F K

- -

fact

fact(3) * 4 = fact(4)

fact(1) * 2
1

fact(2) * 3

fact(2) * 3
2 * 1

fact(1) * 2
...fact(3)... * 4
3 * 2 * 1

fact(4) = 24

E-F

WE-F

E-F

- -

W(Methods Overloading)

(Signature)

W
K

WE-F

// Overload.java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.

public class Overload {


public static void main(String args[]){
sum();
sum(100,3);
System.out.println("sum= " + sum(8.5, 4));
System.out.println("sum= " + sum(10, 4.2));
System.out.println("sum= " + sum(8, 9, 4));
}
// no parametrs no return
static void sum () {
int num1 = 10, num2 = 5;
System.out.println("sum = " + (num1 + num2));
}
// has two parametes and no return
static void sum (int num1, int num2) {
System.out.println("sum = " + (num1 + num2));
}
// has two parametes and return double
static double sum( double num1, int num2) {
return (double)(num1 + num2);
}
// has two parameters and return double
// but different order of the parameters
static double sum(int num2 ,double num1) {
- -

27.
28.
29.
30.
31.
32.
33.
34.

return (double)(num1 + num2);


}
// has three parameters and return integer
static int sum(int num1, int num2, int num3) {
return num1+num2+num3;
}
}

K(Methods Overloading)

sum

sumEFKE

sumEFK(void)
EFK(void)int

int double sum


sumEFKdouble

Kdouble double int

int sumEF
KE-FKint

E-F

- -

W(String)
F characters (String)

(String) E

java characters

String
(String)

K?H?

String (String)
W(Primitive Data Types)
1. String s;
2. s= Hello;

sStringsEF

KsHelloEFKString
K(Methods)E-F

W
length() s.length()
Ks
K(!= ==WF
s
t

s t s s.compareTo(t)
s t

Kt

s.compareToIgnoreCase(t)
- -

compareTo()
KEF

Kts true s.equals(t)



equals() s.equalsIgnoreCase(t)

KEF

s true s.startsWith(t)
Kt
t true

Kis

s.startsWith(t, i)

Kts true s.endsWith(t)


W
-1 indexOf()
K

t s.indexOf(t)
Ks
t s.indexOf(t, i)
Kis
s.indexOf(c)
Ksc

s c s.indexOf(c, i)
Ki

s.lastIndexOf(c)
Ksc
- -


Kst

s.lastIndexOf(t)

Kstring
i s.charAt(i)
Ks
s s.substring(i)
Ki
s s.substring(i, j)
Kj-1i
Kstring

s s.toLowerCase()
K

s s.toUpperCase()
K
s.trim()
Ks

c2 c1 s s.replace(c1, c2)
Kchar
Kstring
true s.matches(regexStr)
- -

regexStr

Ks

string s.replaceAll(regexStr, t)
KtregexStr
string s.replaceFirst(regexStr, t)
KtregexStr

KregexStrs s.split(regexStr)

split(regexStr) s.split(regexStr, count)


K
E-F

KE-FE-F

WE-F

// Strings.java
1. public class UseMath{
2. public static void main(String args[]){
3. String s0="Well Come to Java World!" ,
4. s = "hello", t = "HELLO", s1, s2[], s3;
5. char c;
6. boolean b;
7. int i;
8. System.out.println();
9. i = s0.length();
10. System.out.println(" The length of " + "\"" + s0 + "\"" + " = " + I +
"\n");
11. i = s.compareTo(t);
12. if (i == 0)
13.
System.out.println(" \"" + s + "\"" + " is == " + "\"" + t + "\"\n");
- -

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

else if (i<0)
System.out.println(" \"" + s + "\"" + " is < " + "\"" + t + "\"\n");
else
System.out.println(" \"" + s + "\"" + " is > " + "\"" + t +"\"\n");
i = s.compareToIgnoreCase(t);
System.out.print(" Ignoring case: ");
if (i == 0)
System.out.println(" \"" + s + "\"" + " is == " + "\"" + t + "\"\n");
else if (i<0)
System.out.println(" \"" + s + "\"" + " is < " + "\"" + t + "\"\n");
else
System.out.println(" \"" + s + "\"" + " is > " + "\"" + t +"\"\n");
b = s.equals(t);
System.out.println(" Is " + "\"" + s + "\"" + " equals to " + "\"" + t
+ "\"" + " ? " + b +"\n");
b = s.equalsIgnoreCase(t);
System.out.print(" Is " + "\"" + s + "\"" + " equals to ");
System.out.println("\"" + t + "\"" + " (ignoring case)? " + b +
"\n");
b = s.startsWith("H");
System.out.println(" Is " + "\"" + s + "\"" + " starts with \"H\"? " +
b + "\n");
b = s.startsWith("l", 3);
System.out.print(" Is " + "\"" + s + "\"" + " starts with \"l\" ");
System.out.println("from position 3 ? " + b + "\n");
b = s.endsWith("lo");
System.out.print (" Is " + "\"" + s + "\"" + " ends with \"lo\"");
System.out.println(" ,from position 3 ? " + b + "\n");
i = s0.indexOf("Java");
System.out.print (" Java is at position ");
System.out.println( i + " of " + "\"" + s0 + "\"\n");
i = s0.indexOf("java", 4);
System.out.print(" java is at position" + i +"of ");
System.out.println(" \"" + s0 + "\"" + ", starting from position
4\n");
i = s0.indexOf('e');
System.out.print (" \'e\' is at position ");
- -

47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.

System.out.println(i + " of " + "\"" + s0 + "\"\n");


i = s0.indexOf('e', 4);
System.out.print (" \'e\' is at position " + i + " of ");
System.out.println("\"" + s0 + "\"" + " starting from position 4\n");
i = s0.lastIndexOf('e');
System.out.print(" Last occurrence of \'e\' in ");
System.out.println("\"" + s0 + "\"" + " is at "+ I + "\n");
i = s0.lastIndexOf(t);
System.out.print(" Last occurrence of 'rl' in ");
System.out.println("\"" + s0 + "\"" + " is at " + I + "\n");
c = s0.charAt(3);
System.out.print(" The character at position 3 in");
System.out.println("\"" + s0 + "\"" + " is " + c + "\n");
s3 = s0.substring(6);
System.out.print (" The substring of ");
System.out.println("\"" + s0 + "\"" + " starting from 6 is\n" +
"\t\t\t\"" + s3 + "\"\n");
63. s1 = s0.substring(6, 10);
64. System.out.print(" Substring of " + "\"" + s0 + "\"" + " starting ");
65. System.out.println("from 6 to 10 is:" + "\"" + s1 + "\"\n");
66. System.out.print (" \"" + s0 + "\"" + " in lowercase is ");
67. System.out.println("\"" + s0.toLowerCase() + "\"\n");
68. System.out.print("\""+ s0 + "\"" + "in uppercase ");
69. System.out.println("\""+ s0.toUpperCase() + "\"\n");
70. System.out.print(" \"" + s0 + "\"" + " with replacing all spaces ");
71. System.out.println("with ';' is\n" + "\t\t\t\"" + s0.replace( '
',';')+"\"");
72. System.out.println();
73. }
74. }
E-F
K(String)

- -

E-F

- -

WW
Area = r2 X

EWrF

Actual ) (Formal parameters) W


.(parameters or arguments

W W
public methodJ
private methodJ

KW
WW
Pass-By-ValueJ

Pass-By-Reference J

WNW
N

N 1

N 2

i =1

i =1

i =1

i = N + i = N + N 1 + i
W
KJ

KEFJ

EF iXj W
K3X4 = 3+3+3+3 = 12W
i>0

- -

trueW
Kfalse

KMethod OverloadingW

(methods) W
Fahrenheit Celsius
W

F = 9.0 / 5.0 * (C + 32)

Celsius Fahrenheit

W
C = 5.0 / 9.0 * (F 32)

F W
W(String)

F J
KE

KEFJ
J
KEF

J
KEF

KJ

KJ

- -

WW
-

public class checkupper {


public static void main (String args[]){
char c1 = 'f', c2 = 'T';
System.out.println("Is "+c1 +" in uppercase ? " +
isUpperCase(c1));
System.out.println("Is "+c2 +" in uppercase ? " +
isUpperCase(c2));
}
static boolean isUpperCase(char testChar) {
return ((testChar>='A') && (testChar<='Z'));
}
}

public class validateAddress {


public static void main (String args[]){
String My_email = "java_doc@java.net";
if (validate(My_email) == true)
System.out.println("this a valid email address");
else
System.out.println("this an invalid email
address");
}
static boolean validate(String email) {
String name;
String domain;
- -

int index;
if (( index = email.indexOf( '@')) == -1) {
return false;
}
name = email. substring(0, index);
domain=email.substring(index+1,email.length());
System.out.println(" Name: " + name);
System.out.println(" Domain: " + domain);
return true;
}
}
-

public class primenumbers{


public static void main(String [] args) {
System.out.println("The Prime numbers between 1 and
100 are");
for (int i = 0; i < 100; i++)
if (isPrime(i))
System. out. print(i + " ");
}
static boolean isPrime(int test) {
if (test < 2)
return false;
if (test == 2)
return true;
for (int i = 2; i < test; i++)
- -

if (( test % i) == 0)
return false;
return true;
}
}
-
public class SwapArray{
public static void main(String [] args) {
int values[]={1, 2, 3, 4, 5, 6, 7, 8};
System.out.println("values before swap");
printArray(values);
swap(values);
System.out.println ("values after swap");
printArray(values);
}
static void swap(int a[]){
int length = a.length, temp;
for (int i = 0; i <= (length/2); i++){
temp = a[ length - i - 1];
a[length - i - 1] = a[ i];
a[ i] = temp;
}
}
static void printArray(int a[]){
for (int i =0;i<a.length;i++){
System.out.print (a[i]+"\t");
}
- -

System.out.println( );
}
}

- -


]<gj]<]<j<^]<]

W
K
W
W
K(OOP) J
K J

K J
K(Method Overriding) J

W
K

K W
W
K
K

W
K

- -

W(Object Oriented Programming)


(objects) (classes)


divide and )?? (modules)

.(conquer

K(classes)

(API) (classes)

K(messages)

W
KKK

EF W

K (Student)??KKEF

K (Account)??

(Operation) (Data)
K??E-F K(Methods)

- -

(objects)

(class)

E-F
Class DiagramE-F
? ?

Account

Class Name

Account_no
Balance
Last_Transaction_date

Deposit()
Withdraw()

E-F

Data

Operation

W (Class Declaration)
class
WF

AccountE-FKE


- -

WE-F
// Account.java
1.

import java.util.Date;

2.

public class Account {

3.
4.
5.

private int account_number;


private double balance ;
private Date last_transaction_date;

6.

public void deposit(double amt){

7.
//deposit code
8.
}
9.
public void withdraw(double amt){
10.
// withdraw code
11. }
12. }

data

Operations

W
W
EF public (class name) J

(instances)

(Package) public
K(instances)

E-FJ

E F private
Public
E instanceF
F (Package)

KEinstance

KEFE-FE-FJ

- -

W (Object Creation)
W
E (Objects)
WKEF
K J

new J
K(Constructors)

J
K(public, private, protected, default)

?? protected

protected

E-F K

KE-FAccount

E-F

// Bank.java
1.
2.
3.
4.
5.
6.

public class Bank {


public static void main(String[] args) {
Account acc =new Account();
Acc.deposit(1000);
}
}
W

Account acc EF
new Account acc

F Account (Constructors)

Enew
- -

deposit EF K
K acc
KaccE-F

acc
account_number

balance

last_transaction_date

deposit

withdraw

E-F
(Constructors)

- -

(Overloaded Constructors)
K(Default Constructor)

WE-F

// Account.java
1.
2.
3.
4.
5.
6.
7.

import java.util.Date;
import javax.swing.JOptionPane;
class Account{
private int account_no;
private String customer_name;
private double balance;
Date last_Transaction_Date;

8.
9.
10.
11.

Account(int no ,String name ){


account_no=no;
customer_name=name;
}

12.
13.
14.
15.
16.

Account(int no ,String name ,double amt ){


account_no=no;
customer_name=name;
balance=amt;
}

17.
18.
19.
20.
21.
22.
23.
24.

void deposit (double amt) {


if (amt>0 ){
balance += amt;
last_Transaction_Date= new Date();
}
else
JOptionPane.showMessageDialog(null,"the deposit amount must
be > 0");
}

25.

void withdraw(double amt){


- -

26.
27.
28.
29.
30.
31.
32.

if (amt<=balance ){
balance-=amt;
last_Transaction_Date= new Date();
}
else
JOptionPane.showMessageDialog(null,"the withdraw amount
must be <= balance");
}

33.
34.
35.

public double getBalance(){


return balance;
}

36.
37.
38.
39.

public String getCustomer(){


return customer_name;
}
}

main()

// client_account.java
1. public class client_account{
2.
public static void main(String args[]){
3.
Account acc1=new Account(12, "Ali");
4.
Account acc2=new Account(12, "Fahad", 7350.3);
5.
6.

acc1.deposit(2341.5);
acc2.withdraw(200);

7.
8.
9.

System.out.println("\n Name: "+acc1.getCustomer());


System.out.println("\tHis Balance= " + acc1.getBalance());
System.out.println("\tThe date of the last transaction is: " +
acc1.last_Transaction_Date);

10.

System.out.println(" Name: "+acc2.getCustomer());


- -

11.
12.
13.
14.
15.

System.out.println("\tHis Balance= " + acc2.getBalance());


System.out.println("\tThe date of the last transaction is: " +
acc2.last_Transaction_Date);
System.out.println();
}
}
W

Account

client_account.java client_accountAccount.java
client_account main()

Kacc2acc1Account

E-F Account.java
K private
E-F E-F

W??K

W(Data)J
K(account_no)

K(customer_name)

-
-

K(balance)

K(last_Transaction_Date)

W(Constructors)J

WJ
Account(int no, String name)

WJ
Account(int no, String name, double amt)
- -

W(Methods)J
K(deposit)J

K(withdraw)J
K(getBalance)J

K(getCustomer)J

KAccountE-F
Account

int account_no

String
customer_name
double balance
Date last_Transaction_Date

Account(int,String)

Account(int,String,double)

void deposit
(double)
void withdraw(double)
double getBalance()

String getCustomer()

E-F

E-F client_account EF

acc1 acc2 acc1 Account


E-F Kacc2

E FK

KE-FK

- -

E-F


(Package) (Package)

K (container)


K

package

KK class

K(Packages)E-FK
- -

WE-F
// client_account.java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.

package java2.classes.ch3;
class A{
.
.
.
}
class B{
.
.
.
}
public class client_account{
public static void main(String args[]){
.
.
.
}
}

(Packages)EF
B.class A.class W K
Kjava2classes ch3client_account.class

Kpublicclass

KE-F
- -

E-F

W(Inheritance)

(Super Class) (SubClass)

Kextends K(private)
KE-F
K

- -

WE-F
// y.java
1. class x{
2.
.
3.
.
4.
.
5. } // end of class x
6. public class y extends x{
7.
.
8.
.
9.
.
10. }

W
x y x
yx

KK

W
EF
K

E-FK(private)
KEF

- -

WE-F
// Cars.java
1.
2.
3.
4.
5.
6.

class Transportation{
protected static int x=12;
private int y=19;
public static void meth1(){
System.out.println("Calling meth1() from class Cars.");
}

7.
8.
9.
10.

private void meth2(){


System.out.println("will not be called from Cars");
}
} // end of class Transportation

11.
12.
13.
14.
15.

public class Cars extends Transportation{


public static void main(String args[]){
meth1();
System.out.println(x);
// meth2(); // meth2() has private access in
// Transportation
// System.out.println(y); // y has private access
// on Transportation
}
} // end of class Cars

16.
17.
18.

xW TransportationE-F
(private) y (protected)
meth2() (public) meth1() W

Cars E-F K(private)


Transportation Transportation Cars
- -

SubClass Cars Super Class


FKCarsTransportation

Cars TransportationE

meth1() xE-FKprivate

E-F (Cars) (Transportation)


(private) meth2() y
K (Transportation)

KE-F

E-F

method

this this
thisE-F K

KthisE-F

- -

WE-F

// C.java
1. class A{
2. protected int a=9;
3. } // end of class A
4. class B extends A{
5. void test(){
6.
int a=22;
7.
System.out.println("a = "+a);
8. }
9. } // end of class B
10. public class C{
11. public static void main(String args[]){
12.
B acc=new B();
13.
acc.test();
14. }
15. } // end of class C

aEFa=22W

KAatest()

WE-F

// C.java
1. class A{
2. protected int a=9;
3. } // end of class A
4. class B extends A{
5. void test(){
- -

6.
int a=22;
7.
System.out.println("a = "+this.a);
8. }
9. } // end of class B
10. public class C{
11. public static void main(String args[]){
12.
B acc=new B();
13.
acc.test();
14. }
15. } // end of class C

W
EFa=9W

thistest() a A a

B B a
KAaa

(Super Class) (SubClass)


this

(SubClass) (SubClass)
K(Super Class)
(Super Class) (SubClass)

(SubClass)

E-F K(Super Class) super


super

- -

WE-F

// C.java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.

class A{
void test1(){
System.out.println("The test1() method was invoked FROM class
A");
}
} // end of class A

13.
14.

class B extends A{
void test(){
super.test1();
test1();
}
void test1(){
System.out.println("The test1() method was invoked FROM class
B");
}
} // end of class B

15.
16.
17.
18.
19.
20.

public class C{
public static void main(String args[]){
B acc=new B();
acc.test();
}
} // end of class C

test1()ABEF
test1() KA B
EFKSuperA

test1() Super test1()


- -

E-FKBEF
K

E-F
W(Methods Overriding)
(Super Class)
(Methods (SubClass)

Overriding)
Ksuper

WE-F

// Test.java
1.
2.
3.

class Car {
private int year;
private float originalPrice;
- -

4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.

// calculate the sale price of a car based on its


// cost
public double CalculateSalePrice() {
double salePrice;
if (year > 1994)
salePrice = originalPrice * 0.75;
else if (year > 1990)
salePrice = originalPrice * 0.50;
else
salePrice = originalPrice * 0.25;
return salePrice;
}
// a public constructor
public Car(int year, float originalPrice) {
this.year = year;
this.originalPrice = originalPrice;
}
}

21.
22.

class ClassicCar extends Car {


// calculate the sale price of a car based on its
// cost
23. public double CalculateSalePrice() {
24.
return 10000;
25. }
26.
27.
28.
29.
30.

// a public constructor
public ClassicCar(int year, float originalPrice) {
super(year, originalPrice);
}
}

31.
32.
33.
34.

public class Test{


public static void main(String args[]){
ClassicCar myClassic = new ClassicCar(1920, 1400);
double classicPrice =
- -

35.
36.
37.
38.
39.
40.

myClassic.CalculateSalePrice();
System.out.println(classicPrice);
Car myCar = new Car(1990, 12000);
double price = myCar.CalculateSalePrice();
System.out.println(price);
}
}

Car CalculateSalePrice() E-F


CalculateSalePrice() Car ClassicCar
E-F ClassicCar

EFK(Methods Overriding)

KCar year year this


KE-F

E-F
- -

Rational W
W

F numeratorW int (private)WJ


KEFdenominatorE

F (Constructor)J

E2/4 1/2 W

K(Object)

KJ
KJ

KJ
KJ
(numerator)aa/bW J
K(denominator)b

(float) J
K

length W Rectangle W
width
K
K

HugeInteger W
K
WEF

KinputHugeIntegerJ
- -

K outputHugeIntegeJ
KaddHugeIntegeJ

KsubtractHugeIntegeJ
isEqualToJ
Kfalsetrue

isGreaterThan J
true

Kfalse

WDateW
WJ
MM/DD/YYYY
April 01, 2004
DDD YYYY

J
K

IntegerSetW

i true a[i] boolean


jfalsea[j]

Kfalse

unionOfIntegerSet J
K

- -

intersectionOfIntegerSet J
K

KkinsertElementJ
KmdeleteElementJ

Empty Set setPrintJ


K
KisEqualToJ
K

- -

Deitel and Deitel, Java: How to Program, 3rd Edition, Prentice Hall, 2001 K
Patrick Naughton and Michael Morrison, the Java Handbook, McGraw-Hill, 1996K
Bruce Eckel, Thinking in Java (2nd Edition), 2001K

JAVA 2KK

- -

.............................................................................................................................................W

.................................................................................................................................................

...................................(Allocating)

......................................................................................(Arrays)

...............................................................................................(Sorting)

...............................................................................................(Searching)

.....................................................(Two

(Declaring)

Dimensional Arrays)

.....................................................................................................

..................................................................................................................................................

....................................................................................................................(Methods)W

.................................................................................................................................................

......................................................................................................................................

....................................................................................(Math

Class)

..........................................................................................................................

................................................................................................................

............................................................................(Variable

Life Time)

............................................................................................(Variable

Scope)

...........................................................................................................................

..................................................................................................(Recursion)

...............................................................(Methods

Overloading)

.................................................................................(String)

...................................................................................................................................................

...................................(Object

and Objects)W

Oriented Programming)

.......................................................(Class

.............................................................(Object

.......................................................................................................(Inheritance)

...(Accessing

Declaration)
Creation)

Inherited Methods and Data)

................................................................(Methods

Overriding)

...................................................................................................................................................

........................................................................(Classes

...........................................................................................................................................................................


EF
GOTEVOT appreciates the financial support provided by BAE SYSTEMS


]<gj]<]<j<^]<]

W
K

????
K


]<gj]<]<j<^]<]

K
K

--

Inheritance and Polymorphism


Object Oriented programming

K
Classes

Objects

Methods

J F
Instance variables

E
K

Class
Objects

Behavior Member variablesDataAttributes


Access specifier
Ex:
public
class

class

class_name

WMember Methods

BankAccount

public

class

public classmain

Constructors
Constructors

K
Parameters

--

BankAccount.java
1 public class BankAccount
2 {
3 // The first constructor is the default constructor sets balance to zero
4
public BankAccount()
5
{
6
balance = 0;
7
}
8 // The second constructor sets balance to initial to initial balance
9
public BankAccount(double initialBalance)
10
{
11
balance = initialBalance;
12
}
13 // The deposit method adds an amount to instance variable balance
14
public void deposit(double amount)
15
{
16
balance = balance + amount;
17
}
18 // The withdraw method subtracts an amount from instance variable balance
19
public void withdraw(double amount)
20
{
21
balance = balance - amount;
22
}
23 // The transfer method withdraw an amount from this object and deposit to
other object balance
24
public void transfer(BankAccount other , double amount)
25
{
26
withdraw(amount);
27
other.deposit(amount);
28
}
29
30
// The getBalance method returns the current balance
31
public double getBalance()
32
{
33
return balance;
34
}
35
// The instance variable balance
36
private double balance;
37 }

EJ F

--

K
double

Constructors K

Access Specifier
Ex:
Public

Class name (parameter type parameter name, .)


BankAccount (double

initialBalance)

Methods

Methods BankAccount

deposite Method

withdraw method

transfer method

getBalance method

Wmethod

Access specifier
return type
method name(parameter type parameter name,..)
Ex 1:
public
void
deposite (double amount)
Ex 2:
public
double
getBalance
public

double

Kvoid

--

small letter

getBalance

E,F

implicit parametersEF

explicit parameter

InstanceObjects

new
Ex1:
BankAccount myAccount = new BankAccount();

myAccount
balanceBankAccountBankAccount()
myAccount
Ex2:
BankAccount m1 = new BankAccount(5000);

m1
BankAccount BankAccount(double

initialBalance)

m1balance

--

instance variables

Access specifier
type
Ex:
private
double

variable name;
balance;

private

Encapsulationdata hiding

Ex1:
myAccount.balance
Ex2:
m1.balance

OOP


Ex:
m1.deposit(500);

deposit

balance = balance + amount


this.balnce = this.balance + amount
m1.balance = m1.balance +amount

depositm1

--

Inheritance

OOP inheritance

K W

BankAccount

KEJ F
SavingAccount.java
/* The SavingAccount class extends the BankAccount class implements
a new method addInterest to model an account that pays a fixed
interest rate on deposits
*/
public class SavingAccount extends BankAccount
// The SavingAccount constructor
{
public SavingAccount(double rate)
{
interestRate = rate;
}
// addInterest method
public void addInterest()
{
double interest = getBalance()*interestRate/100;
deposit(interest);
}
// The SavingAccount instance variable
private double interestRate;
}

EJ F

--


code

reuse

superclass EF

Base parent class

class

subclass

drived child class


class
J


extends



class subclass Name
ex:
class SavingAccount

extends

superclass Name

extends

BankAccount

superclassEF
BankAccount

subclassSavingAcount

Object

ObjectBankAccount Object

KtoString

SavingAccountBankAccountObjectEJ F

Inheritance Diagram

--

Object

BankAccount

SavingAccount

EJ F

Ex:
SavingAccount

m2 = new SavingAccount(10)

SavingAccountm2
balanceBankAccount

intrestRateSaving Account
m2.balance = 0
m2.intrestRate = 10

balance

SavingAccountm2EJ

FintrestRate

SavingAccount
Bankaccount portion

Balance 1000
interestRate 10

EJ F

K
--

Ex:

m2.addIntrest();

SavingAccountaddIntrest

BankAccountdepositgetBalance

WaddIntrest addIntrest
double interest =this.getBalance() * this.intrestRate/100
this.deposit(intrest)

WaddIntrest()m2.addIntrest();

double interest = m2.getBalance() * m2.intrestRate/100


m2.deposit(intrest)

C++single inheritance

Multiple inheritance

K
Inheritance Hierarchies

branches root

K
WW

CheckingAccount

SavingAccount

TimeDepositAccount

balance

getBalance withdrawdeposit
- -

BankAccount

EJ F

BankAccount
getBalance
deposit
withdraw

CheckingAccount

SavingAccount

deductFees
deposit
withdraw

addInterest

TimeDeposit
Account
addInterest
withdraw

EJ F

- -

instance variablesmethods
W Methods

EF
override

method
K

Instance variables

BankAccountEJ FCheckingAccount
transactionCount deductFees()

withdrawdeposit

transactionCount

CheckingAccount

BankAccountbalance

CheckingAccounttransactionCount

WCheckingAccount

BankAccountgetBalance()
- -

E Fdeposit(double

amount)

EFwithdraw(double

amount)

CheckingAccountdeductFees()

BankAccount)

BankAccount

CheckingAccount deposit(double amount)

- -

CheckingAccount.java
/* The CheckingAccount class extends the BankAccount class implements
a new method deductFees and overide the deposit and withdraw methods
*/
public class CheckingAccount extends BankAccount
// The CheckingAccount constructor
{
public CheckingAccount(double initialBalance)
{
// construct superclass
super(initialBalance);
// initialize transaction count
transactionCount = 0;
}
// overide the BankAccount deposit method
public void deposit(double amount)
{
transactionCount ++;
// now add amount to balance
super.deposit(amount);
}
// overide the BankAccount withdraw method
public void withdraw(double amount)
{
transactionCount ++;
// now subtract amount from balance
super.withdraw(amount);
}
// New method deductFees
public void deductFees()
{
if(transactionCount>FREE_TRANSACTIONS)
{
double fees =
TRANSACTION_FEE*(transactionCount- FREE_TRANSACTIONS);
super.withdraw(fees);
}
transactionCount = 0;
}
// The CheckingAccount instance variables
private int transactionCount;
private static final int FREE_TRANSACTIONS = 3;
private static final double TRANSACTION_FEE = 2.0;
}

EJ F
- -

override

// override the BankAccount deposit method


public void deposit(double amount)
{
transactionCount ++;
// now add amount to balance
balance = balance + amount;
}

//ERROR

balance

private

balance deposit(amount)

// override the BankAccount deposit method


public void deposit(double amount)
transactionCount ++;
// now add amount to balance
deposit(amount);

this
deposit(amount)
deposit(double

amount)CheckingAccount

super

// override the BankAccount deposit method


public void deposit(double amount)
transactionCount ++;
// now add amount to balance
super.deposit(amount);

// override the BankAccount withdraw method


public void withdraw(double amount)

- -

transactionCount ++;
// now subtract amount from balance
super.withdraw(amount);

deductFees

fees

withdraw(fees)

// New method deductFees


public void deductFees()
if(transactionCount>FREE_TRANSACTIONS)
double fees = TRANSACTION_FEE*(transactionCount- FREE_TRANSACTIONS);
super.withdraw(fees);
transactionCount = 0;

TimeDepositAccount

SavingAccount

EJ F

periodsToMaturity TimeDepositAccount

addIntrest

TimeDepositAccountEJ F

BankAccount BankAccount

depositgetBalanceTimeDepositAccount

K
- -

override

TimeDepositAccount

methodaddInterest()

SavingAccount
// override the SavingAccount addInterest method
public void addInterest()
periodsToMaturity--;
super.addInterest();

withdraw(double amount)

// override the BankAccount withdraw method


public void withdraw(double amount)

if (periodsToMaturity >0)
super.withdraw(EARLY_WITHDRAW_PENALITY);
// now subtract amount from balance
super.withdraw(amount);

- -

TimeDepositAccount.java
/* The TimeDepositAccount extends SavingAccount class overrides
the SavingAccount addInterest method and the BankAccount withdraw
method to model an account like SavingAccount but you promize to leave
the mony in the account for a particular number of months, and
there is a penalty for early withdrawal.
*/
public class TimeDepositAccount extends SavingAccount
// The TimeDepositAccount constructor
{
public TimeDepositAccount(double rate , int maturity)
{
super (rate);
periodsToMaturity = maturity;
}
// override the SavingAccount addInterest method
public void addInterest()
{
periodsToMaturity--;
super.addInterest();
}
// override the BankAccount withdraw method
public void withdraw(double amount)
{
if (periodsToMaturity >0)
super.withdraw(EARLY_WITHDRAW_PENALITY);
// now subtract amount from balance
super.withdraw(amount);
}
// The TimeDepositAccount instance variables
private int periodsToMaturity;
private static final double EARLY_WITHDRAW_PENALITY = 20.0;
}

EJ F
super.addIntrest(); TimeDepositAccount
addIntresetK super.withdraw(amount);

withdrawSavingAccount
withdraw

KBankAccount
- -

Subclass constructors

balanceCheckingAccount

balanceBankAccount

super
W

// The CheckingAccount constructor

public CheckingAccount(double initialBalance)


// construct superclass
super(initialBalance);
// initialize transaction count
transactionCount = 0;

BankAccountCheckingAccount

balanceBankAccount

balance CheckingAccount

// The CheckingAccount constructor


public CheckingAccount(double initialBalance)
// superclass has been constructed with its default //constructor
// now set initial balance
super.deposit(initialBalance);
// initialize transaction count
transactionCount = 0;

SavingAccount TimeDepositAccount

// The TimeDepositAccount constructor

public TimeDepositAccount(double rate , int maturity)


super (rate);
periodsToMaturity = maturity;
- -

Polymorphism

"is a"

ChechingAccount

BankAccount

BankAccounttransfer

// The transfer method withdraw an amount from this object and //deposit to other object balance
public void transfer(BankAccount other , double amount)
withdraw(amount);
other.deposit(amount);

BankAccount

Ex:

transfer

BankAccount c1 = new BankAccount(1000);


CheckingAcount c2 = new CheckingAccount(2000);
C1.transfer(c2,500);

BankAccountK

EJ F CheckingAccountBankAccount

Bankaccountother deposit

deposit

BankAccount.deposit

transactionCount
deposit CheckingAccount

CheckingAccounttransferother

BankAccount.depositCheckingAccount.depoit

actual object

other.depositreference

object

KOOP

many shapespolymorphism

polymorphicinstance methods
- -


overloaded methods explicit parameters

compiler
explicit parameters

overload polymorphism
overload
early

binding

compiler deposit
virtual machine
other

late bindingcompiler

EJ FpolymorphismTestEJ FBankAccountTest

- -

BankAcountTest.java
public class BankAcountTest
{
/* This program is used to test the diferent bankAcounts
classes
*/
// The main method
public static void main(String [] args)
{
BankAccount mohamed = new BankAccount();
BankAccount ahmed = new BankAccount(1000);
BankAccount mahmoud = new BankAccount(2000);
mohamed.deposit(3000);
ahmed.deposit(3000);
mahmoud.deposit(3000);
// transfer 1000Sr from mahmoud to ahmed
mahmoud.transfer(ahmed,1000);
System.out.println(mohamed.getBalance());
System.out.println(ahmed.getBalance());
System.out.println(mahmoud.getBalance());
// construct new SavingAccount object called moustafa
SavingAccount moustafa = new SavingAccount(5);
moustafa.deposit(1000);
moustafa.addInterest();
System.out.println(moustafa.getBalance());
// construct new CheckingAccount object called baker
CheckingAccount baker = new CheckingAccount(5000);
baker.deposit(1000);
baker.deposit(1000);
baker.deposit(1000);
baker.deposit(1000);
baker.deposit(1000);
baker.withdraw(2000);
baker.deductFees();
System.out.println(baker.getBalance());
// construct new TimeDepositAccount object called flah
TimeDepositAccount flah = new TimeDepositAccount(5,5);
flah.deposit(10000);
System.out.println(flah.getBalance());
flah.addInterest();
System.out.println(flah.getBalance());
flah.addInterest();
System.out.println(flah.getBalance());
flah.deposit(1000);
System.out.println(flah.getBalance());
flah.addInterest();
System.out.println(flah.getBalance());
flah.withdraw(5000);
System.out.println(flah.getBalance());
- -

flah.addInterest();
System.out.println(flah.getBalance());
flah.addInterest();
System.out.println(flah.getBalance());
flah.withdraw(5000);
System.out.println(flah.getBalance());
}
}

EJ F
PolymorphismTest.java
public class PolymorphismTest
{
/* This program is used to test the principles of polymorphism
*/
// The main method
public static void main(String [] args)
{
// construct new SavingAccount object called abdalah
SavingAccount abdalah = new SavingAccount(0.5);
// construct new TimeDepositAccount object called flah
TimeDepositAccount flah = new TimeDepositAccount(1,3);
// construct new CheckingAccount object called baker
CheckingAccount baker = new CheckingAccount(0);
abdalah.deposit(10000);
flah.deposit(10000);
printBalance("abdalah ",abdalah);
printBalance("flah ",flah);
printBalance("baker ",baker);
// transfer 1000Sr from abdalah to baker
abdalah.transfer(baker,2000);
// transfer 1000Sr from flah to baker
flah.transfer(baker,980);
- -

printBalance("abdalah ",abdalah);
printBalance("flah ",flah);
printBalance("baker ",baker);
baker.withdraw(500);
printBalance("baker ",baker);
baker.withdraw(80);
printBalance("baker ",baker);
baker.withdraw(400);
printBalance("baker ",baker);
endOfMonth(abdalah);
endOfMonth(flah);
endOfMonth(baker);
printBalance("abdalah ",abdalah);
printBalance("flah ",flah);
printBalance("baker ",baker);
}
public static void endOfMonth(SavingAccount savings)
{savings.addInterest();
}
public static void endOfMonth(CheckingAccount checking)
{checking.deductFees();
}
public static void printBalance(String name , BankAccount account)
{System.out.println("The balance of " + name +
"account is " + account.getBalance()+" SR");
}
}

EJ F

The balance of abdalah account is 10000.0 SR


The balance of flah account is 10000.0 SR
The balance of baker account is 0.0 SR
The balance of abdalah account is 8000.0 SR
The balance of flah account is 9000.0 SR
The balance of baker account is 2980.0 SR
The balance of baker account is 2480.0 SR
The balance of baker account is 2400.0 SR
The balance of baker account is 2000.0 SR
The balance of abdalah account is 8040.0 SR
The balance of flah account is 9090.0 SR
The balance of baker account is 1996.0 SR

PolymorphismTest

- -


]<gj]<]<j<^]<]

K
K
try K
catch K
finally K

K
W

- -


Exception Handling

syntax error

Error codes

W
J

The basics of java Exception Handling

Error codes

program
JVM

K
- -

JVM

exception

handler

K
KK

EJ F
EdF

(-)

EJ F
Process completed
(compiler)

EF

Exception in thread "main" java.lang.ArithmeticException: /by zero at Excp1.main <Excp1.java:6>


- -

ArithmaticException
EJ F/by

zero

(-)


EJ F

a[2] = 6;EJ F

Exception in thread "main" java.lang.ArrayIndexOutOfBoundException at Excp1.main <Excp3.java:9>

ArrayIndexOutOfBoundException
- -

EJ F

EJ F
- -

Exception types

class classes

Throwable

java.langError

subclassException subclass

program related

JVM

root classException

ExceptionEJ F

ArithmaticException

ExceptionEJ

ArrayIndexOutOfBoundsException

ClassNotFoundException

FileNotFoundException

IOException

NullPointerException

null reference

root classError

OutOfMemoryError class JVM


K
- -

Exception Handling In java

abcde-

try block
catch blocks
finally block
throw statement
throws clause

trycatch finally blocks :


try
catch

finally catch

try
W

try
// Tested statements
catch ( ExceptionType 1 exob1)
// exception handler for ExceptionType1
catch ( ExceptionType 2 exob2)
// exception handler for ExceptionType2
finally
// Statements that must be executed

EJ F

d ArithmaticException

Wtry

try
int d=0;
int a=60/d;

- -

Wcatch

catch (ArithmeticException e)

System.out.println("divide by zero");
System.out.println(e.getMessage());

EJ F

ArithmeticException

divide by zero

/by

zeroe

After Exception Handling

EJ F

a[2]ArrayIndexOutOfBoundsException


try
W

try
a[0]=2;
a[1]=4;
a[2]=6;

- -

(-)

(-)
- -

WcatchArrayIndexOutOfBoundsException

catch (ArrayIndexOutOfBoundsException e)

System.out.println("Array Index out of bounds.."+ e);

finally
Ktry

EJ F

(e)
Array

Index

out

of

bounds

java.lang.ArrauIndexOutofBoundsException
Wfinally

The code here must be executed

(-)

- -

EJ F
finally

catch

try

catch
K

EJ F
try

ArithmeticExceptioncatch
KArrayIndexOutOfBoundsException

Handling the first Exception divide by zero


/by zero

finally

The code here must be executed

W
Ktry

( -)

Handling the second Exception Array Index out of bounds


Array Index out of bounds java.lang.ArrauIndexOutofBoundsException
The code here must be executed

finally
Ktry
- -

(-)

(-)
- -

- -

- -

- -

DivideByZeroException.java
Created with JBuilder
// DivideByZeroException.java
// Definition of class DivideByZeroException.
// Used to throw an exception when a
// divide-by-zero is attempted.
public class DivideByZeroException
extends ArithmeticException {
public DivideByZeroException()
{
super( "Attempted to divide by zero" );
}
public DivideByZeroException( String message )
{
super( message );
}

NegativeNumberException.java
Created with JBuilder
// NegativeNumberException.java
// Definition of class NegativeNumberException.
// Used to throw an exception when a
// negative number is intered
public class NegativeNumberException
extends ArithmeticException {
public NegativeNumberException()
{
super( "Attempted to Enter negative numbers" );
}
}

- -

DivideByZeroTest.java
Created with JBuilder
// DivideByZeroTest.java
// A simple exception handling example.
// Checking for a divide-by-zero exception
// and negative number exception
import java.text.DecimalFormat;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DivideByZeroTest extends JFrame
implements ActionListener {
private JTextField input1, input2, output;
private int number1, number2;
private double result;
// Initialization
public DivideByZeroTest()
{
super( "Demonstrating Exceptions" );
Container c = getContentPane();
c.setLayout( new GridLayout( 3, 2 ) );
c.add( new JLabel( "Enter numerator ",
SwingConstants.RIGHT ) );
input1 = new JTextField( 10 );
c.add( input1 );
c.add(
new JLabel( "Enter denominator and press Enter ",
SwingConstants.RIGHT ) );
input2 = new JTextField( 10 );
c.add( input2 );
input2.addActionListener( this );
c.add( new JLabel( "RESULT ", SwingConstants.RIGHT ) );
output = new JTextField();
c.add( output );
setSize( 425, 100 );
show();
}
- -

// Process GUI events


public void actionPerformed( ActionEvent e )
{
DecimalFormat precision3 = new DecimalFormat( "0.000" );
output.setText( "" ); // empty the output JTextField
try {
number1 = Integer.parseInt( input1.getText() );
number2 = Integer.parseInt( input2.getText() );
if(number1 < 0 || number2 <0)
throw new NegativeNumberException();
result = quotient( number1, number2 );
output.setText( precision3.format( result ) );
}
catch ( NumberFormatException nfe ) {
JOptionPane.showMessageDialog( this,
"You must enter two integers",
"Invalid Number Format",
JOptionPane.ERROR_MESSAGE );
}
catch ( DivideByZeroException dbze ) {
JOptionPane.showMessageDialog( this, dbze.toString(),
"Attempted to Divide by Zero",
JOptionPane.ERROR_MESSAGE );
}
catch ( NegativeNumberException nne ) {
JOptionPane.showMessageDialog( this, nne.toString(),
"Attempted to Enter negative numbers",
JOptionPane.ERROR_MESSAGE );
}
}
// Definition of method quotient. Used to demonstrate
// throwing an exception when a divide-by-zero error
// is encountered.
public double quotient( int numerator, int denominator )
throws DivideByZeroException
{
if ( denominator == 0 )
throw new DivideByZeroException();
return ( double ) numerator / denominator;
}
public static void main( String args[] )
{
DivideByZeroTest app = new DivideByZeroTest();
- -

app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
e.getWindow().dispose();
System.exit( 0 );
}
}
);
}
}

UsingException.java
Created with JBuilder
// UsingExceptions.java
// Demonstration of the try-catch-finally
// exception handling mechanism.
public class UsingException {
public static void main( String args[] )
{
try {
throwException();
}
catch ( Exception e )
{
System.err.println( "Exception handled in main" );
}
doesNotThrowException();
}
public static void throwException() throws Exception
{
// Throw an exception and immediately catch it.
try {
System.out.println( "Method throwException" );
throw new Exception(); // generate exception
}
catch( Exception e )
{
System.err.println(
"Exception handled in method throwException" );
throw e; // rethrow e for further processing
// any code here would not be reached
}
- -

finally {
System.err.println(
"Finally executed in throwException" );
}
// any code here would not be reached
}
public static void doesNotThrowException()
{
try {
System.out.println( "Method doesNotThrowException" );
}
catch( Exception e )
{
System.err.println( e.toString() );
}
finally {
System.err.println(
"Finally executed in doesNotThrowException" );
}
System.out.println(
"End of method doesNotThrowException" );
}
}
UsingException1.java
Created with JBuilder
// UsingExceptions.java
// Demonstration of stack unwinding.
public class UsingException1 {
public static void main( String args[] )
{
try {
throwException();
}
catch ( Exception e ) {
System.err.println( "Exception handled in main" );
}
}
public static void throwException() throws Exception
{
// Throw an exception and catch it in main.
try {
System.out.println( "Method throwException" );
throw new Exception(); // generate exception
}
catch( RuntimeException e ) { // nothing caught here
- -

System.err.println( "Exception handled in " +


"method throwException" );
}
finally {
System.err.println( "Finally is always executed" );
}
}
}

UsingException2.java
Created with JBuilder
// UsingExceptions.java
// Demonstrating the getMessage and printStackTrace
// methods inherited into all exception classes.
public class UsingException2 {
public static void main( String args[] )
{
try {
method1();
}
catch ( Exception e ) {
System.err.println( e.getMessage() + "\n" );
e.printStackTrace();
}
}
public static void method1() throws Exception
{
method2();
}
public static void method2() throws Exception
{
method3();
}
public static void method3() throws Exception
{
throw new Exception( "Exception thrown in method3" );
}
}

- -


]<gj]<]<j<^]<]

K K
K

- -

Event Handling

command line

console application

graphical user interface (GUI)

pull down menu Text field


close window click button

Event Sources Event listeners Event

java window manager


eventsevent


mouse event

W event listener
Keyboard events

mouse move events

mouse click events


Window close events

Button click events


- -

event listener classes


K

event source
event listener

W user interface component

Button click eventsbutton

menu selection eventmenu

scrollbar adjustment eventscrollbar

Kevent source
W

an applet

MouseEventThe event class J


EyxF

MouseListenerThe listener class J



MouseEvent

component
The event source J
the applet

EJ FEventObject event classes

getSourceEventObjectK


getYgetXMouseEvent

- -

EventObject

AWTEvent

ActionEvent

Component Event

InputEvent

MouseEvent

WindowEvent

KeyEvent

EJ F


MouseListener interface

public interface Mouselistener


{
void mouseClicked (MouseEvent event)
// called when the mouse has been clicked on a component
void mouseEntered (MouseEvent event)
// called when the mouse enters a component
void mouseExited (MouseEvent event)
// called when the mouse exits a component
void mousePressed (MouseEvent event)
// called when the mouse button has been presseded on a component
void mouseReleaseded (MouseEvent event)
// called when the mouse button has been releaseded on a component
}

- -

MouseSpy
EYxFMouselistener

EJ F

appletaddMouseListener

addMouseListenerMouseSpy

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.

//listen to mouse evnts in an applet


import java.awt.*;
import java.applet.*;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
public class MouseSpyApplet extends Applet
{
public MouseSpyApplet()
{
MouseSpy listener = new MouseSpy();
addMouseListener(listener);
}
}
class MouseSpy implements MouseListener
{
public void mouseClicked (MouseEvent event)
{
System.out.println("Mouse cliked. x= " +event.getX() +
" Y= " +event.getY());
}
public void mouseEntered (MouseEvent event)
{
System.out.println("Mouse entered. x= " +event.getX() +
" Y= " +event.getY());
}
public void mouseExited (MouseEvent event)
{
System.out.println("Mouse exited. x= " +event.getX() +
" Y= " +event.getY());
}
public void mousePressed (MouseEvent event)
{
System.out.println("Mouse pressed. x= " +event.getX() +
" Y= " +event.getY());
}
public void mouseReleased (MouseEvent event)
{
System.out.println("Mouse released. x= " +event.getX() +
" Y= " +event.getY());
}
41. }
(-)

- -


the applet
EJ F
EJ F

mousePressedy=147x=474
mouseReleasedy=161x=168

y=103x=94
mouseClickedmouseReleasedmousePressed
y=286x=216 applet

y=319x=239 mouseEntered

KmouseExited

EJ F
- -

Event Adapter

listener

Klistener methods
mouse click
mouse releasedmouse pressed

methods
1. class MouseClickListener implements MouseListener
2. {
3. public void mouseClicked (MouseEvent event)
4. {
5.
// mouse click action here
6. }

7. public void mouseEntered (MouseEvent event)


8.
{
9.
// do nothing
10. }
11. public void mouseExited (MouseEvent event)
12. {
13.
// do nothing
14. }
15. public void mousePressed (MouseEvent event)
16. {
17.
// do nothing
18.
19. }
20. public void mouseReleased (MouseEvent event)
21. {
22.
// do nothing
23.
24. }
25. }
methods MouseListener interface adapter class
do nothing
1. class MouseAdapter implements MouseListener
2. // This class is defined in the java.awt.event package
3. {
4. public void mouseClicked (MouseEvent event)
5. {
6.
// do nothing
7. }
8. public void mouseEntered (MouseEvent event)
9.
{
- -

10.
// do nothing
11. }
12. public void mouseExited (MouseEvent event)
13. {
14.
// do nothing
15. }
16. public void mousePressed (MouseEvent event)
17. {
18.
// do nothing
19. }
20. public void mouseReleased (MouseEvent event)
21. {
22.
// do nothing
23. }
24. }

MouseAddapterK
class MouseClickListener extends MouseAdapter
{
public void mouseClicked (MouseEvent event)
{
// mouse click action here
}

ActionListener listener interface


implement interface

java.awt.event extend the adapter


E F

two methods adapter class

WindowListener

Implementing Listener as inner class

System.out

ellipse EJ F
K

import java.awt.*;

W
- -

import java.applet.*;
import java.awt.event.*;
import java.awt.geom.*;
public class EggApplet extends Applet
{
public EggApplet()
{
egg = new Ellipse2D.Double(0,0,EGG_WIDTH, EGG_HIGHT);
}
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
g2.draw(egg);
}
private Ellipse2D.Double egg;
private static final double EGG_WIDTH = 30;
private static final double EGG_HIGHT = 50;

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import java.awt.geom.*;
public class EggApplet extends Applet
{
public EggApplet()
{
egg = new Ellipse2D.Double(0,0,EGG_WIDTH, EGG_HIGHT);
// add mouse click listener
MouseClickListener listener = new MouseClickListener();
addMouseListener(listener);
}
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
g2.draw(egg);
}
private Ellipse2D.Double egg;
private static final double EGG_WIDTH = 30;
private static final double EGG_HIGHT = 50;
class MouseClickListener extends MouseAdapter
{
public void mouseClicked(MouseEvent event)
- -

int mouseX=event.getX();
int mouseY=event.getY();
// now move the ellipse to (mouseX, MouseY)
egg.setFrame(mouseX-EGG_WIDTH/2, mouseY-EGG_HIGHT/2,
EGG_WIDTH, EGG_HIGHT);
repaint();

MouseClickListener

KEggApplet

C:\programming 3\chapter10\EggApplet\EggApplet.java:52: cannot resolve symbol


symbol : variable EGG_WIDTH
location: class MouseClickListener
egg.setFrame(mouseX-EGG_WIDTH/2, mouseY-EGG_HIGHT/2,
^
C:\programming 3\chapter10\EggApplet\EggApplet.java:52: cannot resolve symbol
symbol : variable EGG_HIGHT
location: class MouseClickListener
egg.setFrame(mouseX-EGG_WIDTH/2, mouseY-EGG_HIGHT/2,
^
C:\programming 3\chapter10\EggApplet\EggApplet.java:53: cannot resolve symbol
symbol : variable EGG_WIDTH
location: class MouseClickListener
EGG_WIDTH, EGG_HIGHT);
^
C:\programming 3\chapter10\EggApplet\EggApplet.java:53: cannot resolve symbol
symbol : variable EGG_HIGHT
location: class MouseClickListener
EGG_WIDTH, EGG_HIGHT);
^
C:\programming 3\chapter10\EggApplet\EggApplet.java:52: cannot resolve symbol
symbol : variable egg
location: class MouseClickListener
egg.setFrame(mouseX-EGG_WIDTH/2, mouseY-EGG_HIGHT/2,
^
C:\programming 3\chapter10\EggApplet\EggApplet.java:54: cannot resolve symbol
symbol : method repaint ()
location: class MouseClickListener
repaint();
^
6 errors
Process completed.

- -

event listener
inner class

instance variables
Class OuterClassName
{

accessSpecifier
{
methods
variables
}

class

InnerClassName

EJ FEJ F

1. // using inner class


2. import java.awt.*;
3. import java.applet.*;
4. import java.awt.event.*;
5. import java.awt.geom.*;
6. public class EggApplet extends Applet
7. {
8. public EggApplet()
9. {
10. egg = new Ellipse2D.Double(0,0,EGG_WIDTH, EGG_HIGHT);
11. // add mouse click listener
12. MouseClickListener listener = new MouseClickListener();
13. addMouseListener(listener);
14. }
15. public void paint(Graphics g)
16. {
17. Graphics2D g2 = (Graphics2D)g;
18. g2.draw(egg);
19. }
20. private Ellipse2D.Double egg;
21. private static final double EGG_WIDTH = 30;
22. private static final double EGG_HIGHT = 50;
23. // inner class definition
24.
25. private class MouseClickListener extends MouseAdapter
26. {
- -

27. public void mouseClicked(MouseEvent event)


28. {
29. int mouseX=event.getX();
30. int mouseY=event.getY();
31. // now move the ellipse to (mouseX, MouseY)
32. egg.setFrame(mouseX-EGG_WIDTH/2, mouseY-EGG_HIGHT/2,
33. EGG_WIDTH, EGG_HIGHT);
34. repaint();
35. }
36. }
37. }

EJ F

EJ F

- -

Frame Windows

applets

java applications

bordertitle barframe window

javax.swingJFrame
showsetTitlesetSize

EJ Fwindow manager

main

JFrameEmptyFrame

frame

main EmptyFrame

1. import javax.swing.JFrame;
2. public class FrameTest1
3. { public static void main (String[] args)
4.
{ EmptyFrame frame = new EmptyFrame();
5.
frame.setTitle("frameTest");
6.
frame.show();
7.
}
8. }
9. class EmptyFrame extends JFrame
10. {
11. public EmptyFrame()
12. {
13. final int DEFAULT_FRAME_WIDTH =300;
14. final int DEFAULT_FRAME_HIGHT =300;
15. setSize(DEFAULT_FRAME_WIDTH, DEFAULT_FRAME_HIGHT);
16. }
17. }

EJ F

main

graphical programsconsole programs

new thread
main

threadmain
- -

System.exit(0)

mainK

public class FrameTest1


public static void main (String[] args)
{ EmptyFrame frame = new EmptyFrame();
frame.setTitle("frameTest");
frame.show();
System.exit(0); // Error

window events

dispose

EF K

window listener
WWindowListener

Public interface WindowListener

void windowOpend(windowEvent e);


void windowClosed(windowEvent e);
void windowActivated(windowEvent e);
void windowDeactivated(windowEvent e);
void windowIconified(windowEvent e);
void windowDeiconfied(windowEvent e);
- -

void windowClosing(windowEvent e);

JFrame

System.exit JFrame K

windowClosing

WindowListener WindowAdapter
WindowCloser

do

class WindowCloser extends WindowAdapter

nothing

WindowAdapter

public void windowClosing(WindowEvent event)


System.exit(0);

WindowCloser
EJ FaddWindowListener
import javax.swing.JFrame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class FrameTest2
{
public static void main (String[] args)
{ EmptyFrame frame = new EmptyFrame();
frame.setTitle("Close me!");
frame.show();
}
}
class EmptyFrame extends JFrame
{public EmptyFrame()
{
final int DEFAULT_FRAME_WIDTH =300;
final int DEFAULT_FRAME_HIGHT =300;
setSize(DEFAULT_FRAME_WIDTH, DEFAULT_FRAME_HIGHT);
WindowCloser listener = new WindowCloser();
addWindowListener(listener1);
- -

private class WindowCloser extends WindowAdapter


public void windowClosing(WindowEvent event)
System.exit(0);

EJ F

EJ F

- -


]<gj]<]<j<^]<]

K
W
W
K K
K

K K

K K

- -


W



K

components

objects
W


JLabel
JTextField
JButton
JCheckBox

JcomboBox
JList
JPanel

swing

Java 2 javax.swing

swing K1.2 platform


KPure Java Components
- -

AWT
GUI

button platform

KApple Macintosh Apple Macintosh

swing

K
swing
JLabel

KGUI JLabel
JLabel

K
WJLabel
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

// Demonstrating the JLabel class.


// Java core packages
import java.awt.*;
import java.awt.event.*;
// Java extension packages
import javax.swing.*;
public class LabelTest extends JFrame {
private JLabel label1, label2, label3;
// set up GUI
public LabelTest()
{
super( "Testing JLabel" );
// get content pane and set its layout
Container container = getContentPane();
container.setLayout( new FlowLayout() );
// JLabel constructor with a string argument

- -

24
25

label1 = new JLabel( "Label with text" );


label1.setToolTipText( "This is label1" );

26
27
28
29

container.add( label1 );
// JLabel constructor with string, Icon and
// alignment arguments

30
31
32

Icon bug = new ImageIcon( "bug1.gif" );


label2 = new JLabel( "Label with text and icon",
bug, SwingConstants.LEFT );

33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58

label2.setToolTipText( "This is label2" );


container.add( label2 );
// JLabel constructor no arguments
label3 = new JLabel();
label3.setText( "Label with icon and text at bottom" );
label3.setIcon( bug );
abel3.setHorizontalTextPosition(SwingConstants.CENTER );
label3.setVerticalTextPosition( SwingConstants.BOTTOM );
label3.setToolTipText( "This is label3" );
container.add( label3 );
setSize( 275, 170 );
setVisible( true );
}
// execute application
public static void main( String args[] )
{
LabelTest application = new LabelTest();
application.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
}
}

// end class LabelTest

- -

K JLabelEF
JLabelKEJ FLabelTest Constructor

KK?Label with text?

setToolTipText

Kcontent pane label1


Iconswing
KsetIcon

ImageIcon Icon interface

KGPEGGIF, PNGWimage formats

bug1.gif KImageIcon

folder ImageIcon
Kbug Icon ImageIconK

KIconImageIconIconImageIcon

JLabel J JLabel

bug?Label with text and Icon?label

KLabel

KSwingConstants.LEFT
K label

setHorizontalAlignment label
Klabel2 tool tip KsetVerticalAlignment
label Kcontent pane

label3 setText
label3 setIcon KgetText label

J KgetIcon

setVerticalTextPosition setHorizontalTextPosition
- -

Klabel
K

label3 label3
Kcontent pane

- -

KJPasswordFieldJTextField
JPasswordField JTextField
JPasswordFieldK

enter K
event

Klistener

JPasswordField JTextField

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

// Demonstrating the JTextField class.


// Java core packages
import java.awt.*;
import java.awt.event.*;
// Java extension packages
import javax.swing.*;
public class TextFieldTest extends JFrame {
private JTextField textField1, textField2, textField3;
private JPasswordField passwordField;
// set up GUI
public TextFieldTest()
{
super( "Testing JTextField and JPasswordField" );
Container container = getContentPane();
container.setLayout( new FlowLayout() );
// construct textfield with default sizing
textField1 = new JTextField( 10 );
container.add( textField1 );
// construct textfield with default text
textField2 = new JTextField( "Enter text here" );
container.add( textField2 );
// construct textfield with default text and
// 20 visible elements and no event handler
textField3 = new JTextField( "Uneditable text field", 20 );
textField3.setEditable( false );
container.add( textField3 );
// construct textfield with default text
passwordField = new JPasswordField( "Hidden text" );

- -

39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92

container.add( passwordField );
// register event handlers
TextFieldHandler handler = new TextFieldHandler();
textField1.addActionListener( handler );
textField2.addActionListener( handler );
textField3.addActionListener( handler );
passwordField.addActionListener( handler );
setSize( 325, 100 );
setVisible( true );
}
// execute application
public static void main( String args[] )
{
TextFieldTest application = new TextFieldTest();
application.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
}
// private inner class for event handling
private class TextFieldHandler implements ActionListener {
// process text field events
public void actionPerformed( ActionEvent event )
{
String string = "";
// user pressed Enter in JTextField textField1
if ( event.getSource() == textField1 )
string = "textField1: " + event.getActionCommand();
// user pressed Enter in JTextField textField2
else if ( event.getSource() == textField2 )
string = "textField2: " + event.getActionCommand();
// user pressed Enter in JTextField textField3
else if ( event.getSource() == textField3 )
string = "textField3: " + event.getActionCommand();
// user pressed Enter in JTextField passwordField
else if ( event.getSource() == passwordField ) {
JPasswordField pwd =
( JPasswordField ) event.getSource();
string = "passwordField: " +
new String( passwordField.getPassword() );
}
JOptionPane.showMessageDialog( null, string );
}
}

// end private inner class TextFieldHandler

- -

93
94

// end class TextFieldTest

JPasswordField JTextField J

KJ constructors

textField1 K textField1

Kcontent pane

?Enter Text Here?textField2

Kcontent paneK
- -

JTextField textField3
KEF,?Uneditable Text field?

false setEditable
Kcontent paneK

?Hidden Text? PasswordField passwordField


K
K asterisks

Kcontent pane

TextFieldHandler
ActionListener interface EJ F
K ActionListener TextFieldHandler
Handler TextFieldHandler

Kevent-listener

handler J
EenterF

KactionPerformed

actionPerformed

ActionEvent getSource

getActionCommand String string

TextField ActionEvent
JPasswordField getPassword
K

- -

JButtonEF

command buttons, check boxes, radio buttons


K

KCommand Buttons
K ActionEvent

KJButton

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

// Creating JButtons.
// Java core packages
import java.awt.*;
import java.awt.event.*;
// Java extension packages
import javax.swing.*;
public class ButtonTest extends JFrame {
private JButton plainButton, fancyButton;
// set up GUI
public ButtonTest()
{
super( "Testing Buttons" );
// get content pane and set its layout
Container container = getContentPane();
container.setLayout( new FlowLayout() );
// create buttons
plainButton = new JButton( "Plain Button" );
container.add( plainButton );
Icon bug1 = new ImageIcon( "bug1.gif" );
Icon bug2 = new ImageIcon( "bug2.gif" );
fancyButton = new JButton( "Fancy Button", bug1 );
fancyButton.setRolloverIcon( bug2 );
container.add( fancyButton );
// create an instance of inner class ButtonHandler
// to use for button event handling
ButtonHandler handler = new ButtonHandler();
fancyButton.addActionListener( handler );
plainButton.addActionListener( handler );

- -

38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64

setSize( 275, 100 );


setVisible( true );
}
// execute application
public static void main( String args[] )
{
ButtonTest application = new ButtonTest();
application.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
}
// inner class for button event handling
private class ButtonHandler implements ActionListener {
// handle button event
public void actionPerformed( ActionEvent event )
{
JOptionPane.showMessageDialog( null,
"You pressed: " + event.getActionCommand() );
}
}
}

// end private inner class ButtonHandler

// end class ButtonTest

- -

JButtons
KJLabel
KEJ FButtonHandlerinner class

fancyButton plainButton W JButton


K

K?plain button? plainButton


Kcontent pane

JButton
rollover icon
ImageIcon J K

K rolover icon
K

Kbug1 ? Fancy Button? fancyButton


setRolloverIcon K

K
Kcontent pane

J ActionEvent EJTextField F JButton


J K listener

actionPerformedButtonHandler
K

- -

KJCheckBox
JCheckBox
E F JCheckBox

JTextField
K
K

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

// Creating Checkbox buttons.


// Java core packages
import java.awt.*;
import java.awt.event.*;
// Java extension packages
import javax.swing.*;
public class CheckBoxTest extends JFrame {
private JTextField field;
private JCheckBox bold, italic;
// set up GUI
public CheckBoxTest()
{
super( "JCheckBox Test" );
// get content pane and set its layout
Container container = getContentPane();
container.setLayout( new FlowLayout() );
// set up JTextField and set its font
field =
new JTextField( "Watch the font style change", 20 );
field.setFont( new Font( "Serif", Font.PLAIN, 14 ) );
container.add( field );
// create checkbox objects
bold = new JCheckBox( "Bold" );
container.add( bold );
italic = new JCheckBox( "Italic" );
container.add( italic );
// register listeners for JCheckBoxes
CheckBoxHandler handler = new CheckBoxHandler();
bold.addItemListener( handler );
italic.addItemListener( handler );
setSize( 275, 100 );
setVisible( true );

- -

44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86

}
// execute application
public static void main( String args[] )
{
CheckBoxTest application = new CheckBoxTest();
application.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
}
// private inner class for ItemListener event handling
private class CheckBoxHandler implements ItemListener {
private int valBold = Font.PLAIN;
private int valItalic = Font.PLAIN;
// respond to checkbox events
public void itemStateChanged( ItemEvent event )
{
// process bold checkbox events
if ( event.getSource() == bold )
if ( event.getStateChange() == ItemEvent.SELECTED )
valBold = Font.BOLD;
else
valBold = Font.PLAIN;
// process italic checkbox events
if ( event.getSource() == italic )
if ( event.getStateChange() == ItemEvent.SELECTED )
valItalic = Font.ITALIC;
else
valItalic = Font.PLAIN;
// set text field font
field.setFont(
new Font( "Serif", valBold + valItalic, 14 ) );
}
}
}

// end private inner class CheckBoxHandler

// end class CheckBoxTest

- -

K PLAINserif
KJ JCheckBox
KJCheckBox

ItemEvent
ItemListener

KitemStateChanged

bold itemStateChanged

K event.getSource() Kitalic

getStateChanged J if/else bold


W ItemEvent

EItemEvent.DESELECTED ItemEvent.SELECTEDF
valBold Font.BOLD

italic K Font.PLAIN
valItalic Font.ITALIC

valItalic valBoldK Font.PLAIN


KJTextFieldJ

- -

KJRadioButton
JCheckBox JRadioButton
radio buttons H Eselected and deselectedF

JRadioButtonsKdeselected

F ButtonGroup
Ejavax.swing

KJRadioButtons

JCheckBox

radio buttonsK
K

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

// Creating radio buttons using ButtonGroup and JRadioButton.


// Java core packages
import java.awt.*;
import java.awt.event.*;
// Java extension packages
import javax.swing.*;
public class RadioButtonTest extends JFrame {
private JTextField field;
private Font plainFont, boldFont, italicFont, boldItalicFont;
private JRadioButton plainButton, boldButton, italicButton,
boldItalicButton;
private ButtonGroup radioGroup;
// create GUI and fonts
public RadioButtonTest()
{
super( "RadioButton Test" );
// get content pane and set its layout
Container container = getContentPane();
container.setLayout( new FlowLayout() );
// set up JTextField
field =
new JTextField( "Watch the font style change", 25 );
container.add( field );

- -

32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86

// create radio buttons


plainButton = new JRadioButton( "Plain", true );
container.add( plainButton );
boldButton = new JRadioButton( "Bold", false);
container.add( boldButton );
italicButton = new JRadioButton( "Italic", false );
container.add( italicButton );
boldItalicButton = new JRadioButton(
"Bold/Italic", false );
container.add( boldItalicButton );
// register events for JRadioButtons
RadioButtonHandler handler = new RadioButtonHandler();
plainButton.addItemListener( handler );
boldButton.addItemListener( handler );
italicButton.addItemListener( handler );
boldItalicButton.addItemListener( handler );
// create logical relationship between JRadioButtons
radioGroup = new ButtonGroup();
radioGroup.add( plainButton );
radioGroup.add( boldButton );
radioGroup.add( italicButton );
radioGroup.add( boldItalicButton );
// create font objects
plainFont = new Font( "Serif", Font.PLAIN, 14 );
boldFont = new Font( "Serif", Font.BOLD, 14 );
italicFont = new Font( "Serif", Font.ITALIC, 14 );
boldItalicFont =
new Font( "Serif", Font.BOLD + Font.ITALIC, 14 );
field.setFont( plainFont );
setSize( 300, 100 );
setVisible( true );
}
// execute application
public static void main( String args[] )
{
RadioButtonTest application = new RadioButtonTest();
application.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
}
// private inner class to handle radio button events
private class RadioButtonHandler implements ItemListener {
// handle radio button events
public void itemStateChanged( ItemEvent event )
{

- -

87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106

// user clicked plainButton


if ( event.getSource() == plainButton )
field.setFont( plainFont );
// user clicked boldButton
else if ( event.getSource() == boldButton )
field.setFont( boldFont );
// user clicked italicButton
else if ( event.getSource() == italicButton )
field.setFont( italicFont );
// user clicked boldItalicButton
else if ( event.getSource() == boldItalicButton )
field.setFont( boldItalicFont );
}
}
}

// end private inner class RadioButtonHandler

// end class RadioButtonTest

JRadioButton J
content pane
ElabelF JRadioButton
KselecttrueK

ItemEvent JCheckBox JRadioButtons


) RadioButtonHandler J K

ItemEvent (J
KJRadioButtons

- -

radioGroup ButtonGroup
JRadioButton
ButtonGroup add J K
KradioGroupJRadioGroup

ItemListener EJ F RadioButtonHandler
KJRadioButton ItemEvent
radioGroup JRadioButton
EJ F itemStateChanged
KgetSource

JComboBox
K JComboBox
JRadioButtonJCheckBoxJComboBox
KKItemEvent
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

// Using a JComboBox to select an image to display.


// Java core packages
import java.awt.*;
import java.awt.event.*;
// Java extension packages
import javax.swing.*;
public class ComboBoxTest extends JFrame {
private JComboBox imagesComboBox;
private JLabel label;
private String names[] =
{ "bug1.gif", "bug2.gif", "travelbug.gif", "buganim.gif" };
private Icon icons[] = { new ImageIcon( names[ 0 ] ),
new ImageIcon( names[ 1 ] ), new ImageIcon( names[ 2 ] ),
new ImageIcon( names[ 3 ] ) };
// set up GUI
public ComboBoxTest()
{
super( "Testing JComboBox" );

- -

25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71

// get content pane and set its layout


Container container = getContentPane();
container.setLayout( new FlowLayout() );
// set up JComboBox and register its event handler
imagesComboBox = new JComboBox( names );
imagesComboBox.setMaximumRowCount( 3 );
imagesComboBox.addItemListener(
// anonymous inner class to handle JComboBox events
new ItemListener() {
// handle JComboBox event
public void itemStateChanged( ItemEvent event )
{
// determine whether check box selected
if ( event.getStateChange() == ItemEvent.SELECTED )
label.setIcon( icons[
imagesComboBox.getSelectedIndex() ] );
}
}

// end anonymous inner class

); // end call to addItemListener


container.add( imagesComboBox );
// set up JLabel to display ImageIcons
label = new JLabel( icons[ 0 ] );
container.add( label );
setSize( 350, 100 );
setVisible( true );
}
// execute application
public static void main( String args[] )
{
ComboBoxTest application = new ComboBoxTest();
application.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
}
}

// end class ComboBoxTest

- -

JComboBox


K JLabelIcon

iconsJ

names StringImageIcon
K

names JComboBox
EF K K
KEF

KK

JComboBoxsetMaximumRowCount
K

EF J K
KimagesComboBox ItemListener
EJ F itemStateChanged

- -

icons Klabel
KgetSelectedIndex

Layout Managers
Containers GUI Components

WKContainer

java.awt.Applet, FlowLayout

java.awt.Panel, javax.swing.Jpanel.
K

Content pane BorderLayout


WJApplet JFrame
K

K GridLayout
K

FlowLayout
1
2
3
4
5
6
7
8
9
10
11
12
13
14

// Demonstrating FlowLayout alignments.


// Java core packages
import java.awt.*;
import java.awt.event.*;
// Java extension packages
import javax.swing.*;
public class FlowLayoutDemo extends JFrame {
private JButton leftButton, centerButton, rightButton;
private Container container;
private FlowLayout layout;
- -

15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69

// set up GUI and register button listeners


public FlowLayoutDemo()
{
super( "FlowLayout Demo" );
layout = new FlowLayout();
// get content pane and set its layout
container = getContentPane();
container.setLayout( layout );
// set up leftButton and register listener
leftButton = new JButton( "Left" );
leftButton.addActionListener(
// anonymous inner class
new ActionListener() {
// process leftButton event
public void actionPerformed( ActionEvent event )
{
layout.setAlignment( FlowLayout.LEFT );
// re-align attached components
layout.layoutContainer( container );
}
}

// end anonymous inner class

); // end call to addActionListener


container.add( leftButton );
// set up centerButton and register listener
centerButton = new JButton( "Center" );
centerButton.addActionListener(
// anonymous inner class
new ActionListener() {
// process centerButton event
public void actionPerformed( ActionEvent event )
{
layout.setAlignment( FlowLayout.CENTER );
// re-align attached components
layout.layoutContainer( container );
}
}
);
container.add( centerButton );
- -

70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105

// set up rightButton and register listener


rightButton = new JButton( "Right" );
rightButton.addActionListener(
// anonymous inner class
new ActionListener() {
// process rightButton event
public void actionPerformed( ActionEvent event )
{
layout.setAlignment( FlowLayout.RIGHT );
// re-align attached components
layout.layoutContainer( container );
}
}
);
container.add( rightButton );
setSize( 300, 75 );
setVisible( true );
}
// execute application
public static void main( String args[] )
{
FlowLayoutDemo application = new FlowLayoutDemo();
application.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
}
}

// end class FlowLayoutDemo

- -

FlowLayout JButtons
Left

Center Right
K

Container Layout
setLayout
KLayout.setAlignment

BorderLayout

W Container

K K

K container
K K
K

K
WBorderLayout
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

// Demonstrating BorderLayout.
// Java core packages
import java.awt.*;
import java.awt.event.*;
// Java extension packages
import javax.swing.*;
public class BorderLayoutDemo extends JFrame
implements ActionListener {
private JButton buttons[];
private String names[] = { "Hide North", "Hide South",
"Hide East", "Hide West", "Hide Center" };
- -

17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64

private BorderLayout layout;


// set up GUI and event handling
public BorderLayoutDemo()
{
super( "BorderLayout Demo" );
layout = new BorderLayout( 5, 5 );
// get content pane and set its layout
Container container = getContentPane();
container.setLayout( layout );
// instantiate button objects
buttons = new JButton[ names.length ];
for ( int count = 0; count < names.length; count++ ) {
buttons[ count ] = new JButton( names[ count ] );
buttons[ count ].addActionListener( this );
}
// place buttons in BorderLayout; order not important
container.add( buttons[ 0 ], BorderLayout.NORTH );
container.add( buttons[ 1 ], BorderLayout.SOUTH );
container.add( buttons[ 2 ], BorderLayout.EAST );
container.add( buttons[ 3 ], BorderLayout.WEST );
container.add( buttons[ 4 ], BorderLayout.CENTER );
setSize( 300, 200 );
setVisible( true );
}
// handle button events
public void actionPerformed( ActionEvent event )
{
for ( int count = 0; count < buttons.length; count++ )
if ( event.getSource() == buttons[ count ] )
buttons[ count ].setVisible( false );
else
buttons[ count ].setVisible( true );
// re-layout the content pane
layout.layoutContainer( getContentPane() );
}
// execute application
public static void main( String args[] )
- -

65
66
67
68
69
70
71
72

{
BorderLayoutDemo application = new BorderLayoutDemo();
application.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
}
}

// end class BorderLayoutDemo

GridLayout
Grid container

KGridLayoutK
1
2
3
4
5
6

// Demonstrating GridLayout.
// Java core packages
import java.awt.*;
import java.awt.event.*;
- -

7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61

// Java extension packages


import javax.swing.*;
public class GridLayoutDemo extends JFrame
implements ActionListener {
private JButton buttons[];
private String names[] =
{ "one", "two", "three", "four", "five", "six" };
private boolean toggle = true;
private Container container;
private GridLayout grid1, grid2;
// set up GUI
public GridLayoutDemo()
{
super( "GridLayout Demo" );
// set up layouts
grid1 = new GridLayout( 2, 3, 5, 5 );
grid2 = new GridLayout( 3, 2 );
// get content pane and set its layout
container = getContentPane();
container.setLayout( grid1 );
// create and add buttons
buttons = new JButton[ names.length ];
for( int count = 0; count < names.length; count++ ) {
buttons[ count ] = new JButton( names[ count ] );
buttons[ count ].addActionListener( this );
container.add( buttons[ count ] );
}
setSize( 300, 150 );
setVisible( true );
}
// handle button events by toggling between layouts
public void actionPerformed( ActionEvent event )
{
if ( toggle )
container.setLayout( grid2 );
else
container.setLayout( grid1 );
toggle = !toggle;
// set toggle to opposite value
container.validate();
}
// execute application
public static void main( String args[] )
{
- -

62
63
64
65
66
67
68

GridLayoutDemo application = new GridLayoutDemo();


application.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
}
}

// end class GridLayoutDemo

- -

WE

a) buttonName =JButton(Caption);
b) JLabel aLabel, JLabel;
c) TextField = new JTextField(50, Default Text);
d) Container c = getContentPane();
setLayout (new BorderLayout());
button1 = newJButton (North Star);
button2 = newJButton (South Pole);
c.add(button1);
c.add(button2);

E
OK
X: 8

Snap to Grid

Cancel

Show Grid
Y: 8

Help

E
K

EJTextFieldJButtons F

7
4
1
0

8
5
2
.

9
6
3
=
- -

/
*
+


]<gj]<]<j<^]<]

KK

W
W
K
K

K
K

- -

variable scope

K
K


K
W

Sequential Access Files Ka

Random Access Files Kb

W Text files Ki
Characters
W Binary files Kii
Bytes

- -

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20


K
import java.io.*;
//Class Definition
class ReadTextFilel
{
public static void main (String args[]) throws IOException
{
String fileName = c:/temp/toRead.txt;
String line;
BufferedReader in = new BufferedReader (new
FileReader (filename) );
line = in.readLine();
while (line != null) // continue until end of file;
{
System.out.prinln(line);
Line = in.readLine();
}
in.close();
}
}

java.io package W
K

ReadTextFile1 W J

? main
main ?FileNotFound
Kthrows IOException

- -

W
fileName

String fileName = c:/temp/toRead.txt;

line W
K

BufferedReader in WJ
fileName

KFileReader
BufferedReader in = new BufferedReader (new FileReader (fileName) );

in W
K

line = in.readln ();


linein

K
W

EwhileF
Knull

while (line != null)

WJ
{

K
System.out.prinln(line);
line = in.readLine();

}
- -

Kin

in.close();

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

import java.io.*;
class ReadWithTokenizer
{
public static void main (String args[]) throws IOException
{
String fileName = c:/temp/toRead.txt;
BufferedReader in = new BufferedReader (
new FileReader (fileName) );
StreamTokenizer reader = new StreamTokenizer(in);
reader.nextToken();
While (reader.ttype != StreamTokenizer.TT_EOF)
//continue until end of file
{
String word = reader.sval;
System.out.println (word);
Reader.nextToken();
}
in.close();
}
}

- -

java.io package W
K

ReadwithTokenizerWJ
Kmain

W
String fileName = c:/temp/toRead.txt;

KfileName

BufferedReader in WJ

fileName

KFileReader
BufferedReader in = new BufferedReader (new FileReader (fileName) );
W
Tokens

readerStreamTokenizer
StreamTokenizer reader = new StreamTokenizer(in);

nextToken()W

KreaderStreamTokenizer
reader.nextToken();
W
abstracted

StreamTokenizerTT_EOF
while (reader.ttype != StreamTokenizer.TT_EOF)
- -

reader.nextTokenW

reader

Ksvalnval
String word = reader.sval;
W
System.out.println (word);

reader.nextToken ();
WW
in.close ();

While (reader.nextToken() != StreamTokenizer.TT_EOF)


//continue until end of file
{
if (reader.ttype == StreamTokenizer.TT_WORD)
System.out.println( A word: + reader.sval);
Else if (reader.ttype == StreamTokenizer.TT_NUMBER)
System.out.println( A number: + reader.nal);
}
StreamTokenizer

TT_NUMBERStringTT_WORD

readerK

WKttype
if (reader.ttype == StreamTokenizer.TT_WORD)
- -

WK

1
2
3
5
6
7
8
9
10
11
12
13
14
15
16

import java.io.*;
public class WriteTextFile
{
public static void main (String args[] throws IOExcepetion
{
String filename = reaper.txt
PrintWriter print = new PrintWriter( new BufferedWriter (
new FileWriter (filename)));
print.println(College of Telecommunication and Information);
print.println(Computer Department);
print.println(Programming);
print.println(Java 3);
print.close();
}
}


KPrintWriterprint

println print
K

- -

KK

1
2 import java.io.*
3 class ReadWrite
4 {
5
public static void main(String[] args) throws IOException
6
{
7
String[] line = new String[10];
8
load (line);
9
10
/* --------m ----------------*/
11
12
commit (line);
13
}
14
//
15
Public static void load (String[] line) throws IOException
16
17 {
String filename =c:/temp/toRead.txt;
18
BufferedReader in = new BufferedReader (new
19
FileReader(filename));
20
Line[0] = in.readln();
21
int i = 0;
22
while (line[i] != null) //
23
24
{
25
System.out.println(line[i]);
26
i++;
27
Line[i] = in.readln();
28
}
29
in.close();
30
}
- -

31 //
32
33
public static void commit (String[] line) throws IOException
34 {
35
String filename =c:/temp/toRead.txt;
36
BufferedWriter print = new BufferedWriter (new
37
38 FileWriter(filename));
39
int i = 0;
40
while (line[i] != null) //
41
{
42
print.println(line[i]);
43
i++;
44
}
45
print.close();
46
}
47
48 }

- -

E
________________________________________________________

________________________________________________________

________________________________________________________

WE

_______________________________________K

_______________________________________K

WEE

_______________________________________K

_______________________________________K

E
EADTFK


K
- -


]<gj]<]<j<^]<]

K
W
W
K
K

- -

Random- Sequential files W

access files
K

K
Relational Database

Structured systems
Query Language (SQL)

K
K SQL

Microsoft Access, Sybase, Oracle, Informix, Microsoft SQL W

Microsoft KServer
KSQL OracleAccess

Books

KOracleAccess

ISBN W
W

- -

Primary F

AutherID

FirstName

LastName

YearBorn

EKey

AutherId
1
2
3

FirstName
Ali
Salem
Abdullah

W
LastName
Suliman
Khalid
Amer

YearBorn
1960
1975
1963

EF


PublisherID

PublisherName

PublisherID
1
2

PublisherName
Prentice Hall
Prentice Hall PTR

ISBN

ISBN

ISBN

AutherID

- -

WISBN

ISBN
0-13-010671-2
0-13-015231-2
0-14-044131-7
0-11-028271-4
0-10-070471-1

AutherID
1
2
1
3
2


ISBN

ISBN

Title
EditionNo

YearPublished

PublisherId

ISBN

Title

0-13-010671-2
0-13-015231-2
0-14-044131-7
0-11-028271-4
0-10-070471-1

C How to program
C++ How to Program
Java How to program
Oracle PL/SQL
Internet Programming

:
Edition YearPublisherID
No
Published
2
1994
1
3
1997
1
2
1992
1
2
1999
2
1
1998
1

Access Relational database Management Systems


KOracle

- -

KW

SELECT * from Author


ORDER BY FirstName

KJTable

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

// Fig. 18.24: TableDisplay.java


// This program displays the contents of the Authors table
// in the Books database.
import java.sql.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class TableDisplay extends JFrame {
private Connection connection;
private JTable table;
public TableDisplay()
{
// The URL specifying the Books database to which
// this program connects using JDBC to connect to a
// Microsoft ODBC database.
String url = "jdbc:odbc:Books";
String username = "anonymous";
String password = "guest";
// Load the driver to allow connection to the database
try {
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
connection = DriverManager.getConnection(
- -

28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69

url, username, password );


}
catch ( ClassNotFoundException cnfex ) {
System.err.println(
"Failed to load JDBC/ODBC driver." );
cnfex.printStackTrace();
System.exit( 1 ); // terminate program
}
catch ( SQLException sqlex ) {
System.err.println( "Unable to connect" );
sqlex.printStackTrace();
}
getTable();
setSize( 450, 150 );
show();
}
private void getTable()
{
Statement statement;
ResultSet resultSet;
try {
String query = "SELECT * FROM Author";
statement = connection.createStatement();
resultSet = statement.executeQuery( query );
displayResultSet( resultSet );
statement.close();
}
catch ( SQLException sqlex ) {
sqlex.printStackTrace();
}
}
private void displayResultSet( ResultSet rs )
throws SQLException
{
// position to first record
- -

70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111

boolean moreRecords = rs.next();


// If there are no records, display a message
if ( ! moreRecords ) {
JOptionPane.showMessageDialog( this,
"ResultSet contained no records" );
setTitle( "No records to display" );
return;
}
setTitle( "Authors table from Books" );
Vector columnHeads = new Vector();
Vector rows = new Vector();
try {
// get column heads
ResultSetMetaData rsmd = rs.getMetaData();
for ( int i = 1; i <= rsmd.getColumnCount(); ++i )
columnHeads.addElement( rsmd.getColumnName( i ) );
// get row data
do {
rows.addElement( getNextRow( rs, rsmd ) );
} while ( rs.next() );
// display table with ResultSet contents
table = new JTable( rows, columnHeads );
JScrollPane scroller = new JScrollPane( table );
getContentPane().add(
scroller, BorderLayout.CENTER );
validate();
}
catch ( SQLException sqlex ) {
sqlex.printStackTrace();
}
}
private Vector getNextRow( ResultSet rs,
ResultSetMetaData rsmd )
throws SQLException
- -

112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153

{
Vector currentRow = new Vector();
for ( int i = 1; i <= rsmd.getColumnCount(); ++i )
switch( rsmd.getColumnType( i ) ) {
case Types.VARCHAR:
currentRow.addElement( rs.getString( i ) );
break;
case Types.INTEGER:
currentRow.addElement(
new Long( rs.getLong( i ) ) );
break;
default:
System.out.println( "Type was: " +
rsmd.getColumnTypeName( i ) );
}
return currentRow;
}
public void shutDown()
{
try {
connection.close();
}
catch ( SQLException sqlex ) {
System.err.println( "Unable to disconnect" );
sqlex.printStackTrace();
}
}
public static void main( String args[] )
{
final TableDisplay app = new TableDisplay();
app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
app.shutDown();
System.exit( 0 );
}
- -

154
155
156

}
);
}
}

import java.sql.*
Classes java.sql

private Connection connection;


Connection Object

SQL
KTransactions

TableDisplay Class Constructor


KgetTable

String url = "jdbc:odbc:Books";


String username = "anonymous";
String password = "guest";

URL W

odbc jdbc
password username K

ODBC

jdbc.odbc.jdbcodbcDriver Driver
K

Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
class forName

Database driver
- -

try block java.lang.classNotFound


Kcatch block
connection = DriverManager.getConnection(url, username, password );
DriverManager getConnection
K URL
java.sql.sqlException
KgetTable

displayResultSet gettable
KJTable

Statement statement

Ejava.sql F Statement SQL


SQL

ResultSet resultSet

resultSet
KSQL

statement = connection.createStatement();
statement CreateStatement

resultSet = statement.executeQuery(query);
executeQuery

displayResult resultSetK
K

displayResultSet

boolean moreRecords = rs.next();

moreRecords

next ResultSet

BooleannextK

ETrueF
- -

Vector KEFalseF
ResultSet

KResultSetJTableResultSet
W

ResultSetMetaData rsmd = rs.getMetaData();


ResultSet

MetaData

ResultSetMetaData Krsmd

getColumnCount ResultSet
getColumnName
W

do

rows.addElement (getNextRow (rs, rsmd ) );


while (rs.next() );
getNextRow ResultSet


ResultSet rs.next()
KResultSet

JTable

ResultSetMetaData ResultSet E F getNextRow


KResultSet

Kcloseshutdown

- -

KODBCBooks.mdb??

ODBC

KODBC
W

WindowsControl Panel

KODBC Data Sources


Add User DSN

KMicrosoft Access DriverAccess


K

- -

ODBC Microsoft Access

Data JDBC

KSource Name

- -

DescriptionEF
Select K

EBooks.mdbF K
OK K

Advanced K
anonymous K
guest K

OK K
ODBC Microsoft Access SetupOKK K

ODBC Data Source AdministratorOKK K

- -

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

// DisplayQueryResults.java
// This program displays the ResultSet returned by a
// query on the Books database.
import java.sql.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class DisplayQueryResults extends JFrame {
// java.sql types needed for database processing
private Connection connection;
private Statement statement;
private ResultSet resultSet;
private ResultSetMetaData rsMetaData;
- -

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

// javax.swing types needed for GUI


private JTable table;
private JTextArea inputQuery;
private JButton submitQuery;
public DisplayQueryResults()
{
super( "Enter Query. Click Submit to See Results." );
// The URL specifying the Books database to which
// this program connects using JDBC to connect to a
// Microsoft ODBC database.
String url = "jdbc:odbc:test";
String username = "moh";
String password = "moh";
// Load the driver to allow connection to the database
try {
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
connection = DriverManager.getConnection(
url, username, password );
}
catch ( ClassNotFoundException cnfex ) {
System.err.println(
"Failed to load JDBC/ODBC driver." );
cnfex.printStackTrace();
System.exit( 1 ); // terminate program
}
catch ( SQLException sqlex ) {
System.err.println( "Unable to connect" );
sqlex.printStackTrace();
System.exit( 1 ); // terminate program
}
// If connected to database, set up GUI
inputQuery =
new JTextArea( "SELECT * FROM Authors", 4, 30 );
submitQuery = new JButton( "Submit query" );
submitQuery.addActionListener(
new ActionListener() {
public void actionPerformed( ActionEvent e )
- -

59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100

{
getTable();
}
}
);
JPanel topPanel = new JPanel();
topPanel.setLayout( new BorderLayout() );
topPanel.add( new JScrollPane( inputQuery),
BorderLayout.CENTER );
topPanel.add( submitQuery, BorderLayout.SOUTH );
table = new JTable( 4, 4 );
Container c = getContentPane();
c.setLayout( new BorderLayout() );
c.add( topPanel, BorderLayout.NORTH );
c.add( table, BorderLayout.CENTER );
getTable();
setSize( 500, 500 );
show();
}
private void getTable()
{
try {
String query = inputQuery.getText();
statement = connection.createStatement();
resultSet = statement.executeQuery( query );
displayResultSet( resultSet );
}
catch ( SQLException sqlex ) {
sqlex.printStackTrace();
}
}
private void displayResultSet( ResultSet rs )
throws SQLException
{
- -

101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142

// position to first record


boolean moreRecords = rs.next();
// If there are no records, display a message
if ( ! moreRecords ) {
JOptionPane.showMessageDialog( this,
"ResultSet contained no records" );
setTitle( "No records to display" );
return;
}
Vector columnHeads = new Vector();
Vector rows = new Vector();
try {
// get column heads
ResultSetMetaData rsmd = rs.getMetaData();
for ( int i = 1; i <= rsmd.getColumnCount(); ++i )
columnHeads.addElement( rsmd.getColumnName( i ) );
// get row data
do {
rows.addElement( getNextRow( rs, rsmd ) );
} while ( rs.next() );
// display table with ResultSet contents
table = new JTable( rows, columnHeads );
JScrollPane scroller = new JScrollPane( table );
Container c = getContentPane();
c.remove( 1 );
c.add( scroller, BorderLayout.CENTER );
c.validate();
}
catch ( SQLException sqlex ) {
sqlex.printStackTrace();
}
}
private Vector getNextRow( ResultSet rs,
ResultSetMetaData rsmd )
throws SQLException
- -

143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
171
172
173
174
175
176
177
178
179
180
181
182
183

{
Vector currentRow = new Vector();
for ( int i = 1; i <= rsmd.getColumnCount(); ++i )
switch( rsmd.getColumnType( i ) ) {
case Types.VARCHAR:
case Types.LONGVARCHAR:
currentRow.addElement( rs.getString( i ) );
break;
case Types.INTEGER:
currentRow.addElement(
new Long( rs.getLong( i ) ) );
break;
default:
System.out.println( "Type was: " +
rsmd.getColumnTypeName( i ) );
}
return currentRow;
}
public void shutDown()
{
try {
connection.close();
}
catch ( SQLException sqlex ) {
System.err.println( "Unable to disconnect" );
sqlex.printStackTrace();
}
}
public static void main( String args[] )
{
final DisplayQueryResults app =
new DisplayQueryResults();
app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
app.shutDown();
- -

184
185
186
187
188

System.exit( 0 );
}
}
);
}}

- -

W E

___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________

K E

K

K K
K K

- -


Java How to Program, Deitel and Deitel, Fourth Edition

- -

.........................................................................................

.............................................................................

....................................................................................................................

....................................................................................................................

.............................................................................

....................................................................................................................

....................................................................................................................

..................................................................................................

....................................................................................................................

............................................................................................

.................................................................................................................

....................................................................................................................

........................................................................................................

........................................................................................................

......................................................................................

...........................................................................................................

..................................................................................................

...........................................................................................................

...................................................................................
......

.........................................................................................................................................

.........................................................................................

swing

.........................................................................................

JLabel

.............................

........................................................................................

JButton

.........................................................................................

JComboBox

................................................................................

JPassWordFieldJTextField

JRadioButton

............................................................................................

JComboBox

............................................................................................

.....................................................................................................

.............................................................................................................................

.................................................................................................................

.................................................................................................................

.................................................................................................................

...................................................................................

..............................................................................................................

..............................................................................................................

..........................

..............................................................................................................

.......................................................................

ODBC


EF
GOTEVOT appreciates the financial support provided by BAE SYSTEMS

You might also like