Anda di halaman 1dari 246

Java

( )



()


Java
Java




Java web site
web site
Java









Java





2546

Java

Java code

JDK
path
code application applet
Java application
execute HelloWorld
Java applet
Java EditPlus
Java

1
2

13

Keyword
Primitive datatype

final

integer
operator
short byte
cast

Mathematical Functions
Character
boolean
Logical operator
Relational operator
bit (shift bitwise)

13
14

(Repetition)

if
if
if else
Conditional operator ? :
switch

for loop
StreamTokenizer
while loop
do while

4
5
6
7
8
12

15
16
18
19
23
26
26
29
32
33
35
37
39
43
45
49
51
58
58
60
68
69
72
73
77
80
83

ii

break continue
Nested loop
labeled continue labeled break

86
88
90

Array String

96

Array
Array
array clone copy array
array
array

array array
array
String
Array of characters
String Java
String

String
StringBuffer
array String
5

97
101
104
106
106
108
109
111
113
115
116
118
120
121
125
129

Objects Classes

133

Class class
class
Method
method class
method
parameter list
pass by value

class
Constructor
constructor constructor
overload method
class class
Package
package

134
136
136
138
140
141
143
149
150
153
155
156
162

class class

this super()
protected
override method
Polymorphism
object
interface

168
168
171
175
179
181

iii
7

Error (Exceptions)

188

throw exception
try catch
try catch loop
printStacktrace()
throw try
exception

188
190
192
192
195
198

Streams I/O

204

File
FileNameFilter
Input Output streams
FileReader
FileInputStream read()
StreamTokenizer FileReader
BufferedReader
delimiter text file
FileWriter PrintWriter
Binary file
DataInputStream FileInputStream
DataOutputStream FileOutputStream
writeUTF() readUTF()
PrintWriter
writeChars()
Random-access file
seek()
update record

205
208
210

211
213
217
218
218
221

224
228
229
233
234
240

ASCII UNICODE ()
Constant

Escape sequences
Format

Java
application applet

o
o
o
o
o
o

Java
application
applet
HTML execute applet
Java EditPlus

Java

Java code
Java
code
computer (platform) compile pc

code compile execute pc


apple, linux, unix, JVM Java Virtual Machine
Java
OOP Object-Oriented Programming
(user)
(procedural language programming)
Java download

Sun Micro System


Sun
download
Java
1. Text Editor source
code
2. JDK (Java Development Kit) version J2SE 1.4
download http://sun.java.com JDK compile

3. Java VM Java Virtual Machine


code
compile code execute (code
machine
code) VM JDK

(
)

1
Java

Java

( pc)
1. JDK
2. path compile execute (run)
path Java

JDK
download JDK JDK self-extracting
file
execute (doubling click click
icon file enter) j2se1.4.1 35.9 MB
download ( speed download )
64.6 MB
install JDK
JDK version
path

Windows 9x path


1. autoexec.bat path JDK J2SDK 1.4.1
drive c path autoexec.bat
set path=c:\j2sdk1.4.1\bin set path
set path ; (semicolon) path
c:\j2sdk1.4.1\bin
2. path ( autoexec.bat)
Command Prompt ( dos window) set path
(dos) Command Prompt

3. directory JDK drive c:\j2sdk1.4.1\bin


directory
directory java
Windows XP Windows 2000 path (Windows XP
Windows 2000
path
Windows XP)
1. mouse icon My Computer (
start
My Computer) Properties

1
Java

Java

2. advanced System Properties

3. Environment Variables

4. System Variables Path

5. Edit

1
Java

Java

6. ; (semicolon) path install JDK OK


path
path (
path path )


Java
path path

execute code Java JRE


Java Run-time Environment code compile JDK
execute JRE execute
JDK
JRE
Sun
Java Java
Java download JRE

code application code applet
Applet code
execute web browser HTML
download applet application
execute command line ( download)
code application
(SDK tools)

Java Development Kit

J2SDK Java 2 Software Development Kit


Java
javac

compile (compiler)

source code
byte code

java

execute byte code


application

appletviewer execute applet


java

application applet
1-1 1-2 code editor text editor
editor format Microsoft Word
ASCII SDK execute text editor SDK

1
Java

Java

Text Editor

Java Class File


First.class

Javac

Java Source File


First.java
Java

Java Program
Output

1-1 application

Text Editor

Java Class File


First.class

Javac

Java Source File


First.java

appletviewer

HTML file
First.html

Java Program
Output

1-2 applet

Java application
text editor free

Java
user (execute)
HelloWorld.java
class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
keyword

1
Java

Java

class HelloWorld Java class code


class
class method main() execute JRE method
main() execute method main() keyword
public, static, void
parameter array String C
C++ method main()
Parameter method main() String[] args command-line argument

method main() System.out.println("")
System.out console window dos window
dos prompt 1-3

1.3 compile run

compile HelloWorld

1-3 compile javac



javac HelloWorld.java
compile compiler
error message compile HelloWorld .java
error
E:\bc221Book\source>javac HelloWorld
javac: invalid flag: HelloWorld
Usage: javac <options> <source files>
where possible options include:
-g
Generate all debugging info
-g:none
Generate no debugging info
-g:{lines,vars,source} Generate only some debugging info

( java - )
execute HelloWorld
compile HelloWorld error execute
java
java HelloWorld
output 1-3

1
Java

Java

execute
.class
( )
compiler error (java.lang.NoClassDefFoundError)

application
1. compile javac
2. execute java

(comment)



comment
Java
1. //
2. /* */
comment 1

comment comment
/* */
HelloWorld comment
// My first Java program - HelloWorld
class HelloWorld {
/* Java launcher will call this method (main).
This will display a message to the screen.
*/
public static void main(String[] args) {
System.out.println("Hello World");
}
}
Java applet
Java applet 2 Java
source file HTML file applet web
browser application
//my first Java applet - HelloWorldApplet
import java.applet.Applet;
import java.awt.Graphics;
public class HelloWorldApplet extends Applet {
public void paint(Graphics g) {
g.drawString("Hello World", 25, 25);
}
}

1
Java

Java

applet web browser

(inheritance)
Java extends Applet class HelloWorldApplet

Java
applet
method paint() method applet
method drawstring() class Graphics
g.drawString("Hello World", 25, 25);
compile HelloWorldApplet javac execute applet
HTML
<html>
<applet code="HelloWorldApplet.class" width="200" height="80"></applet>
</html>
applet tag HTML Java compile
field code applet field width ()
field height
execute HelloWorldApplet.html appletviewer
output

applet
1. Java source file extends Applet
2. HTML file applet tag applet (1) class file
Java (2) applet width height
applet
Java class method Java

Java program EditPlus


HelloWorld.java
run Dos Window
Operating System
Windows

Thai Edition OS

Dos Window
Java



Text Editor EditPlus ( Text Editor
EditPlus )

1
Java

Java

EditPlus Java
download www.editplus.com shareware
30

install menu
Tools

Preferences

click Fonts Default (edit window) Drop-down menu


Area
font Tahoma
Output window

1
Java

Java

10

set editor output window


set EditPlus
compile execute Java click User tools
Preferences Add Tool>> Program

Menu Text:
Command:
Argument:
Initial directory:

Compile Java Source File

install Java c:\j2sdk1.4.1\bin\javac.exe


$(FileName) drop-down list
$(FileDir) drop-down list

9 Capture output

1
Java

Java

11

EditPlus run execute


compile
Add tool>>

OK EditPlus

HelloWorld.java

System.out.println()
class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World! ");
}
}
compile Ctrl + 1 compile

run Ctrl + 2

1
Java

Java

12

EditPlus features set


help file EditPlus Text
Editor Crimson editor
download WWW
Java
Java Sun Microsystems
Oak
Sun Sun Oak Sun
Oak
Oak Sun
Silk, Ruby, WRL (Web
Runner Language)

Java (
)
Java version version Java J2SDK1.4.1
version download web site Sun


(data) (variable)
(calculation evaluation)


Java


o
o
o
o
o
o
o

(variable declaration) integer floating-point

character boolean
(assignment)
(statement expression)
(calculation evaluation)
(casting)
(Mathematical Functions) Java

(data and variable)


354 + 45 * 12








(memory) compiler
(address offset)


integer
double float
compiler
compiler
Java

1. (letter) _ (underscore) $ (dollar
sign)
2. Java
( operator Java + () () * () / () )

taxRate
pricePerUnit

2
Java

14

_timeInSecond
$systemClock
unit897
Java Unicode1


text editor code



variable identifier
identifier ()


keyword reserved word Java
2.1
2.1 keyword
abstract
const
boolean
continue
break
default
byte
do
case
double
catch
else
char
extends
class
final

finally
float
for
goto
if
implements
import
instanceof

int
interface
long
native
new
package
private
protected

public
return
short
static
strictfp
super
switch
synchronized

this
throws
throws
transient
try
void
volatile
while

(datatype)


datatype identifier
datatype Java datatype
primitive datatype reference ( reference )
Java primitive datatype 8 2.2
2.2 primitive
datatype
boolean
byte
short
int
long
float
double
char

datatype

(bit)
8 true false
8
16
32
64
32
64
16

datatype
bit 2.3
datatype

2 byte ( ASCII 1 byte)

2
Java

2.3 primitive datatype


datatype


byte
-128
short
-32768
int
-2147483648
long
-9223372036854775808
float
-3.4 x 1038
double
-1.7 x 10308

15

127
32767
2147483647
9223372036854775807
3.4 x 1038
1.7 x 10308

int numberOfBikes;
float taxRate;
double interests, PI;
boolean yesOrNo;
char response;


_ (underscore)
int number_of_bikes;
float tax_rate;
double cum_gpa;
boolean yes_or_no;






letterGrade

gpa cumulativeGPA
(Assignment)
= ( assignment operator)
" (rvalue) =

(lvalue) =" rvalue
lvalue (physical
memory)
numberOfBikes = 2;
area = PI * r * r;
taxReturned = calculateTaxReturned(income);

2 = numberOfBikes;
PI * r * r = area;
calculateTaxReturned(income) = taxReturned;

(1)

(2) (standard I/O channel)

2
Java

16

/*
* Variables.java - Variable decalration and initialization
*/
class Variables {
public static void main(String[] args) {
boolean booleanVar = true;
byte byteVar = 0;
short shortVar = 0;
int intVar = 0;
long longVar = 0L;
float floatVar = 0.0F;
double doubleVar = 0.0D;
char charVar = 'A';

System.out.println("boolean variable and its initial


value is " + booleanVar);
System.out.println("byte variable and its initial
value is " + byteVar);
System.out.println("short variable and its initial
value is " + shortVar);
System.out.println("int variable and its initial
value is " + intVar);
System.out.println("long variable and its initial
value is " + longVar);
System.out.println("float variable and its initial
value is " + floatVar);
System.out.println("double variable and its initial
value is " + doubleVar);
System.out.println("char variable and its initial
value is " + charVar);

boolean true
Java
0L 0.0F 0.0D long float
double Java
float double

float Java double

Variables.java
boolean variable and its initial value is true
byte variable and its initial value is 0
short variable and its initial value is 0
int variable and its initial value is 0
long variable and its initial value is 0

2
Java

17

float variable and its initial value is 0.0


double variable and its initial value is 0.0
char variable and its initial value is A
Java (

)
long longVar = 0L;

long longVar;
longVar = 0L;
long longVar; longVar long longVar
= 0L; 0 longVar ( 2.1
Java)
code





double price = 0.0D, tax = 0.7D, returned = 0.0D, interests = 0.0D,
principal = 10000.0D;

long longVar;

longVar = 0L;

???

long
longVar Java

0
longVar

2.1



range

127
byte int


int length = 2, height = 8, width = 4;
double angles = 30.5, distance = 24.50;

2
Java

18

, (comma)


int cats = 90, float tax = 0.50; // ERROR mixed-type declaration
// and initialization

double radius;
radius = 2.54;

int one = 1, two = 2, three = one + two;


Java
one two
three


compiler three = one + two;
one + two
three

final
PI

Java user
(reserved word) final
final
keyboard

/*
* Final.java - Use of final keyword
*/
class Final {
public static void main(String[] args) {
final double PI = 3.14;
int radius = 2;

double area = radius * radius * PI;


System.out.println("Area of a circle is " + area);

compile run
Area of a circle is 12.56

Final.java PI
FinalWithError.java compiler
/*
* FinalWithError.java - Changing the value of final keyword
*/

2
Java

19

class FinalWithError {
public static void main(String[] args) {
final double PI = 3.14;
int radius = 2;
double area = radius * radius * PI;
System.out.println("Area of a circle is " + area);

PI = 3.142;
area = radius * radius * PI;
System.out.println("Area of a circle is " + area);

compile
FinalWithError.java:14: cannot assign a value to final variable PI
PI = 3.142;
^
1 error
error Java error 14
compile error
error (
error)
final


149, 600,000 (1.496 x 108)
(electron mass)
0.0000000000000000000000000009 (9.0 x 10-28)
(scientific notation)
final double sunDistance = 1.496E8; // 1.496 x 108
final float electronMass = 9.0E-28F;
// 9.0 x 10-28


27 (
) code


(?)
(life-time and scope)


(block) {}
/* Scope.java - Showing scope of variables */
class Scope {
public static void main(String[] args) {
int x = 5, y = 8;

2
Java

20

System.out.print("Value of x is ");
System.out.println(" Value of y is " + y);
{

int x = 45; //error x is already defined


int w = 89;
System.out.println("Value of x in brackets is " + x);
System.out.println("Value of y in brackets is " + y);

}
//error w is out of scope
System.out.println("Value of w is " + w);

Scope.java compile
compiler (1) int x main() (2) int w
scope

block int x int w
Scope.java:13 x is already defined in main(java.lang.String[])
int x = 45;
^
Scope.java:19: cannot resolve symbol
symbol : variable w
location: class Scope
System.out.println("Value of w is " + w);
^
2 errors
C++ block
( Scope.java) Java
block

/* Scope2.java - Showing scope of variables */


class Scope2 {
static int x = 8, y;
public static void main(String[] args) {
{
int x;
x = 5;
y = x;
System.out.println("Value of y is " + y);
}
y = x;
System.out.println("Value of y is " + y);
}
}

Scope2.java compile
Value of y is 5
Value of y is 8
compiler x block
x scope static Java
class variable
y

2
Java

21

block x y
class variable x

/* Scope2v1.java - Showing scope of variables */


class Scope2v1 {
static int x = 8, y;
public static void main(String[] args) {
{
//int x;
x = 5;
y = x;
System.out.println("Value of y is " + y);
}
y = x;
System.out.println("Value of y is " + y);
}
}
Scope2v1.java x
method main()
8 x block x 5
run

Value of y is 5
Value of y is 5

/* Scope3.java - Showing scope of variables */


class Scope3 {
static int x;
public static void main(String[] args) {
int x = (x = 12) + 8;
System.out.println("Value of local x is " + x);
}
}
Scope3.java

x scope
class Scope3 scope method main() compile

Value of local x is 20

x Java int x = (x = 12) + 8;


Java x code x
4 Scope3v1.java
/* Scope3v1.java - Showing scope of variables */
class Scope3v1 {
static int x = 4;
public static void main(String[] args) {
int x = x + 8;

2
Java

22

System.out.println("Value of local x is " + x);

compile Java x block compiler error


Scope3v1.java:8 variable x might not have been initialized
int x = x + 8;
^
1 error
compile code Scope4.java
/* Scope4.java - Showing scope of variables */
class Scope4 {
public static void main(String[] args) {
int x = (x = 12) + 8;
System.out.println("Value of local x is " + x);
}
}
Scope4.java Scope3.java

compile run
Scope3.java Java code
Scope5.java ( compile)
/* Scope5.java - Showing scope of variables */
class Scope5 {
public static void main(String[] args) {
int x = x + 8;
System.out.println("Value of local x is " + x);
}
}
compiler error
Scope5.java:7: variable x might not have been initialized
int x = x + 8;
^
1 error
error error
compile Scope3v1.java (
x
)
/* Scope6.java - Showing scope of variables */
class Scope6 {
public static void main(String[] args) {
int x = 12, y = x + 8;
System.out.println("Value of local y is " + y);
}
}
compile run

2
Java

23

Value of local y is 20
x
y



scope scope method, class



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

class variable
instance variable
array component
method parameter
constructor parameter
exception-handler parameter
local variable

1 (class variable) 7 (local variable)


(statement and expression)
Java (statement) ; (semicolon)

int priceOfBook = 125;


float taxReturn;
;

int

priceOfBook
=
125
;

Java ;

code
code


/* Scope2v1.java - Showing scope of variables* @author faa
xumsai*/class Scope2v1{static int x = 8, y;public static void
main(String[] args) { {int x;x = 5;y = x;System.out.println("Value of
y is " + y);}y = x; System.out.println("Value of y is " + y);}}
code
(indentation)


Expression Java

2
Java

24

(mathematical evaluation) (relational


evaluation)
operator
+ (), (), * (), /
() % ( integer)
operator
/* Operators.java - Shows mathematical operators */
class Operators {
public static void main(String[] args) {
int i, j, k;
//generate random number between 1 and 10
j = 1 + (int)(Math.random() * 10);
k = 1 + (int)(Math.random() * 10);
System.out.println("j = " + j + " and k = " + k);

//evaluate
i = j + k;
i = j - k;
i = j * k;
i = j / k;
i = j % k;
}

and display results of math


System.out.println("j + k =
System.out.println("j - k =
System.out.println("j * k =
System.out.println("j / k =
System.out.println("j % k =

operators
" + i);
" + i);
" + i);
" + i);
" + i);



method
random() class Math ( Java ) method random() 0 0.9+
0 1 1 ( n
0.0 <= n < 1.0) 10 1 1 10
i operator

run
j
j
j
j
j
j

=
+
*
/
%

5
k
k
k
k
k

and k = 2
= 7
= 3
= 10
= 2
= 1

method random() run



Operator
%
integer

i = j % k;
k 2 j 5
( 1) i
int double

2
Java

25

/* Operators.java - Shows mathematical operators */


import java.util.Random;
class Operators {
public static void main(String[] args) {
//do the ints
int i, j, k;
//generate random number between 1 and 10
Random rand = new Random();
j = 1 + rand.nextInt(10);
k = 1 + rand.nextInt(10);
System.out.println("j = " + j + " and k = " + k);
//evaluate
i = j + k;
i = j - k;
i = j * k;
i = j / k;
i = j % k;

and display results of math


System.out.println("j + k =
System.out.println("j - k =
System.out.println("j * k =
System.out.println("j / k =
System.out.println("j % k =

operators
" + i);
" + i);
" + i);
" + i);
" + i);

//do the doubles


double v1, v2, v3;
//generate random double between 1.0 and 10.0 (exclusive)
v1 = 1.0 + rand.nextDouble() * 9;
v2 = 1.0 + rand.nextDouble() * 9;
System.out.println("v1 = " + v1 + " v2 = " + v2);
v3 = v1 + v2; System.out.println("v1 + v2 = " + v3);
v3 = v1 - v2; System.out.println("v1 - v2 = " + v3);
v3 = v1 * v2; System.out.println("v1 * v2 = " + v3);
v3 = v1 / v2; System.out.println("v1 / v2 = " + v3);

Operators.java operator
i j
(random) method nextInt(max value) method 0
max value max value 1 10
1 method

/* Operators1.java - Shows mathematical operators */


class Operators1 {
public static void main(String[] args) {
int a, b, c, d, e;
b
c
d
e

=
=
=
=

1
1
1
1

+
+
+
+

(int)(Math.random()
(int)(Math.random()
(int)(Math.random()
(int)(Math.random()

*
*
*
*

10);
10);
10);
10);

System.out.print("b = " + b + " c = " + c);


System.out.println(" d = " + d + " e = " + e);
a = b + c - d; System.out.println("Value of a is " + a);
a = b * c - d; System.out.println("Value of a is " + a);

2
Java

26

a = b / c * d; System.out.println("Value of a is " + a);

run
b = 8
Value
Value
Value

c = 2 d
of a is
of a is
of a is

= 6 e = 5
4
10
24

(precedence)
operator
( )
2.4
2.4 Operator Precedence
Operator
(), [], ., postfix ++, postfix -unary +, unary , prefix ++, prefix -(datatype), new
*, /, %
+, <<, >>, >>>
<, <=, >, >=, instance of
==, !=
&
^
|
&&
||
?:
=, +=, -=, *=, /=, %=, <<=, >>=, >>>=, &=, |=, ^=

integer
integer

operator statement
50 * 2 45 / 5

91 2 50 5 45
50 2 100 9



50 * (2 45) / 5

50 * -43 / 5

2
Java

27

-430
integer
4 9 2.25
integer Java 2

5/2=2
125 / 4 = 31
3/9=0
15 / 15 = 1
operator %

5%2=1
125 % 4 = 1
3%9=3
15 % 15 = 0


integer
Java double float
(
double float )

(vat) price rate



double price = 120.0, rate = 7.5;
double vat = price * rate;
integer
/*
* Integer.java - Integers calculation */
class Integer {
public static void main(String[] args) {
//declares and initialize three variables
int studentNumber = 40;
int teacherNumber = 30;
int totalNumber = 0;
totalNumber = studentNumber + teacherNumber;

//display result
System.out.print(studentNumber + " students + " +
teacherNumber);
System.out.println(" teachers = " + totalNumber + " people");

2
Java

28

Integer.java
(studentNumber) (teacherNumber)
totalNumber = studentNumber + teacherNumber;
Java studentNumber
teacherNumber
totalNumber = (assignment operator) 2.2

teacherNumber

studentNumber

40

totalNumber

30

70

2.2 integer

System.out.print()
System.out.println()
System.out.print(studentNumber + " students + " + teacherNumber);

studentNumber string
"student +"
teacherNumber
System.out.println(" teachers = " + totalNumber + " people");
string
" teachers = " totalNumber
string
" people"

40 students + 30 teachers = 70 people
"" Java +
(System.out) " "

Java

System.out.println("30 + 45 = " + (30 + 45));

"30 + 45 = " (30 + 45)


75
30 + 45 = 75
30 45 Java

2
Java

29

30 + 45 = 3045
Java
System.out
System.out


total = total + value;

value

total

total

value

2.3


total += value;
+=
() operator
2.5
2.5 operator

sum = sum + count;


sum = sum - count;
sum = sum * count;
sum = sum / count;
sum = sum % count;

sum += count;
sum -= count;
sum *= count;
sum /= count;
sum %= count;



total += 4;
sum += 1;
operator

count = count + 1;
value -= 1;

2
Java

30


operator ++ operator --
count++;
value--;
++
-
postfix (postfix notation) operator Java



total += 2;

total -= 3;
Java Operator

int count = 8, value = 5;
count = count + value++;
value count
value count +
value value++
Java value count
value execute count = count + value++
13 value 6
count = count + ++value;
14 ()
++ Java
value
count 14
prefix (prefix notation)
prefix postfix Java
loop (repetition)
prefix postfix
int count = 10, value = 5;
count--;
value++;
value = ++count + ++value;
execute value = ++count + --value; value 17
count 9 value 6 ( count value++)

2
Java

31

code
value = (++count) + (++value);

value = (count += 1) + (value += 1);

value = (count = count + 1) + (value = value + 1);


(?)
value =

(count++) + (value++);

count = 10 value = 5
postfix ++ Java count 10
value 5 value value
15 count value count 11
value 16
run value = 15 count = 11 ?

value = 5;
value = value++;
run value = 5 Java postfix
operator ++

run
int sum = value++;
sum 5 value 6 postfix operator
++ (
)

++

operator ++ operator

/* Increments.java - Shows increment operators */
class Increments {
public static void main(String[] args) {
int value = 25, number = 25;
System.out.println("value is " + value);
System.out.println("number is " + number);
--value;
number++;
System.out.println("value is " + value);
System.out.println("number is " + number);
value = value + --number;
System.out.println("value is " + value);

2
Java

32

System.out.println("number is " + number);


number = number - value++;
System.out.println("value is " + value);
System.out.println("number is " + number);
number--;
value++;
System.out.println("value is " + value);
System.out.println("number is " + number);
value = --value;
number = number++;
System.out.println("value is " + value);
System.out.println("number is " + number);

run
value is 25
number is 25
value is 24
number is 26
value is 49
number is 25
value is 50
number is -24
value is 51
number is -25
value is 50
number is -25
operator increment (++ --)
operator

integer (short byte)
byte short Java
int short byte
int
/* ByteShort.java - Shows byte and short integer calculation */
class ByteShort {
public static void main(String[] args) {
short numScooters = 10;
short numChoppers = 5;
short total = 0;
total = numScooters + numChoppers;

System.out.println("Number of scooters is " + numScooters);


System.out.println("Number of choppers is " + numChoppers);
System.out.println("Total number of bikes is " + total);

compile Java error


ByteShort.java:10: possible loss of precision

2
Java

33

found
: int
required: short
total = numScooters + numChoppers;
^
1 error
integer 64 bit total
16 bit compiler
int casting
cast
cast

cast cast

ByteShort.java Java compile
total = numScooters + numChoppers;
total = (short)(numScooters + numChoppers);
Java compile run
Number of scooters is 10
Number of choppers is 5
Total number of bikes is 15

numScooters 32767
compile run
short numScooters = 32767;
short numChoppers = 5;

//


Number of scooters is 32767
Number of choppers is 5
Total number of bikes is -32764
total -32764 32772
?
short 32767

total Java
(
bit 64 bit 32 bit)

cast

cast Casting.java
/* Casting.java - Changing type of data */
class Casting {
public static void main(String[] args) {
byte byteVar = 127;

2
Java

34

short shortVar = 32767;


long longVar = 100000;
int intVar = 300000;
System.out.println("byteVar is " + byteVar);
System.out.println("shortVar is " + shortVar);
System.out.println("longVar is " + longVar);
System.out.println("intVar is " + intVar);
byteVar = (byte)shortVar;
shortVar = (short)longVar;
longVar = (int)intVar * (int)longVar;
intVar = (short)intVar * (short)intVar;

System.out.println("byteVar is " + byteVar);


System.out.println("shortVar is " + shortVar);
System.out.println("longVar is " + longVar);
System.out.println("intVar is " + intVar);

run
byteVar is 127
shortVar is 32767
longVar is 100000
intVar is 300000
byteVar is -1
shortVar is -31072
longVar is -64771072
intVar is 766182400


long ( long L
) long
long value = 125;
long price = 200L;
int total = 0;
total = value * price;
value long price
integer
o
o

long L
bit 64 bit
int bit
32 bit

integer
o

int 0 Java
error exception
error Java exception

2
Java

35

%
0 error 0

(Floating Point Calculations)

integer
operator + - * /
/* FloatingPoint.java - Calculating income */
class FloatingPoint {
public static void main(String[] args) {
double weeklyPay = 1075 * 5; //1075 per day
double extras = 1580;
final double TAX_RATE = 8.5; //tax rate in percent
//calculate tax and income
double tax = (weeklyPay + extras) * TAX_RATE / 100;
double totalIncome = (weeklyPay + extras) - tax;

System.out.println("Tax = " + tax);


System.out.println("Total income = " + totalIncome);

FloatingPoint.java
1075 1580 8.5% execute

Tax = 591.175
Total income = 6363.825

double tax = (weeklyPay + extras) * TAX_RATE / 100;




? code
/* FloatingPoint2.java - Calculating income with formatted output */
import java.text.*;
//for NumberFormat
class FloatingPoint2 {
public static void main(String[] args) {
double weeklyPay = 1075 * 5; //1075 per day
double extras = 1580;
final double TAX_RATE = 8.5; //tax rate in percent
//set format output
NumberFormat form = NumberFormat.getNumberInstance();
form.setMaximumFractionDigits(2);
//calculate tax and income
double tax = (weeklyPay + extras) * TAX_RATE / 100;
double totalIncome = (weeklyPay + extras) - tax;
System.out.println("Tax = " + form.format(tax));
System.out.println("Total income = " +
form.format(totalIncome));

2
Java

36

NumberFormat form = NumberFormat.getNumberInstance();


form.setMaximumFractionDigits(2);
form.format(tax) form.format(totalIncome)

Tax = 591.18
Total income = 6,363.82
591.175 591.18 6363.825 6363.82
totalIncome , (comma)
method getNumbereInstance() setMaximumFractionDigits()
import class NumberFormat method

method class DecimalFormat format


, (comma) ?

/* FloatingPoint3.java - Calculating income with formatted output */
import java.text.*;
//for DecimalFormat
class FloatingPoint3 {
public static void main(String[] args) {
double weeklyPay = 1075 * 5; //1075 per day
double extras = 1580;
final double TAX_RATE = 8.5; //tax rate in percent
//set format output
DecimalFormat form = new DecimalFormat("#.00");
//calculate tax and income
double tax = (weeklyPay + extras) * TAX_RATE / 100;
double totalIncome = (weeklyPay + extras) - tax;

System.out.println("Tax = " + form.format(tax));


System.out.println("Total income = " +
form.format(totalIncome));

Tax = 591.18
Total income = 6363.82
class DecimalFormat NumberFormat format
DecimalFormat form = new DecimalFormat("#.00);

, (comma)

2
Java

37

(Mixed Type Calculations)


Java

integer

/* FloatingPoint4.java - Mixed-type calculations */


import java.text.*;
//for NumberFormat
class FloatingPoint4 {
public static void main(String[] args) {
double hourlyPay = 85.50; //85.50 per hour
int hoursPerDay = 8;
//8 hours per day
int numberOfDays = 5;
//total days worked
int extraHoursWorked = 15;
//overtime hours
final double TAX_RATE = 8.5;//tax rate in percent
//set format output
NumberFormat form = NumberFormat.getNumberInstance();
form.setMaximumFractionDigits(2);
//calculate weekly pay
double weeklyPay = hourlyPay * hoursPerDay * numberOfDays;
//calculate extra pay: one and a half time of
//regular hourly pay
double extras = extraHoursWorked * (hourlyPay +
(hourlyPay / 2.0));
//calculate tax
double tax = (weeklyPay + extras) * TAX_RATE / 100;
//calculate total income
double totalIncome = (weeklyPay + extras) - tax;

System.out.println("Income before tax = " +


form.format((weeklyPay + extras)));
System.out.println("Tax = " + form.format(tax));
System.out.println("Income after tax = " +
form.format(totalIncome));

FloatingPoint4.java
double integer
hoursPerDay numberOfDays extraHoursWorked
integer hourlyPay weeklyPay extras tax totalIncome
double
Java
int double

Income before tax = 5,343.75
Tax = 454.22
Income after tax = 4,889.53
()
o

double double

2
Java

o
o

38

float float

long long





/* MixedTypes.java - Mixed-type calculations */
import java.text.*;
class MixedTypes {
public static void main(String[] args) {
double result = 0.0;
int one = 1, two = 2;

result = 1.5 + one / two;


//formatting output
DecimalFormat f = new DecimalFormat("#.00");
System.out.println("Result is " + f.format(result));

2.0 Java 1.5

result = 1.5 + one / two;


one two int
int 0
Java 0 double 1.5
cast one double
/* MixedTypes.java - Mixed-type calculations */
import java.text.*;
class MixedTypes {
public static void main(String[] args) {
double result = 0.0;
int one = 1, two = 2;

result = 1.5 + (double)one / two;


//formatting output
DecimalFormat f = new DecimalFormat("#.00);
System.out.println("Result is " + f.format(result));

2.0
cast cast

/* FloatingPoint5.java - Mixed-type calculations */


import java.text.*;

//for NumberFormat

2
Java

39

class FloatingPoint5 {
public static void main(String[] args) {
double hourlyPay = 85.50D;
//85.50 per hour
int hoursPerDay = 8;
//8 hours per day
float numberOfDays = 5F;
//total days worked
int extraHoursWorked = 15;
//overtime hours
final double TAX_RATE = 8.5D;//tax rate in percent
//set format output
NumberFormat form = NumberFormat.getNumberInstance();
form.setMaximumFractionDigits(2);
//calculate weekly pay
double weeklyPay = hourlyPay * hoursPerDay * numberOfDays;
//calculate extra pay: one and a half time of
regular hourly pay
double extras = extraHoursWorked * (hourlyPay +
(hourlyPay / 2.0));
//calculate tax
double tax = (weeklyPay + extras) * TAX_RATE / 100;
//calculate total income
double totalIncome = (weeklyPay + extras) - tax;

System.out.println("Income before tax = " +


form.format((weeklyPay + extras)));
System.out.println("Tax = " + form.format(tax));
System.out.println("Income after tax = " +
form.format(totalIncome));

int numberOfDays = 5; float numberOfDays = 5F;


Java float double int
double
Mathematical Functions Java

function
sine cosine tangent Java
function
function
Quadratic Equation ax2 + bx + c =
0

x1 =

b + b 2 4ac
2a

x2 =

b b 2 4ac
2a

mathematical function
square root Java method
Math.sqrt()
/* Quadratic.java - Calculating roots of function */

2
Java

40

class Quadratic {
public static void main(String[] args) {
double a, b, c;
//4x2 + 20x + 16 = 0
a = 4;
b = 20;
c = 16;
//calculate determimant
double det = Math.sqrt(b * b - 4 * a * c);
//calculate roots
double x1 = (-b + det) / (2 * a);
double x2 = (-b - det) / (2 * a);

System.out.println("Root 1 = " + x1);


System.out.println("Root 2 = " + x2);

Root 1 = -1.0
Root 2 = -4.0
Quadratic.java determinant
0 square root 0 b2 4ac

(if else)
Math.sqrt()
Mathematical function
/* MaxMin.java - Finding max and min */
class MaxMin {
public static void main(String[] args) {
int num1 = 58, num2 = 97, num3 = 15;
//finding maximum between num1, num2, and num3
int maxOfTwo = Math.max(num1, num2);
int maxOfAll = Math.max(maxOfTwo, num3);
//finding minimum between num1, num2, and num3
int minOfTwo = Math.min(num1, num2);
int minOfAll = Math.min(minOfTwo, num3);

System.out.println("Maximum number is " + maxOfAll);


System.out.println("Minimum number is " + minOfAll);

MaxMin.java method max() min()



integer 3 method
parameter integer 2

integer
execute

Maximum number is 97

2
Java

41

Minimum number is 15
method class Math
/* Maths.java - Other math functions */
class Maths {
public static void main(String[] args) {
double angle = 0.7853982; //45 degrees angle in radians
System.out.println("sin(45) is " + Math.sin(angle));
System.out.println("cos(45) is " + Math.cos(angle));
System.out.println("tan(45) is " + Math.tan(angle));

//absolute value of -456


System.out.println("Absolute value of -456 is " +
Math.abs(-456));
//two to the fourth power
System.out.println("2 to the 4th power is " +
Math.pow(2D, 4D));
//round to the nearest integer
System.out.println("2.345267 rounded to " +
Math.round(2.345267));
//round to the nearest integer
System.out.println("2.859 rounded to " + Math.round(2.859));
//the remainder of 3.25 / 2.25
System.out.println("The remainder of 3.25 / 2.25 is " +
Math.IEEEremainder(3.25, 2.25));
//nearest integer of PI
System.out.println("The nearest integer of PI is " +
Math.rint(Math.PI));

Maths.java method class Math sine cosine tangent


45 0.7853982 radians
radians method

parameter radians
absolute -456 24
run
sin(45) is 0.7071068070684596
cos(45) is 0.7071067553046345
tan(45) is 1.0000000732051062
Absolute value of -456 is 456
2 to the 4th power is 16.0
2.345267 rounded to 2
2.859 rounded to 3
The remainder of 3.25 / 2.25 is 1.0
The nearest integer of PI is 3.0
method toRadians() degrees radians

degrees radians
/* Maths1.java - Other math functions */
import java.text.DecimalFormat;
class Maths1 {

2
Java

42

public static void main(String[] args) {


double angle = 45;
//45 degrees angle
double sin, cos, tan;
//set format output
DecimalFormat f = new DecimalFormat("0.00000");
//calculate sin, cos, and tan
sin = Math.sin(Math.toRadians(angle));
cos = Math.cos(Math.toRadians(angle));
tan = Math.tan(Math.toRadians(angle));
System.out.println("sin(" + angle + ") = " + f.format(sin));
System.out.println("cos(" + angle + ") = " + f.format(cos));
System.out.println("tan(" + angle + ") = " + f.format(tan));
}

math function

/* Radius.java - Other math functions */


import java.text.DecimalFormat;
class Radius {
public static void main(String[] args) {
double radius;
double area = 850.0;
int meters, centimeters;
//calculate radius
radius = Math.sqrt(area / Math.PI);
//convert to meters and centimeters
meters = (int)Math.floor(radius);
centimeters = (int)Math.round(100.0 * (radius - meters));

System.out.print("Circle with area of " + area +


" square meters ");
System.out.print("has a radius of " + meters +
" meters and ");
System.out.println(centimeters + " centimeters");

floor() round()
centimeters meters radius run
Circle with area of 850.0 square meters has a radius of 16 meters and
45 centimeters
method
2.6
2.6 Mathematical Functions
Method
Function
Argument
sin(arg)
sine
double (radians)
cos(arg)
cosine
double (radians)
tan(arg)
tangent
double (radians)

Result Type
double
double
double

2
Java

43

asin(arg)

arc sine

double

acos(arg)

arc cosine

double

atan(arg)

arc tangent

double

atan2(arg1, arg2)

arc tangent of arg1


arg2

double

abs(arg)

absolute arg

max(arg1, arg2)

arg1
arg2
arg1
arg2



arg


arg
integer
arg

int long float


double
int long float
double
int long float
double
double

double (radians
/2
/2)
double (radians
0.0
)
double (radians
/2
/2 )
double (radians

)

Argument

Argument

Argument
double

double

double

float double

double

int
argument
float long
double
double

double

double

double
double

double
double

double
double

double
double
double

min(arg1, arg2)
ceil(arg)
floor(arg)
round(arg)

rint(arg)
IEEEremainder(arg1,
arg2)
sqrt(arg)
pow(arg1, arg2)
exp(arg)
log(arg)
random()

integer
arg

arg1 arg2
root
arg
arg1
arg2
e arg
log arg
0.0
1.0

Character
character
character Java character

/* Characters.java - Using character data */


class Characters {
public static void main(String[] args) {
char H, e, l, o;
H
e
l
o

=
=
=
=

72;
101;
108;
111;

//ASCII
//ASCII
//ASCII
//ASCII

for
for
for
for

'H'
'e'
'l'
'o'

2
Java

44

System.out.print(H);
System.out.print(e);
System.out.print(l);
System.out.print(l);
System.out.print(o);
System.out.println(" World");

run Characters.java Hello World ASCII


H e l o

character operator
/* Characters1.java - Using character data */
class Characters1 {
public static void main(String[] args) {
char ch1 = 88, ch2 = 77;
System.out.println("ch1 = " + ch1);
System.out.println("ch2 = " + ch2);
ch1 -= 23; //ASCII for 'A'
ch2 += 6; //ASCII for 'S'

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


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

ch1 ch2 X M
ch1 ch2 ch1
23 ch2 6 A X
execute
ch1
ch2
ch1
ch2

=
=
=
=

X
M
A
S

Unicode
/* Characters2.java - Using character data */
class Characters2 {
public static void main(String[] args)
char ch1 = '\u0058'; //unicode for
char ch2 = '\u004D'; //unicode for
char ch3 = '\u0041'; //unicode for
char ch4 = '\u0053'; //unicode for

System.out.println("ch1
System.out.println("ch2
System.out.println("ch3
System.out.println("ch4

=
=
=
=

"
"
"
"

+
+
+
+

{
'X'
'M'
'A'
'S'

ch1);
ch2);
ch3);
ch4);

2
Java

45

}
run Characters1.java

Unicode Unicode

'?'
Unicode applet Unicode
applet
2.7

Character Escape Sequences
( )
2.7 Character Escape Sequence
Escape Sequence

\ddd
(Octal)
\uxxxx
Unicode (Hexadecimal)
\'
' (Single quote)
\"
" (Double quote)
\\
\
\r

(Carriage return)
\n
(New line Linefeed)
\f
(Form feed)
\t
(Tab)
\b

boolean
boolean
boolean
boolean
operator Logical Operator
boolean operator
&&
||
&
|
!

Conditional AND
Conditional OR
Logical AND
Logical OR
Logical NOT

&& || Lazy Short Circuit

& |
operator && & &&

false false
false
operator || &&
true
true
true
operator & |

2
Java

46

operator !
boolean

Operator

boolean
<
>
<=

>=

==
!=

operator Relational operator

operator

/* BooleanOp.java - Testing boolean operations */
class BooleanOp {
public static void main(String[] args) {
boolean A = true, B = false;

System.out.println("Conditional
System.out.println("F && F is "
System.out.println("F && T is "
System.out.println("T && F is "
System.out.println("T && T is "

AND");
+ (B &&
+ (B &&
+ (A &&
+ (A &&

B));
A));
B));
A));

System.out.println("Conditional
System.out.println("F || F is "
System.out.println("F || T is "
System.out.println("T || F is "
System.out.println("T || T is "

OR");
+ (B ||
+ (B ||
+ (A ||
+ (A ||

B));
A));
B));
A));

System.out.println("Logical AND");
System.out.println("F & F is " + (B
System.out.println("F & T is " + (B
System.out.println("T & F is " + (A
System.out.println("T & T is " + (A

&
&
&
&

B));
A));
B));
A));

System.out.println("Logical OR");
System.out.println("F | F is " + (B
System.out.println("F | T is " + (B
System.out.println("T | F is " + (A
System.out.println("T | T is " + (A

|
|
|
|

B));
A));
B));
A));

System.out.println("Logical NOT");
System.out.println("!F is " + (!B));
System.out.println("!T is " + (!A));

A B true false
operator System.out.println()

2
Java

47

Conditional AND
F && F is false
F && T is false
T && F is false
T && T is true
Conditional OR
F || F is false
F || T is true
T || F is true
T || T is true
Logical AND
F & F is false
F & T is false
T & F is false
T & T is true
Logical OR
F | F is false
F | T is true
T | F is true
T | T is true
Logical NOT
!F is true
!T is false
Relational operator
/* BooleanOp2.java - Using relational operators */
class BooleanOp2 {
public static void main(String[] args) {
int i = 5, j = 10;

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


System.out.println("j = " + j);
System.out.println("i > j is " + (i > j));
System.out.println("i < j is " + (i < j));
System.out.println("i >= j is " + (i >= j));
System.out.println("i <= j is " + (i <= j));
System.out.println("i == j is " + (i == j));
System.out.println("i != j is " + (i != j));
System.out.println("(i < 10) && (j < 10) is " + ((i < 10) &&
(j < 10)));
System.out.println("(i < 10) || (j < 10) is " + ((i < 10) ||
(j < 10)));

BooleanOp2.java
operator int i j
5 10 operator
run

2
Java

48

i = 5
j = 10
i > j is false
i < j is true
i >= j is false
i <= j is true
i == j is false
i != j is true
(i < 10) && (j < 10) is false
(i < 10) || (j < 10) is true
operator && operator ||

p q 5 10

10 5
p = 5, q = 10

(p < q)

&&

p = 10, q = 5

(q <= 10)

(p < q)

&&

(q <= 10)

F
&& F

T
2.4 &&

p = 5, q = 10

(p < q)

||

p = 10, q = 5

(q <= 10)

T ||
T

(p < q)

||

(q <= 10)

2.5 ||

2.8 operator && || & |

2
Java

2.8
P
true
false
true
false

operator && || & |


Q
P && Q
P || Q
true
true
true
true
false
true
false
false
true
false
false
false

P&Q
true
false
false
false

49

P|Q
true
true
true
false

boolean operator
boolean
(condition)

true false true
false boolean operator logic
(logic and loop)
bit operator Shift Bitwise
bit operator
bit
operator shift Java <<
>> >>>
2.9 operator shift << >> >>>
Operator

<<
operand1 << operand2
bit operand1
operand2 0 bit
>>
operand1 >> operand2
bit operand1
operand2 bit (sign bit)
>>>
operand1 >>> operand2
bit operand1
operand2 0 bit

13 >> 1
13 = 000011012 shift 1 bit 000001102 ( 6 10)
13 << 1
shift 1 bit 000110102 ( 26 10)
13 >>> 1
shift 1 bit 000001102 ( 6 10)
bit bit
bit ShiftLeftOp.java
/* ShiftLeftOp.java - Using shift operators */
class ShiftLeftOp {
public static void main(String[] args) {
byte bits = 1;
System.out.println("Value of bits is " + bits);
bits = (byte) (bits << 1);
System.out.println("Value of bits is " + bits);
bits = (byte) (bits << 1);

2
Java

System.out.println("Value of
bits = (byte) (bits << 1);
System.out.println("Value of
bits = (byte) (bits << 1);
System.out.println("Value of
bits = (byte) (bits << 1);
System.out.println("Value of

50

bits is " + bits);


bits is " + bits);
bits is " + bits);
bits is " + bits);

bits byte bit




run
Value
Value
Value
Value
Value
Value

of
of
of
of
of
of

bits
bits
bits
bits
bits
bits

is
is
is
is
is
is

1
2
4
8
16
32

byte bit bit


bit ()
bits code
run
bits = (byte) (bits << 2);
System.out.println("Value of bits is " + bits);
run code bits -128 Java
byte 127

Value
Value
Value
Value
Value
Value
Value

of
of
of
of
of
of
of

bits
bits
bits
bits
bits
bits
bits

is
is
is
is
is
is
is

1
2
4
8
16
32
-128

cast
Java bits int shift
( shift )

integer floating-point




Java method
keyboard



keyboard ( )

2
Java

51


Java method

int float double char



C C++
code String
String String

String
String
Java String object ( object? object
)

People of Thailand

price_of_coffee
1234567890
23+popOfRock
String String
keyboard String
code
Radius.java area keyboard
/* Radius2.java - Reading data from keyboard */
import java.io.*;
class Radius2 {
public static void main(String[] args) throws IOException {
double radius, area;
int meters, centimeters;
//prompt user for area of a circle
System.out.print("Please enter area of a circle: ");
//get string from keyboard
InputStreamReader in = new InputStreamReader(System.in);
BufferedReader buffer = new BufferedReader(in);
String inputString = buffer.readLine();
//convert string to double
area = Double.parseDouble(inputString);
//calculate radius
radius = Math.sqrt(area / Math.PI);
//convert to meters and centimeters
meters = (int)Math.floor(radius);
centimeters = (int)Math.round(100.0 * (radius - meters));

System.out.print("Circle with area of " + area +


" square meters ");
System.out.print("has a radius of " + meters +
" meters and ");
System.out.println(centimeters + " centimeters");

Raadius2.java code String keyboard


System.out.print("Please enter area of a circle: ");

2
Java

52

InputStreamReader in = new InputStreamReader(System.in);


BufferedReader buffer = new BufferedReader(in);
String inputString = buffer.readLine();
user
byte (System.in) character
in
buffer character
in String String ( buffer)
String method readLine() buffer
String inputString

String String
keyboard ( )
String String
Radius.java double String
double method parseDouble() class Double
keyboard method
area = Double.parseDouble(inputString);
code run
850 54
Please enter area of a circle: 850
Circle with area of 850.0 square meters has a radius of 16 meters and
45 centimeters
Please enter area of a circle: 54
Circle with area of 54.0 square meters has a radius of 4 meters and
15 centimeters

Radius2.java main(..)
throws IOException
throws IOException main()
Java
I/O


( 7)
Radius2.java error
Radius2.java:16: unreported exception java.io.IOException; must be
caught or declared to be thrown
String inputString = buffer.readLine();
^
1 error
Java

must be caught or declared to be thrown


(1) catch (2)
throws Java

2
Java

53

error


code
/* Radius2.java - Reading data from keyboard */
import java.io.*;
class Radius2 {
public static void main(String[] args) throws IOException {
double radius, area;
int meters, centimeters;
String inputString = null;
try {
//prompt user for area of a circle
System.out.print("Please enter area of a circle: ");
//get string from keyboard
InputStreamReader in = new InputStreamReader(System.in);
BufferedReader buffer = new BufferedReader(in);
inputString = buffer.readLine();
}
catch(IOException ioe) {}
//convert string to double
area = Double.parseDouble(inputString);
//calculate radius
radius = Math.sqrt(area / Math.PI);
//convert to meters and centimeters
meters = (int)Math.floor(radius);
centimeters = (int)Math.round(100.0 * (radius - meters));

System.out.print("Circle with area of " + area +


" square meters ");
System.out.print("has a radius of " + meters +
" meters and ");
System.out.println(centimeters + " centimeters");


String inputString = null;
//prompt user for area of a circle
System.out.print("Please enter area of a circle: ");
try {
//get string from keyboard
InputStreamReader in = new InputStreamReader(System.in);
BufferedReader buffer = new BufferedReader(in);
inputString = buffer.readLine();
}
catch(IOException ioe) {}
inputString


try {

2
Java

54

}
catch(IOException ioe) {}
string block try {}
catch(IOException ioe) {} block try {}
code code catch(IOExcpetion ioe) {}
error error Java


Enter try {..} catch() {}
Radius2.java
/* Radius2.java - Reading data from keyboard */
import java.io.*;
class Radius2 {
public static void main(String[] args) {
double radius, area;
int meters, centimeters;
String inputString = null;
//prompt user for area of a circle
System.out.print("Please enter area of a circle: ");
try {
//get string from keyboard
InputStreamReader in = new InputStreamReader(System.in);
BufferedReader buffer = new BufferedReader(in);
inputString = buffer.readLine();
try {
//convert string to double
area = Double.parseDouble(inputString);
//calculate radius
radius = Math.sqrt(area / Math.PI);
//convert to meters and centimeters
meters = (int)Math.floor(radius);
centimeters = (int)Math.round(100.0 *
(radius - meters));
System.out.print("Circle with area of " + area +
" square meters ");
System.out.print("has a radius of " + meters +
" meters and ");
System.out.println(centimeters + " centimeters");

}
//catch empty string (user hits Enter)
catch(Exception e) {
System.out.println("Error! you must supply input");
e.printStackTrace();
System.exit(1);
}

}
//catch other I/O error - do nothing
catch(IOException ioe) { /* leave it to Java! */ }

2
Java

55

}
Radius2.java try {} cath() {}



1. System.out.println("Error! you must supply input");
2. error Java e.printStackTrace();
3. System.exit(1);
execute
Please enter area of a circle: <
Enter >
Error! you must supply input
java.lang.NumberFormatException: empty String
at
java.lang.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:9
86)
at java.lang.Double.parseDouble(Double.java:202)
at Radius2.main(Radius2.java:22)
Java
1 System.exit(1) 0 0
1
error code
error

primitive datatype Java



(casting) method

error

1. final
2. 5, 5.0, '5', "5", "5.0"
3.
double x = 4.5;
double y = -45.25;
int p = 12;
int q = 2;
3.1.
3.2.
3.3.
3.4.
3.5.
3.6.

x + p * y / (p y) * x
p % (p q)
(int) y
(int) p
Math.round(x)
(int) Math.round(y)

2
Java

3.7.
3.8.
3.9.
3.10.

56

-2 * y + (int) x
q/p
p%q
y * y y + (x * (int) x)

4. int keyboard 2 double 2


4

5. Java
5.1.
5.2.
5.3.
5.4.

a + bc / 2
a(a c) + b(b c) (c(c a) / d)
b2 4ac
(4/3)2 / 2

5.5.

T xM
q= 1
+ T2
Dk

6.

Celsius Fahrenheit
keyboard

Celsius =

5
(Fahrenheit 32)
9

7.

Fahrenheit Celsius
keyboard
8. keyboard mile

9. keyboard
( 1 365 )
10. int 5

11.


12.
beer 1 beer 1 (24
) barley 1
200
barley beer

13. long (digit) 10 12


,
3
14.
(perimeter)
15.
keyboard

2
Java

57

16. double 5 keyboard


17. 865,000
7,600
17.1.
17.2.
17.3.

(cubic mile mile3)


(cubic mile)

18. double 123.4567 keyboard


long
long long



(repetition loop)

o
o
o
o

(comparison)
(logical expression)
(control statement)
(loop)
for loop
while loop
do while loop
loop break continue




code







code

relational operator

boolean operator < <= > >= == != operator


if
if if
if(expression)
statement;
expression boolean
true false

3
Java

(Repetition)

59

if(numberOfStudents >= 500)


entranceExam = true;

if(number < 0)
number *= 10;
number++;
expression
if
number < 0 number *= 10
3.1 if
number
if(expression)
statement;
other_statement;

no

yes

number
<0

no

yes

statement

number *= 10;

other_statement

number++;

3.1 if

if


if(number < 0) number *= 10;
number++;
Java

code
user
/* IfStatement.java - Using if statement to find out whether a number
* is odd or even
*/
import java.io.*;
import java.lang.Integer;
class IfStatement {
public static void main(String[] args) throws IOException {

3
Java

(Repetition)

60

int number;
//set up buffer stream
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader buffer = new BufferedReader(isr);
//get input string
System.out.print("Enter a number (int): ");
String input = buffer.readLine();
//convert string to int
number = Integer.parseInt(input);

//check if number is even or not


if(number % 2 == 0)
System.out.println(number + " is an even number.");

IfStatement.java user
number
if(number % 2 == 0)
System.out.println(number + " is an even number.");
number ()
run
Enter a number (int): 45
Enter a number (int): 20
20 is an even number.

45



if

(if block)
code {}
(compound statement)
if(expression) {
statement 1;
statement 2;
statement 3;

statement n;
}

if(number % 2 == 0) {
System.out.println(number + " is an even number.");
number++;
System.out.println("But " + number + " is not!");
}

3
Java

(Repetition)

61


if
else if
if else
if(expression)
statement;
else
other_statement;
another_statement;
3.2 if else

yes

statement

no

other_statement

another_statement

3.2 if - else

IfStatement.java
user

code
/* IfElse.java - Using if - else statement to find out whether a
* number is odd or even
*/
import java.io.*;
import java.lang.Integer;
class IfElse {
public static void main(String[] args) throws IOException {
int number;
//set up buffer stream
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader buffer = new BufferedReader(isr);
//get input string
System.out.print("Enter a number (int): ");
String input = buffer.readLine();

3
Java

(Repetition)

62

//convert string to int


number = Integer.parseInt(input);
//check if number is even or not
if(number % 2 == 0)
System.out.println(number + " is an even number.");
else
System.out.println(number + " is an odd number.");

System.out.println("Good Bye.");


else
System.out.println(number + " is an odd number.");
System.out.println("Good Bye.");

else number % 2 == 0

( 2 )
run
Enter a number (int): 45
45 is an odd number.
Good Bye.
Enter a number (int): 80
80 is an even number.
Good Bye.
if else

if else statement if else
if else if else
Nested if ( if else
)
if(expression 1) {
statement 1;
statement 2;
}
else
if(expression 2)
statement 3;
else {
statement 4;
statement 5;
}

if(expression 1) {
statement 1;
statement 2;
}
else if(expression 2)
statement 3;
else {
statement 4;
statement 5;
}

expression 1
statement 1 statement 2 statement 3
expression 2
statement 4 statement 5
expression 1 expression 2

3
Java

(Repetition)

63

Nested if Grades.java
/* Grades.java - Using Nested - if finding letter grade
* from a given score
*/
import java.io.*;
import java.lang.Integer;
class Grades {
public static void main(String[] args) throws IOException {
int score;
char grade;
//set up buffer stream
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader buffer = new BufferedReader(isr);
//get input string
System.out.print("Enter your score: ");
String input = buffer.readLine();
//convert string to int
score = Integer.parseInt(input);
//determine grade by given score
if(score >= 90)
grade = 'A';
else if(score >= 80)
grade = 'B';
else if(score >= 70)
grade = 'C';
else if(score >= 60)
grade = 'D';
else
grade = 'F';

System.out.println("Your grade is " + grade);

Grades.java score

60 F

90
80
70
60

A
B ( 80 89)
C ( 70 79)
D ( 60 69)

90 60
user score
75 if if
if score >= 70
grade = 'C'
grade = 'F'

if else score

run

3
Java

(Repetition)

64

Enter your score: 87


Your grade is B
Enter your score: 45
Your grade is F
Enter your score: 92
Your grade is A

Grades.java operator && ||


score
/* Grades2.java - Using Nested - if finding letter grade
* from a given score
*/
import java.io.*;
import java.lang.Integer;
class Grades2 {
public static void main(String[] args) throws IOException {
int score;
char grade;
//set up buffer stream
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader buffer = new BufferedReader(isr);
//get input string
System.out.print("Enter your score: ");
String input = buffer.readLine();
//convert string to int
score = Integer.parseInt(input);
//determine grade by given score
if(score >= 90)
grade = 'A';
else if(score >= 80 && score <= 89)
grade = 'B';
else if(score >= 70 && score <= 79)
grade = 'C';
else if(score >= 60 && score <= 69)
grade = 'D';
else
grade = 'F';

System.out.println("Your grade is " + grade);

code
if(score >= 90)
grade = 'A';
else if(score >= 80 && score <= 89)
grade = 'B';
else if(score >= 70 && score <= 79)

3
Java

(Repetition)

65

grade = 'C';
else if(score >= 60 && score <= 69)
grade = 'D';
else
grade = 'F';
run Grades.java

&&
&&
score
85 if Java if else if(score >= 80 &&
score <= 89) Java &&

score >= 80




&& ||

/* UpperLower.java - Using && in if - else statement */
import java.io.*;
class UpperLower {
public static void main(String[] args) throws IOException {
char ch = 'F';

if(ch >= 'A' && ch <= 'Z')


System.out.println(ch + " is an uppercase letter.");
else if(ch >= 'a' && ch <= 'z')
System.out.println(ch + " is a lowercase letter.");

ch F if else

&& ch
Java ASCII (Unicode)
F A (70 65) F
Z (70 90)
System.out.println(ch + " is an uppercase
letter."); ch
else if
||

/* Season.java - Using || in if - else statement */
import java.io.*;
import java.lang.Integer;
class Season {
public static void main(String[] args) throws IOException {
int month;
String season, input;
InputStreamReader in;
BufferedReader buffer;
System.out.print("Enter month (1 12): ");
in = new InputStreamReader(System.in);

3
Java

(Repetition)

66

buffer = new BufferedReader(in);


input = buffer.readLine();
month = Integer.parseInt(input);
if(month == 3 || month == 4 || month == 5 || month == 6)
season = "Summer";
else if(month == 7 || month == 8 || month == 9 || month == 10)
season = "Rainy";
else if(month == 11 || month == 12 ||
month == 1 || month == 2)
season = "Winter";
else
season = "Never heard of it!";

System.out.println(month + " is in " + season);

Season.java || month user


3 6 7 10 11 2 (

) run
Enter month (1 12): 4
4 is in Summer
Enter month (1 12): 8
8 is in Rainy
Enter month (1 12): 1
1 is in Winter
Enter month (1 12): 20
20 is in Never heard of it!
Operator ||

month 3 4 5 6 season Summer
&&
month else

Nested if else if else Java
else if

/* DanglingElse.java */
import java.io.*;
class DanglingElse {
public static void main(String[] args) {
int x = 7, y = 99;
if(x > 5)
if(y > 5)
System.out.println("x and y is greater than 5");
else
System.out.println("x is less than 5");

3
Java

(Repetition)

67

DanglingElse.java run
x and y is greater than 5

y 2
x is less than 5
x 5 Java else if

if(x > 5)
if(y > 5)
System.out.println("x and y is greater than 5");
else
System.out.println("x is less than 5");
{}
if(x > 5) {
if(y > 5)
System.out.println("x and y is greater than 5"):
}
else
System.out.println("x is greater than 5");
run y
0
Quadratic.java



determinant 0 if
//calculate determinant
double d = b * b 4 * a * c;
if(d <= 0) {
System.err.println("Error: cannot find square root");
System.exit(1);
}
double det = Math.sqrt(d);
d Math.sqrt() d
0 user System.exit(1)
/* Quadratic.java - Calculating roots of function */
class Quadratic {
public static void main(String[] args) {
double a, b, c;
//4x2 + 20x + 16 = 0
a = 4;
b = 20;
c = 16;
//calculate determimant
double d = b * b 4 * a * c;

3
Java

(Repetition)

68

if(d <= 0) {
System.err.println("Error: cannot find square root");
System.exit(1);
}
double det = Math.sqrt(d);
//calculate roots
double x1 = (-b + det) / (2 * a);
double x2 = (-b - det) / (2 * a);

System.out.println("Root 1 = " + x1);


System.out.println("Root 2 = " + x2);

Conditional Operator (? :)
Java operator if else operator
Conditional operator operator expression (statement)
(expression) ? (true statement) : (false statement);

(number % 2 == 0) ? System.out.println("Even number.")


: System.out.println("Odd number.");

/* OddEven.java */
import java.io.*;
class OddEven {
public static void main(String[] args) {
int num;
String result;

num = (int)(Math.random() * 100;


result = (num % 2 == 0) ? "Even" : "Odd";
System.out.println(num + " is an " + result + " number.");

OddEven.java operator ? : num


(Even Odd) result

65 is an Odd number.
Min.java operator ? :

/* Min.java */
import java.io.*;
class Min {

3
Java

(Repetition)

69

public static void main(String[] args) {


int num1 = 45, num2 = 89;

int min = (num1 < num2) ? num1 : num2;


System.out.println("Min number is " + min);

run
Min number is 45
operator ? : if else

operator
switch
Java if else switch
switch(expression) {
case value1 :
statement;
break;
case value2 :
statement;
break;

default :
statement;
break;

expression switch
char byte short int
Java error 3.3 switch

3
Java

(Repetition)

yes
?

70

statement

break

statement

break

no

yes

no
default

break

3.3 switch

break switch switch


switch
/* Switch.java - Using switch
* to differentiate input
*/
import java.io.*;
import java.lang.Integer;
class Switch {
public static void main(String[] args) throws IOException {
int month;
String season, input;
InputStreamReader in;
BufferedReader buffer;
System.out.print("Enter month (1 12): ");
in = new InputStreamReader(System.in);
buffer = new BufferedReader(in);
input = buffer.readLine();
month = Integer.parseInt(input);
switch(month) {
case 3: case 4: case 5: case 6:
season = "Summer";
break;
case 7: case 8: case 9: case 10:
season = "Rainy";
break;
case 11: case 12: case 1: case 2:
season = "Winter";
break;
default :
season = "Never heard of it!";

3
Java

(Repetition)

71

break;
}
System.out.println(month + " is in " + season);

Season.java if else switch


Season.java case
case
case
case 3: case 4: case 5: case 6:
season = "Summer";
break;
Java case 3 case Java case 4
case 5 case 6 case Java season =
"Summer" break
case operator ||
if switch

run Switch.java run Season.java


switch
/* Switch2.java */
import java.io.*;
import java.lang.Integer;
class Switch2 {
public static void main(String[] args) throws IOException {
int digit;
BufferedReader buffer;
InputStreamReader isr;
String input;
System.out.print("Enter a digit: ");
isr = new InputStreamReader(System.in);
buffer = new BufferedReader(isr);
input = buffer.readLine();
digit = Integer.parseInt(input);
switch(digit) {
case 1: System.out.println("You
break;
case 2: System.out.println("You
break;
case 3: System.out.println("You
break;
case 4: System.out.println("You
break;
case 5: System.out.println("You
break;
case 6: System.out.println("You

entered ONE.");
entered TWO.");
entered THREE.");
entered FOUR.");
entered FIVE.");
entered SIX.");

3
Java

(Repetition)

72

break;
case 7: System.out.println("You entered SEVEN.");
break;
case 8: System.out.println("You entered EIGHT.");
break;
case 9: System.out.println("You entered NINE.");
break;
case 0: System.out.println("You entered ZERO.");
break;
default: System.out.println("Sorry - not a digit!");
break;

Switch2.java User 0 9
run
Enter a digit: 9
You entered NINE.
Enter a digit: 2
You entered TWO.
Enter a digit: 36
Sorry - not a digit!
36

(Loop)


1 10 2 keyboard user
Java
1 10

/* ForLoop.java */
import java.io.*;
class ForLoop {
public static void main(String[] args) {
int number = 1;
System.out.println("Number
number++;
System.out.println("Number
number++;
System.out.println("Number
number++;
System.out.println("Number
number++;
System.out.println("Number
number++;
System.out.println("Number
number++;

now is " + number);


now is " + number);
now is " + number);
now is " + number);
now is " + number);
now is " + number);

3
Java

(Repetition)

System.out.println("Number
number++;
System.out.println("Number
number++;
System.out.println("Number
number++;
System.out.println("Number

73

now is " + number);


now is " + number);
now is " + number);
now is " + number);

Number
Number
Number
Number
Number
Number
Number
Number
Number
Number

now
now
now
now
now
now
now
now
now
now

is
is
is
is
is
is
is
is
is
is

1
2
3
4
5
6
7
8
9
10

1 10 1 100
1 1000 loop

Java while,
do..while for for loop
for loop
for loop for loop

/* ForLoop2.java */
import java.io.*;
class ForLoop2 {
public static void main(String[] args) {
int number;

for(number = 1; number <= 10; number++)


System.out.println("Number now is " + number);

for loop Java


10 number 1 number 10
number 10 Java
ForLoop.java
for loop

for(expression1 ; expression2 ; expression3)
statement;

3
Java

(Repetition)

74

expression
expression1
expression initialization expression

for loop expression2


statement for loop for loop

expression2 statement for loop


expression3 for loop
expression2 statement
expression2 expression2 loop condition expression3 increment
expression
3.4 for loop

expression1

expression2
( ?)

no

yes
statement

expression3

statement

3.4 for loop

ForLoop2.java
for loop
for(number = 1; number <= 10; number++)
System.out.println("Number now is " + number);
Java number

number Java for
loop number++ number
number <= 10 number
for loop

1. number
2. number <= 10

System.out.println("Number now is " + number);



for loop
3. number++
4.

3
Java

(Repetition)

75

Expression


for loop expression

for loop


for loop

Infinite loop for loop
for(number = 1; number > 0; number++)
System.out.println("Number now is " + number);
For loop

number

for loop
int number = 1;
for(;;)
System.out.println("Number now is " + number);
for loop expression
loop
expression
int number = 1;
for(;number > 0;)
System.out.println("Number now is " + number);
infinite loop

for( ; ;) ;
for loop 1 100
/* Add1To100.java */
import java.io.*;
class Add1To100 {
public static void main(String[] args) {
int total = 0;

for(int i = 1; i <= 100; i++)


total += i;
System.out.println("Sum of 1 - 100 is " + total);

run
Sum of 1 100 is 5050
user

( user )

amount = p(1 + r)n

3
Java

(Repetition)

76

p (principal)
r
n
amount
/* Interests.java */
import java.io.*;
import java.lang.Integer;
class Interests {
public static void main(String[] args) throws IOException {
double amount;
//amount at the end of year
double principal; //first deposit
double rate;
//annual interests rate
int years;
//number of years
BufferedReader buffer;
InputStreamReader isr;
String input;
//get input from user (principal, rate, years)
System.out.print("Enter amount to deposit: ");
isr = new InputStreamReader(System.in);
buffer = new BufferedReader(isr);
input = buffer.readLine();
principal = Double.parseDouble(input);
System.out.print("Enter interests rate: ");
input = buffer.readLine();
rate = Double.parseDouble(input);
System.out.print("Enter number of year: ");
input = buffer.readLine();
years = Integer.parseInt(input);

//calculate and display amount


System.out.println("\nYear\tAmount on deposit");
for(int y = 1 y <= years; y++) {
amount = principal * Math.pow(1.0 + rate, y);
System.out.println(y + "\t" + amount);
}
System.out.print("\nTotal interests after " + years);
System.out.println(" years is " + (amount - principal));

run principal = 10000 rate = 0.25 years = 5


Enter amount to deposit: 10000
Enter interests rate: .25
Enter number of year: 5
Year
1
2
3
4
5

Amount on deposit
12500.0
15625.0
19531.25
24414.0625
30517.578125

3
Java

(Repetition)

77

Total interests after 5 years is 20517.578125

for loop ()
method Math.pow()
for loop y years
for loop



code
amount = principal;
System.out.println("\nYear\tAmount on deposit");
for(int y = 1; y <= years; y++) {
double interests = amount * rate;
//calculate interests
amount += interests;
//calculate new principal
System.out.println(y + "\t" + amount);
}
for loop
user
/* AddNumbers.java - reading numbers from input line
* user must specify space between those numbers and
* hit <enter> when done.
*/
import java.io.*;
import java.text.DecimalFormat;
class AddNumbers {
public static void main(String[] args) throws IOException {
double number, sum = 0; //a number read and sum of numbers
int count = 0;
//total numbers read
BufferedReader buffer;
//input buffer
InputStreamReader isr;
//input stream
StreamTokenizer token;
//token from input stream
DecimalFormat f = new DecimalFormat("0.00");
System.out.print("Enter numbers (space between
enter when done): ");
isr = new InputStreamReader(System.in);
buffer = new BufferedReader(isr);
//get tokens from input buffer
token = new StreamTokenizer(buffer);
//set priority to EOL so that we can break out of the loop
token.eolIsSignificant(true);
//get each number from tokens
//calculate the sum until EOL is reached
for(; token.nextToken() != token.TT_EOL ;) {
switch(token.ttype) {
//token is a number
case StreamTokenizer.TT_NUMBER:
number = token.nval; //save token in number
count++;
//number of tokens read

3
Java

(Repetition)

78

sum += number;
//calculate sum
break;
default:
System.out.println("Token is not a number! " +
token.toString());
break;

}
}
//calculate average and display result
double average = sum / count;
System.out.println("Sum of numbers = " + sum);
System.out.println("Average of numbers = " +
f.format(average));

AddNumbers.java method class StreamTokenizer for loop


User user <enter>

Java <enter>
loop method eolIsSignificant()
eolIsSignificant(true);
method <enter> user (

<ctrl> + c )
<enter> token keyboard
token EOL (End Of Line)
token
buffer token
token = new StreamTokenizer(buffer);
token
buffer EOL
switch token

sum count
for(; token.nextToken() != token.TT_EOL ;) {
switch(token.ttype) {
//token is a number
case StreamTokenizer.TT_NUMBER:
number = token.nval; //save token in number
count++;
//number of tokens read
sum += number;
//calculate sum
break;
default:
System.out.println("Token is not a number! " +
token.toString());
break;
}
}
token token.ttype
StreamTokenizer.TT_NUMBER token nval (
double) number double
number
number = token.nval;

3
Java

(Repetition)

79

token token

token token
for loop user <enter> <enter>
expression for loop for loop
expression 1 expression 3 for loop

for loop
<enter> user
run
Enter numbers (space between - enter when done): 20 30 45 789 12 34
Sum of numbers = 930.0
Average of numbers = 155.0
Enter numbers (space between - enter when done): 45 68 95
Sum of numbers = 208.0
Average of numbers = 69.33
Class StreamTokenizer field

AddNumbers.java
javadoc Sun
for loop , (comma) expression


/* Sum.java */
import java.io.*;
class Sum {
public static void main(String[] args) {
int i, sum;
for(i = 1, sum = 0; i <= 10; sum += i, i++) ;

System.out.println("Sum = " + sum);


System.out.println("Average = " + (double)sum / (i-1));

expression1 i = 0 sum = 0 ,
expression3 sum += i i++
for loop
expression3 ; ( {}) Java for loop

for(i = 1, sum = 0; i <= 10; sum += i, i++) ;

for(i = 1, sum = 0; i <= 10; sum += i, i++) { }


for loop for loop

3
Java

(Repetition)

80

sum = 0;
for(i = 1; i <= 10; i++)
sum += i;

sum += i
i++ Java
,

i++ sum += i

i i
sum for loop i 11
for loop


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

i = 1;
sum = 0;
for( ; i <= 10; ) {
sum += i;
i++;
}

sum = 0;
for( i = 1; i <= 10; ) {
sum += i;
i++;
}
code
Java
code code
code (?)
while loop
while loop for loop
( expression) while loop
while(expression)
statement;
while loop expression

while loop
( while loop)
while loop 3.5 while loop

3
Java

(Repetition)

Expression
( ?)

81

no

yes

statement

Next statement

3.5 while loop

while loop for loop


/* Sum.java */
import java.io.*;
class Sum {
public static void main(String[] args) {
int i, sum;
i = 0;
sum = 0;
while(i <= 10) {
sum += i;
i++;
}

System.out.println("Sum = " + sum);


System.out.println("Average = " + (double)sum / (i-1));

i sum
i <= 10 while loop i
sum i while loop for
loop
i = 0;
sum = 0;
expression for loop

3
Java

(Repetition)

82

i <= 10 expression for loop i++ expression for loop


( i 0
loop )
while loop for loop AddNumbers.java
/* AddNumbers2.java - reading numbers from input line
user must specify space between those numbers and
hit <enter> when done. (using while loop)
*/
import java.io.*;
import java.text.DecimalFormat;
class AddNumbers2 {
public static void main(String[] args) throws IOException {
double number, sum = 0; //a number read and sum of numbers
int count = 0;
//total numbers read
BufferedReader buffer;
//input buffer
InputStreamReader isr;
//input stream
StreamTokenizer token;
//token from input stream
DecimalFormat f = new DecimalFormat("0.00");

System.out.print("Enter numbers (space between


enter when done): ");
isr = new InputStreamReader(System.in);
buffer = new BufferedReader(isr);
//get tokens from input buffer
token = new StreamTokenizer(buffer);
//set priority to EOL so that we can break out of the loop
token.eolIsSignificant(true);
//get each number from tokens
//calculate the sum until EOL is reached
while(token.nextToken() != token.TT_EOL) {
switch(token.ttype) {
//token is a number
case StreamTokenizer.TT_NUMBER:
number = token.nval; //save token in number
count++;
//number of tokens read
sum += number;
//calculate sum
break;
default:
System.out.println("Token is not a number! " +
token.toString());
break;
}
}
//calculate average and display result
double average = sum / count;
System.out.println("Sum of numbers = " + sum);
System.out.println("Average of numbers = " +
f.format(average));


for(; token.nextToken() != token.TT_EOL ;)

3
Java

(Repetition)

83

while(token.nextToken() != token.TT_EOL)
code
for loop while loop

loop loop


do..while
Java loop


do while
do {

statement
}
while(expression);
3.6 do while loop

statement

yes

Expression
( ?)

no

statement

3.6 do while


do while loop
do
while loop
/* DoWhile.java - do .. while to repeat the program
until user enter a letter other than 'y'
*/
import java.io.*;

3
Java

(Repetition)

84

import java.lang.Integer;
class DoWhile {
public static void main(String[] args) throws IOException {
int score;
char grade, ch;
//set up buffer stream
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader buffer = new BufferedReader(isr);
do {
//get input string
System.out.print("Enter your score: ");
String input = buffer.readLine();
//convert string to int
score = Integer.parseInt(input);
//determine grade by given score
if(score > 90)
grade = 'A';
else if(score > 80)
grade = 'B';
else if(score > 70)
grade = 'C';
else if(score > 60)
grade = 'D';
else
grade = 'F';
System.out.println("Your grade is " + grade);
System.out.print("\nDO you want to continue? <y/n> : ");
String response = buffer.readLine();
ch = (char)response.charAt(0);

}
while(ch == 'y');

do while
System.out.print("\nDO you want to continue? <y/n> : ");
String response = buffer.readLine();
ch = (char)response.charAt(0);
user
y expression do while loop
do while loop
n (
y)
method chatAt() parameter buffer
ch do while loop
run
Enter your score: 89
Your grade is B

3
Java

(Repetition)

85

DO you want to continue? <y/n> : y


Enter your score: 12
Your grade is F
DO you want to continue? <y/n> : y
Enter your score: 75
Your grade is C
DO you want to continue? <y/n> : n
do while loop 1
100
/* Sum2.java */
import java.io.*;
class Sum2 {
public static void main(String[] args) {
int i, sum;
i = 0;
sum = 0;
do {
sum += i;
i++;
}
while(i <= 100);

System.out.println("Sum = " + sum);


System.out.println("Average = " + (double)sum / (i-1));

run
Sum = 5050
Average = 50.5
loop do while loop
loop code loop

loop

1
class Loops {
public static void main(String[] args) {
int index = 1;
while(index != 9) {
index += 2;
System.out.println(index);
index--;
}

3
Java

(Repetition)

86

2
class Loops1 {
public static void main(String[] args) {
int index1, index2;
index1 = 33;
index2 = 1;

while(index1 < index2) {


index1 = index1 + 10;
System.out.println(index1);
index2 = index2 * 2;
}

3
class Loops2 {
public static void main(String[] args) {
int index = 1;

while(index != 33) {
index++;
System.out.println(index);
index++;
}

break continue
loop loop
loop loop index

/* Sum3.java */
import java.io.*;
class Sum3 {
public static void main(String[] args) {
int i, sum;
i = 0;
sum = 0;
do {
sum += i;
i++;
//break out of loop when i >= 50
if(i >= 50)
break;
}

3
Java

(Repetition)

87

while(i <= 100);

System.out.println("Sum = " + sum);


System.out.println("Average = " + (double)sum / (i-1));

Sum2.java i
50 break loop
if(i >= 50)
break;
run
Sum = 1225
Average = 25.0
break loop

/* Break.java */
import java.io.*;
class Break {
public static void main(String[] args) {

for(int number = 1; ; number++)


if(number % 2 == 0) {
System.out.println("Number is " + number);
//break out of loop when number >= 10
if(number >= 10)
break;
}



loop

Number
Number
Number
Number
Number

is
is
is
is
is

2
4
6
8
10

continue
/* Continue.java */
import java.io.*;
class Continue {
public static void main(String[] args) {
for(int number = 1; number <= 10; number++) {

3
Java

(Repetition)

88

//skip if number is 5
if(number == 5)
continue;
System.out.println("Number is " + number);

code number

Number
Number
Number
Number
Number
Number
Number
Number
Number

is
is
is
is
is
is
is
is
is

1
2
3
4
6
7
8
9
10

continue



Nested Loop

loop
loop if else
loop
nested loop
/* NestedLoop.java */
import java.io.*;
class NestedLoop {
public static void main(String[] args) {

for(int row = 1; row <= 10; row++) {


for(int column = 1; column <= 10; column++) {
if(column > row)
continue;
System.out.print("*");
}
System.out.println();
}

NestedLoop.java for loop '*'


()

3
Java

(Repetition)

89

*
**
***
****
*****
******
*******
********
*********
**********
for loop row loop index
row for loop column loop index
for loop

for loop
column row
'*' continue

row column '*' column


row column
for loop
row
'*' column row
row for loop
break continue
break for loop

continue for loop row
( for loop
for loop - row)
nested-loop (
)
1
class Loops3 {
public static void main(String[] args) {
int j, k = 0;

while(k < 3) {
j = 5;
while(j > 0) {
System.out.println(j);
j -= 2;
}
System.out.println("k = " + k);
k++;
}

3
Java

(Repetition)

90

2
class Loops4 {
public static void main(String[] args) {
int j, k = 1;

while(k < 7) {
j = 5;
while(j > 0) {
System.out.println("j = " + j);
System.out.println("k = " + k);
j--;
}
k *= 2;
}

3
class Loops5 {
public static void main(String[] args) {
int j = 10, k = 1;

while(k < 8) {
while(j > 0) {
System.out.println("j = " + j);
System.out.println("k = " + k);
j--;
}
k = k * 2;
}

Labeled continue Labeled break for loop


Java
label

/* LabledContinue.java */
import java.io.*;
class LabeledContinue {
public static void main(String[] args) {

label: for(int row = 1; row <= 10; row++) {


System.out.println();
for(int column = 1; column <= 10; column++) {
if(column > row)
continue label;
//goto label
System.out.print("*");
}
}

3
Java

(Repetition)

91

Continue.java labeled continue


LabeledContinue.java identifier
label for loop
':' continue for loop

identifier continue
labeled continue column
row for loop for loop

label

continue break labeled break

/* LabledContinue.java */
import java.io.*;
class LabeledContinue {
public static void main(String[] args) {

System.out.println("Statement before first label.");


first:
for(int i = 1; i <= 10; i++) {
for(int j = 1; j <= 10; j++) {
if(j > i)
break first;
System.out.println('*');
}
}
System.out.println("Statement after first label.");

label
first
first
Statement before first label.
for loop
*

Statement after first label.
labeled break
block first Java

block first
System.out.println("Statement after first label.");

label block block labeled break


code
block
labeled break 1 5

3
Java

(Repetition)

92

/* LabledBreak.java */
import java.io.*;
class LabeledBreak {
public static void main(String[] args) {
int prod = 1;
int i = 1;

outer:
while(true) {
prod *= i;
i++;
if(i > 5)
break outer;
}
System.out.println("Product = " + prod);

while loop

( true expression)
labeled break while loop
i break block outer
block System.out.println("Product = " + prod)
Loop loop

loop Array
String


loop
9
9
9
9
9
9

if if-else
nested-if
Tertiary operator - ? :
switch
loop for-loop while-loop do-while-loop
break continue label

1. int keyboard 10

10
2.
100

10
3. 2

20
4.
A Z while loop
keyboard

3
Java

(Repetition)

93

5.

keyboard
( 10 )
6. 2 keyboard
(product
number)
(quantity sold) 5

1
2
3
4
5

500.0
750.0
850.0
950.0
1000.0



keyboard switch

7.
keyboard
( )
a = p(1 + r)n
p
r
n
a

column column column
run 5%
1000 10
8.
loop
**********
*********
********
*******
******
*****
****
***
**
*

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

9. int (n)
1 2 3 n-1 n
1 2 3 n-1

123
12
1

3
Java

(Repetition)

94

10. keyboard
12 29 2002 363
11. keyboard 0

user

12. 1 100
11
13.
keyboard

2 mod (26
) a a + c
97 + 99 = 196 % 26 = 14

14

n
14. 9 + 5 2 * 4 + 2 / 3

15. 1 12

16. sum code
class Loops6 {
public static void main(String[] args) {
int j = 0, k, m, n, sum = 0;

}
}

while(j != 20) {
k = 0;
while(k != 100) {
m = 0;
while(m != 50) {
n = 0;
while(n != 10) {
sum++;
n++;
}
m++;
}
k++;
}
j++;
}

17.
(GCD Greatest Common Divisor)
keyboard gcd 24 15 3
note: gcd x y integer
x y ( 0)
18.
(LCD Least Common Multiple)
keyboard lcd 24 15 120
note: lcd x y integer
x y

3
Java

(Repetition)

95

19.
factor keyboard 18 factor
2 3 3 (8 = 2 * 3 * 3)

array
string

object Java

o
o
o
o
o
o

array
array
array array
object string
array object
object string

array
Array
array array index integer (int)
Java index 0

array array
datatype[] nameOfArray;

int[] listOfNumbers;
double[] prices;
char[] vowels;
array array
array [] Java
array
array
array
int listOfNumbers[];
double prices[];
char vowels[];

array array
listOfNumbers = new int[5];

4
Java

Array String

97

Java Java int


10 listOfNumbers (reference)
array 4.1 array

array
num

array

array
int

int [] num = new int[5];


operator new
int 5

index
array num
num[0]

num[1]

num[2]

num[3]

num[4]

num.length 5

4.1 array

array
int [] num;
array
operator new

int [] num = new int[5];
Java 0

index
num[3]
num[2]

index 4 array num
5 index 0 1 2 3 4
Java error (array index out of bound)

array

array array int


array 0
/* Array1.java */
import java.io.*;
class Array1 {

4
Java

Array String

98

public static void main(String[] args) {


int[] list;
//declare array of int

list = new int[10];


//allocate space for 10 ints
for(int i = 0; i < list.length; i++)
System.out.println("list[" + i +"] = " + list[i]);

Array1.java list array int 10


for loop array Java
array
list[0]
list[1]
list[2]
list[3]
list[4]
list[5]
list[6]
list[7]
list[8]
list[9]

=
=
=
=
=
=
=
=
=
=

0
0
0
0
0
0
0
0
0
0

loop

array
array 5 3
list[5] list[3]
Array

Java array

array
list.length;
array array length
array . length

array
/* Array2.java */
import java.io.*;
class Array2 {
public static void main(String[] args) {
int[] list;
//declare array of int

list = new int[10];


//allocate space for 10 ints
list[5] = 8;
list[3] = 2;
list[9] = 4;
for(int i = 0; i < list.length; i++)
System.out.println("list[" + i +"] = " + list[i]);

run

4
Java

list[0]
list[1]
list[2]
list[3]
list[4]
list[5]
list[6]
list[7]
list[8]
list[9]

=
=
=
=
=
=
=
=
=
=

Array String

99

0
0
0
2
0
8
0
0
0
4

array array Java



/* Array3.java */
import java.io.*;
class Array3 {
public static void main(String[] args) {
int[] list = {2, 3, 1, 56, 90};

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


System.out.println("list[" + i +"] = " + list[i]);

list array int 2 3 1 56 90


Java
array
user array list run
list[0]
list[1]
list[2]
list[3]
list[4]

=
=
=
=
=

2
3
1
56
90

user keyboard array


/* ArrayOfNumbers.java */
import java.io.*;
import java.text.DecimalFormat;
import java.lang.Integer;
class ArrayOfNumbers {
public static void main(String[] args) throws IOException {
double number, sum = 0; //a number read and sum of numbers
double[] list;
//array of double
int count;
//number of items in array
String input;
//input string
BufferedReader buffer;
//input buffer
InputStreamReader isr;
//input stream
DecimalFormat f = new DecimalFormat("0.00");
System.out.print("How many numbers? : ");
isr = new InputStreamReader(System.in);
buffer = new BufferedReader(isr);

4
Java

Array String

100

input = buffer.readLine();
count = Integer.parseInt(input); //total items in list
list = new double[count];
//allocate space forlist
//reading each double into list
for(int i = 0; i < list.length; i++) {
System.out.print("Enter number: ");
input = buffer.readLine();
list[i] = Double.parseDouble(input);
}
//add all doubles in list
int n = list.length - 1; //n is the last index of list
while(n >= 0) {
//looping until n equals to 0
sum += list[n--];
//add list[n] into sum and
}
//decrement n

//calculate average and display result


double average = sum / count;
System.out.println("Sum of numbers = " + sum);
System.out.println("Average of numbers = " +
f.format(average));

ArrayOfNumbers.java user user


array
list = new double[count];
user array list
for(int i = 0; i < list.length; i++) {
System.out.print("Enter number: ");
input = buffer.readLine();
list[i] = Double.parseDouble(input);
}
array

loop array
n index array list
int n = list.length - 1;
list.length
array index
list.length 1 while loop array
sum
while(n >= 0) {
sum += list[n--];
}
sum += list[n--] n sum n

n 0 while loop

4
Java

Array String

101

array clone copy array


array

array array
array

/* Array4.java */
import java.io.*;
class Array4 {
public static void main(String[] args) {
int[] list = {2, 3, 1, 56, 90};
for(int i = 0; i < list.length; i++)
System.out.println("list[" + i +"] = " + list[i]);

int[] newList = list; //cloning


newList[0] = 11;
//changing data at list[0]
for(int i = 0; i < list.length; i++)
System.out.println("list[" + i +"] = " + list[i]);

Array3.java (reference) array list



newList
int[] newList = list;
0 11 newList run


list[0]
list[1]
list[2]
list[3]
list[4]

=
=
=
=
=

2
3
1
56
90

list[0]
list[1]
list[2]
list[3]
list[4]

=
=
=
=
=

11
3
1
56
90

copy array array






array copy array array
/* Array5.java */
import java.io.*;
class Array5 {
public static void main(String[] args) {
int[] list = {2, 3, 1, 56, 90};
int[] newList = new int[list.length];

//original array
//new array

4
Java

Array String

102

//copy each item from list into newList


for(int i = 0; i < list.length; i++)
newList[i] = list[i];
for(int i = 0; i < list.length; i++)
System.out.println("newList[" + i +"] = " + newList[i]);
}

Array5.java newList
int[] newList = new int[list.length];
newList list copy for
loop
for(int i = 0; i < list.length; i++)
newList[i] = list[i];
run

newList[0]
newList[1]
newList[2]
newList[3]
newList[4]

=
=
=
=
=

2
3
1
56
90



/* Array6.java */
import java.io.*;
class Array6 {
public static void main(String[] args) {
int[] list = {2, 3, 1, 56, 90};
int[] newList = new int[list.length];

//original array
//new array

//copy each item from list into newList


System.arraycopy(list, 0, newList, 0, list.length);
for(int i = 0; i < newList.length; i++)
System.out.println("newList[" + i +"] = " + newList[i]);
}

class method
method Java
method arraycopy() copy
(
) copy
System.arraycopy(list, 0, newList, 0, list.length);
(parameter) Java

4
Java

Array String

array
copy

index array

array

index array

copy

103

(list)
(0)
(newList)
(0)
(list.length)


method clone()
/* Array7.java */
import java.io.*;
class Array7 {
public static void main(String[] args) {
int[] list = {2, 3, 1, 56, 90};

//original array

//cloning process
int[] newList = (int[])list.clone();
for(int i = 0; i < list.length; i++)
System.out.println("newList[" + i +"] = " + newList[i]);
}

method clone() Array7.java array



int[] newList = (int[])list.clone();

cast array array clone


(int[]) list.clone()
array (list)

copy array
array
array array

/* Array8.java */
import java.io.*;
class Array8 {
public static void main(String[] args) {
int[] list = {2, 3, 1, 56, 90};
//original array
int[] newList = new int[list.length-2]; //new array
//copy item at index 2, 3, and 4 from list into newList
System.arraycopy(list, 2, newList, 0, list.length 2);

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


System.out.println("newList[" + i +"] = " + newList[i]);

4
Java

Array String

104

Array8.java copy 2 3 4 array list


array newList 0 1 2
method arraycopy()

System.arraycopy(list, 2, newList, 0, list.length 2);


run
newList[0] = 1
newList[1] = 56
newList[2] = 90
array (Dynamic Array)

array
array
array
array AddNumbers.java

/* DynamicArray.java */
import java.io.*;
import java.text.DecimalFormat;
class DynamicArray {
public static void main(String[] args) throws IOException {
double number, sum = 0; //a number read and sum of numbers
double []list = new double[2]; //array of double
int count = 0;
//total numbers read
BufferedReader buffer;
//input buffer
InputStreamReader isr;
//input stream
StreamTokenizer token;
//token from input stream
DecimalFormat f = new DecimalFormat("0.00");
System.out.print("Enter numbers (space between
enter when done): ");
isr = new InputStreamReader(System.in);
buffer = new BufferedReader(isr);
//get tokens from input buffer
token = new StreamTokenizer(buffer);
//set priority to EOL so that we can break out of the loop
token.eolIsSignificant(true);
//get each number from tokens
//calculate the sum until EOL is reached
while(token.nextToken() != token.TT_EOL) {
switch(token.ttype) {
//token is a number
case StreamTokenizer.TT_NUMBER:
//double the size of list
if(count > list.length-1) {
double []newList = new double[list.length*2];
System.arraycopy(list, 0, newList, 0,
list.length);
list = newList;
//point to new list
}
list[count] = token.nval; //save token into list

4
Java

Array String

105

sum += list[count];
//calculate sum
count++;
//number of tokens read
break;
default:
System.out.println("Token is not a number! ");
break;

}
}
//calculate average and display result
double average = sum / count;
System.out.println("Sum of numbers = " + sum);
System.out.println("Average of numbers = " +
f.format(average));

list array double 2


array index
array list
copy array list array (newList)
array (list)
array Java


if(count > list.length-1) {
double []newList = new double[list.length*2];
System.arraycopy(list, 0, newList, 0, list.length);
list = newList;
}
array array
array array
array


run DynamicArray.java
Enter numbers (space between - enter when done): 15 5 20 15 10 15 20
Sum of numbers = 100.0
Average of numbers = 14.29
array
/* DiceRolling.java */
import java.io.*;
class DiceRolling {
public static void main(String[] args) {
int face, roll;
int[] frequency = new int[7];//number of times each face occur
//rolling the die for 100 times
roll = 1;
while(roll <= 100) {
//calculate face of die
face = (int)(Math.random() * 6) + 1;

4
Java

Array String

106

//save each time the same face occur by using


//indeces as faces of die
frequency[face]++;
roll++;

System.out.println("Face\tFrequency");
for(int i = 1; i < frequency.length; i++)
System.out.println(i + "\t" + frequency[i]);
}

DiceRolling.java index array


method random() 1 6 6
1 index
6 frequency[6]++

index array
if else

if(face == 1)
count1++;
else if(face == 2)
count2++;
else if(face == 3)
count3++;

else if(face == 6)
count6++;
code frequency[face]++
run
Face
1
2
3
4
5
6

Frequency
12
25
24
7
12
19

array
array
(sequential search)
(binary search)


(Sequential search)

array

array

4
Java

Array String

107

/* SeqSearch.java */
import java.io.*;
class SeqSearch {
public static void main(String[] args) {
int[] list = {2, 3, 1, 56, 90};;
int number = 90;
//number to search
int i = 0;
//loop index
boolean notFound = true; //loop control variable
while(notFound) {
if(number == list[i]) //if found
notFound = false; //break out of loop
i++;
//move to next number
}
//in the list

if(!notFound)
System.out.println(number + " is in the list.");
else
System.out.println(number + " is not in the list.");

while loop
array list notFound
boolean loop
notFound false while loop
90
90 is in the list.
boolean loop loop
break
code
/* SeqSearch2.java */
import java.io.*;
class SeqSearch2 {
public static void main(String[] args) {
int[] list = {2, 3, 1, 56, 90};
int number = 90;
//number to search
int i = 0;
//loop index
while(true) {
if(number == list[i]) //if found
break;
//break out of loop
i++;
//move to next number
}
//in the list

if(i >= list.length)


System.out.println(number + " is not in the list.");
else
System.out.println(number + " is in the list.");

4
Java

Array String

108

list i
array
i array (
boolean ) loop
break loop

array array
(Binary search)
binary search

(key) key
array key
key

key array


binary search
array 1024 10
512 256 128 64 32 16 8 4 2 1
binary search BinSearch.java
binary search
/* BinSearch.java */
import java.io.*;
class BinSearch {
public static void main(String[] args) {
int[] list = {1, 2, 3, 4, 5, 6, 7, 8 ,9, 10};
//generate key to search
int key = (int)(Math.random() * 10 + 1);
int low = 0;
//lower index
int high = list.length - 1; //higher index
int middle;
//number at the middle (pivot)
boolean found = false;
//indicate search result

while(low <= high) {


middle = (low + high) / 2;
//calculate pivot
if(key == list[middle]) {
//if found - stop searching
found = true;
break;
}
else if(key < list[middle]) //key is in lower half
high = middle - 1;
else
low = middle + 1;
//key is in upper half
}
if(found)
System.out.println("Found " + key + "!");
else
System.out.println(key + " not found!");

4
Java

Array String

109

BinSearch.java array list 10


(key) index (low)
(high) array 0 list.length 1 while loop
array list low high low
high list


middle = (low + high) / 2;

if(key == list[middle]) {
found = true;
break;
}

else if(key < list[middle])


high = middle - 1;
else
low = middle + 1;
index
middle 1 key
middle low middle + 1 key middle
middle
(sort) array

array
Java
()
method sort Java

array sort method sort() Java


Arrays.sort(list)
list array sort Sort.java sort class
Arrays
//Sort.java - recursive version
import java.lang.Integer;
import java.util.Arrays;
class Sort {
public static void main(String[] args) {
int[] list = new int[100];
//array with 100 ints
int i;
//loop index
//populate list with random ints
for(i = 0; i < 100; i++)
list[i] = (int)(Math.random() * 100 + 1);

4
Java

Array String

110

//display 100 ints to screen 20 per line


for(i = 0; i < list.length; i++) {
if(i % 20 == 0)
System.out.println();
System.out.print(list[i] + "\t");
}
System.out.println();
Arrays.sort(list);

//calling sort from class Arrays

//display again
for(int j =0 ; j < list.length; j++) {
if(j % 20 == 0)
System.out.println();
System.out.print(list[j] + "\t");
}
System.out.println();

method class Arrays



method binarySearch() code
binary search
BinarySearch.java method
binarySearch()
//BinarySearch.java - recursive version
import java.util.Arrays;
class BinarySearch {
public static void main(String[] args) {
int[] list = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int key = (int)(Math.random() * 10 + 1);//key to search for
int found = Arrays.binarySearch(list, key);

if(found >= 0)
System.out.println("Found " + key + " at index " + found);
else
System.out.println(key + " is not in the list!");

method binarySearch() parameter 2 (1) array


list
(2) key
int found = Arrays.binarySearch(list, key)
list method binarySearch() index
found
0
found 0
run
Found 3 at index 2
Found 1 at index 0

4
Java

Array String

111

array
array (Array of arrays)
array primitive type
array
array

int[][] table = new int[5][5];
table array 5
array
int 5 [][] Java array
array array array 2 4.2 array
table
index

array

(index)
[0]

[1]

[2]

[3]

[4]

table[0]

table[1]

table[2]

table[3]

table[4]

int [] [] table = new int [5] [5];


4.2 array array (array 2 )

Array9.java
array 2 5 x 5
1 10 random()
table length array 1

table[0].length
table[3].length
Array9.java table[i].length i index

/* Array9.java */
import java.io.*;

4
Java

Array String

112

class Array9 {
public static void main(String[] args) {
int[][] table = new int[5][5];
for(int i = 0; i < table.length; i++) {
for(int j = 0; j < table[i].length; j++)
table[i][j] = (int)(1 + Math.random() * 10);
}
for(int i = 0; i < table.length; i++) {
for(int j = 0; j < table[i].length; j++)
System.out.print(table[i][j] + "\t");
System.out.println();
}
}

run Array9.java
7
5
7
7
10

3
8
6
10
4

2
5
8
9
4

8
4
6
7
2

7
8
2
5
2

array 2
Java
/* Array10.java */
import java.io.*;
class Array10 {
public static void main(String[] args) {
//declare 2-D array with specific data
int[][] table = { {1, 2, 3},
{5, 6, 8},
{7, 4, 6},
{4, 8, 9} };
for(int i =0 ; i < table.length; i++) {
for(int j = 0; j < table[i].length; j++)
System.out.print(table[i][j] + "\t");
System.out.println();
}
}

table array 2
4 3
{}
,
int[][] table = { {1, 2, 3},
{5, 6, 8},
{7, 4, 6},

/* 0 */
/* 1 */
/* 2 */

4
Java

Array String

{4, 8, 9}
};

113

/* 3 */


int[][] table = {{1, 2, 3}, {5, 6, 8}, {7, 4, 6}, {4, 8, 9}};
run
1
5
7
4

2
6
4
8

3
8
6
9

array

array
double [][] list = new double[5][];
array 2
5
0 4 4 10

list[0] = new double[4];
list[4] = new double[10];

(index)
int m = 0;
while(m < 5) {
list[m] = new double[m + 1];
m++;
}
Array11.java array 2
index
/* Array11.java */
import java.io.*;
class Array11 {
public static void main(String[] args) {
double [][]list
= new double[5][];
//allocate space for each row
int m = 0;
while(m < 5) {
list[m] = new double[m + 1];
m++;
}
for(int i = 0; i < list.length; i++) {
for(int j = 0; j < list[i].length; j++)
System.out.print(list[i][j] + "\t");
System.out.println();

4
Java

Array String

114

run
0.0
0.0
0.0
0.0
0.0

0.0
0.0 0.0
0.0 0.0 0.0
0.0 0.0 0.0 0.0

array


8 x 25 = 200 byte
8 x 15 = 120 byte
array


array
Array of arrays max min

//ArrayOfArrays.java
import java.io.*;
class ArrayOfArrays {
public static void main(String[] args) {
//inititial scores
int [][]score = { {45, 87, 68, 57},
{98, 70, 58, 69},
{85, 42, 68, 82} };
double average;
//average of scores
int max, min, total = 0; //maximum, minimum, total of scores
int count = 0;
//total scores
max = score[0][0];
//assuming max score is at [0][0]
min = score[0][0];
//assuming min score is at [0][0]
//looping for 3 rows
for(int i = 0; i < score.length; i++) {
//looping for 4 columns
for(int j = 0; j < score[i].length; j++) {
if(score[i][j] > max) //find max score
max = score[i][j];
if(score[i][j] < min) //find mim score
min = score[i][j];
total += score[i][j]; //calculate total
count++;
//number of scores
}
}
//calculate average of scores
average = (double)total / count;
System.out.println("Maximum score is " + max);
System.out.println("Minimun score is " + min);
System.out.println("Average score is " + average);

4
Java

Array String

115

ArrayOfArrays.java score array 3


4 score
score

score
for loop 2 array score
max score min
array array
if(score[i][j] > max)
max = score[i][j];
max score[i][j]

max
if(score[i][j] < min)
min = score[i][j];
min score[i][j]
min
max min max min
array range
max min max min
(
method max() min()
class Math )

array of arrays table


array of arrays
row column array 2 (two dimensional array)
array of arrays array array 3

array
3
3 ( array 3 )
String
string array
string
string
array String string
array char array of characters
string array of characters string
String Java
Array of characters
string array

array char
char [] string = new char[20];
array char 20
array of characters
//ArrayOfChars.java
import java.io.*;
class ArrayOfChars {
public static void main(String[] args) {

4
Java

Array String

116

//declare array of char


char[] str = new char[26];
int i = 0;

//populate str with characters a to z


for(char c = 'a'; c <= 'z'; c++) {
str[i] = c;
i++;
}
//print all characters to screen
for(i = 0; i < 26; i++)
System.out.print(str[i]);
System.out.println();

ArrayOfChars.java array of chars 27


char[] str = new char[26];
for loop str char index
loop
char
char c = 'f' c c 'g'

ASCII for loop


str
for(char c = 'a'; c <= 'z'; c++) {
str[i] = c;
i++;
}

abcdefghijklmnopqrstuvwxyz
array of characters array
string string 2
string Java class String
string
String Java
String Java object class String string
user string
user
String
String str = new String("Java is fun");

String str = "Java is fun";


2
char[] str = {'J', 'a', 'v', 'a', ' ', 'i', 's', ' ', 'f', 'u', 'n'};
String str = new String(str);

4
Java

Array String

117

string array of chars string


string
String name;
name string compile
error Java compile
null string name
String name = null;
Java string name

string
//StringOps.java
import java.io.*;
class StringOps {
public static void main(String[] args) {
String first = "Java ";
String second = "Programming";
String third = null;
int percent = 100;

third = first + second;


System.out.println(third + " is " + percent + "% fun!");

StringOps.java String 3 first second third


first "Java " second "Programming" third string
percent 100
third = first + second;
first second third "Java Programming"

percent string

Java Programming is 100% fun!

string string

int percent = 100;
String is = " is ";
String fun = "%fun!";
String int
third = first + second + is + percent + fun;

4
Java

Array String

118

Java int
string string
String
string 2 ==
primitive type
first == third
string (
string
string )
String myString = "Motorcycle";
String yourString = myString;
myString yourString ( true
==)
string
String keyboard = "from Thailand";
String kb = "from Thailand";

if(keyboard == kb)
false ==
( address )

method Java class String
string
//StringCompare.java
import java.io.*;
class StringCompare {
public static void main(String[] args) {
String first = "Java ";
String second = "Programming";
String third = "Java Programming";
String forth;
forth = first + second; //forth is "Java Programming"
if(third == forth)
System.out.println("third and forth refer to
the same string");
else
System.out.println("third and forth do not refer to
the same string");
first = forth; //first and forth refer to the same string
System.out.println("first is " + first);
System.out.println("forth is " + forth);
if(first == forth)
System.out.println("first == forth is true");
else

4
Java

Array String

119

System.out.println("first == forth is false");

StringCompare.java string ==
string third forth (string char
) run
third and forth do not refer to the same string
== string
first
forth run
first is Java Programming
forth is Java Programming
first == forth is true
string method equals() method compareTo()

//StringCompare1.java
import java.io.*;
class StringCompare1 {
public static void main(String[] args) {
String first = "Java ";
String second = "Programming";
String third = "Java ProgramminG";
String forth;
forth = first + second; //forth is "Java Programming"
if(third.equals(forth))
System.out.println("third equals forth");
else
System.out.println("third not equals forth");

first = forth; //first and forth refer to the same string


if(first.equals(forth))
System.out.println("first equals forth");
else
System.out.println("first not equals forth");

third "Java ProgramminG"


char run
third not equals forth
first equals forth
third.equals(forth) third forth ()
true false
string 2

4
Java

Array String

120

third.equals(forth) forth.equals(third)
method equals() string
g
G false

string
method equalsIgnoreCase()
string

equals()
equalsIgnoreCase()
if(third.equalsIgnoreCase(forth))
System.out.println("third equals forth");
else
System.out.println("thrid not equals forth");

third equals forth


( ) string
string string


string method compareTo()
myString.compareTo(yourString);
myString "lovely bike" yourString "lovely kite"
compareTo() 'k' yourString
'b' myString method compareTo()
//StringCompareTo.java
import java.io.*;
class StringCompareTo {
public static void main(String[] args) {
String first = "lovely bike";
String second = "lovely kite";
String third = "lovely";
//compare first and second
if(first.compareTo(second) > 0)
System.out.println("first is greater than second");
else
System.out.println("second is greater than first");
//compare first and third
if(first.compareTo(third) > 0)
System.out.println("first is greater than third");
else
System.out.println("third is greater than first");
String a = "A";

4
Java

Array String

121

String z = "Z";
String str1 = "AAA";
String str2 = "AAA";
//compare a and z
if(a.compareTo(z) < 0)
System.out.println(a + " is less than " + z);

//compare str1 and str2


if(str1.compareTo(str2) == 0)
System.out.println(str1 + " equals " + str2);

run
second is greater than first
first is greater than third
A is less than Z
AAA equals AAA
first second 0
first second true first second
false Java else (
)
method compareTo() 0 true
false
==

if(str1.compareTo(str2) == 0)
System.out.println(str1 + " equals " + str2);
method compareTo()
3 -1, 0,
1
-1 string string (string parameter)
0 string
1 string
string
string1.compareTo(string2);
string1 string

string2 string
string parameter

string

string method
StringChars.java
//StringChars.java
import java.io.*;

4
Java

Array String

122

import java.lang.Character;
class StringChars {
public static void main(String[] args) {
//setting up constant string
String string = "Learn to write programs in Java doesn't take"
+ " as long as I think it would. But to fully understand"
+ " it is a time consuming task.";
int
int
int
int
int

charCount = 0;
vowelCount = 0;
lowerCaseCount = 0;
upperCaseCount = 0;
spaceCount = 0;

//count
//count
//count
//count
//count

of
of
of
of
of

letters
vowels
lowercase letters
uppercase letters
white spaces

//check all letters


for(int i = 0; i < string.length(); i++) {
char ch = string.charAt(i);
//check if it's a letter
if(Character.isLetter(ch))
charCount++;
//check if it's an uppercase
if(Character.isUpperCase(ch))
upperCaseCount++;
//check if it's a lowercase
if(Character.isLowerCase(ch))
lowerCaseCount++;
//check if it's a white space
if(Character.isWhitespace(ch))
spaceCount++;

//convert it to lowercase
ch = Character.toLowerCase(ch);
//check if it's a vowel
if(ch == 'a' || ch == 'e' || ch == 'i' ||
ch == 'o' || ch == 'u')
vowelCount++;

System.out.println(charCount + " characters counted.");


System.out.println(upperCaseCount +
" uppercase letters counted.");
System.out.println(lowerCaseCount +
" lowercase letters counted.");
System.out.println(vowelCount + " vowels counted.");
System.out.println(charCount - vowelCount +
" consonants counted.");
System.out.println(spaceCount + " spaces counted.");

run
99 characters counted.
4 uppercase letters counted.
95 lowercase letters counted.
37 vowels counted.
62 consonants counted.

4
Java

Array String

123

24 spaces counted.

string " "


for loop string
char ch = string.charAt(i)
index i ch
method class Character
Character.isLetter(ch)
Character.isUpperCase(ch)
Character.isLowerCase(ch)
Character.isWhitespace(ch)

true
true
true
true

( tab)

string

ch = Character.toLowerCase(ch);
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
vowelCount++;
method class Character class String
string (sub string) string method
indexOf()
//IndexOf.java
import java.io.*;
import java.lang.Character;
class IndexOf {
public static void main(String[] args) {
//setting up constant string
String string = "Learn to write programs in Java doesn't take"
+ " as long as I think it would. But to fully understand"
+ " it is a time consuming task.";
int itCount = 0; //count of it
String it = "it"; //string to seach for
//search for "it"
int index = string.indexOf(it);
while(index >= 0) {
itCount++;
//move to first letter after last "it"
index += it.length();
//look for next "it"
index = string.indexOf(it, index);
}

System.out.println("it appeared " + itCount + " times.");

4
Java

Array String

124

it appeared 3 times.
index "it" string
int index = string.indexOf(it)
while loop
itCount index
"it" index += it.length() method indexOf()
"it"
index = string.indexOf(it, index)
string while loop
indexOf()

0 index
-1 while loop
Method indexOf()
(parameter)
sub string sub string
(index) indexOf()

index
index
indexOf() -1 sub string string
sub string sub string

() sub string
string
//SubString.java
import java.io.*;
import java.lang.Character;
class SubString {
public static void main(String[] args) {
//setting up constant string
String string = "Learning Java";
String str1 = string.substring(0);
String str2 = string.substring(9);
String str3 = string.substring(0, 8);

//the whole string


//string: "Java"
//string: "Learning"

System.out.println("str1 > " + str1);


System.out.println("str2 > " + str2);
System.out.println("str3 > " + str3);

Java method substring()


substring() parameter substring()
parameter
index sub string parameter

index sub string

4
Java

Array String

125

String str2 = string.substring(9)


index = 9 string 'J'
'a' "Java"
String str3 = string.substring(0, 8)

index = 0 8 'L' ' ' (space)


space sub string "Learning"

sub string string


String sub = "Basic idea about Java".substring(6) "idea about
Java"

String sub = "Basic idea about Java".substring(6, 10) "idea"


4.1 method class String
4.1 method class String
method
length()
indexOf(String)
indexof(String, start index)
lastIndexof(String)
lastIndexof(String, start index)
trim()
substring(start index)
substring(start index, end index)
replace(old char, new char)
charAt(index)
equals(String)
equalsIgnoreCase(String)
startsWith(String)
startsWith(String, start index)
endsWith(String)

String ()
String -1
String
-1
String -1
String
-1
String space
String
String
char char

true String
true String case
true String String
true String String

true String String

class StringBuffer string


class String class StringBuffer
string
StringBuffer string = new StringBuffer("Basic String Operations");
object string class StringBuffer "Basic String
Operations"
string class String
new

4
Java

Array String

126

StringBuffer string = null;


string = new StringBuffer("Just another way to declare");

StringBuffer string = "Just another way to declare";


StringBuffer
string (object
class String ) string class
StringBuffer object class
StringBuffer
//StringBufferTest.java
import java.io.*;
class StringBufferTest {
public static void main(String[] args) {
//setting up constant string
StringBuffer string = new StringBuffer("fish");
System.out.println("string is " + string);
//append "er" after "fish"
string.append("er");
System.out.println("string is " + string);

//append "man" after "fisher" using method insert()


string.insert(string.length(), "man");
System.out.println("string is " + string);

StringBufferTest.java object class StringBuffer


StringBuffer string = new StringBuffer("fish")
string
f i
uiui

string string "er" string "fish"

string.append("er")
string
f

string "fisher"
string string "man" string
method insert()
string.insert(string.length(), "man")

4
Java

Array String

127

string
f

insert() parameter 2 1). string


2). string "man" run
string is fish
string is fisher
string is fisherman

object class StringBuffer


string.setLength(6)
string string

System.out.println("string after set length is " + string)


run
string after set length is fisher
string object class StringBuffer
append() insert()
//StringBufferTest1.java
import java.io.*;
class StringBufferTest1 {
public static void main(String[] args) {
//setting up constant string
StringBuffer string = new StringBuffer();
string.append(2);
System.out.println("string is " + string);
//append " fisher" after 2
string.append(" fisher");
System.out.println("string is " + string);
//append "men" after "fisher" using method insert()
string.insert(string.length(), "men");
System.out.println("string is " + string);
string.append(" with ");
System.out.println("string is " + string);

string.append(100);
string.append(" fish.");
System.out.println("string is " + string);

4
Java

Array String

128

method append() int


string.append(2) string.append(100) Java

object class StringBuffer

string
string
string
string
string

is
is
is
is
is

2
2
2
2
2

fisher
fishermen
fishermen with
fishermen with 100 fish.

class StringBuffer buffer


object class Java buffer
buffer 16 object
StringBuffer name = new StringBuffer("Chiang Mai");
() 10 Java 26
buffer method capacity()

StringBuffer s = new StringBuffer("Chaing Mai");


System.out.println("Length of " + s + " is " + s.length());
System.out.println("Capacity of " + s + " is " + s.capacity());

Length of Chaing Mai is 10
Capacity of Chaing Mai is 26
method
string (reverse)
//ReverseString.java
import java.io.*;
class ReverseString {
public static void main(String[] args) {
//setting up a constant string
StringBuffer string = new StringBuffer("I love Chaing Mai");
//create an empty string
StringBuffer revStr = new StringBuffer();
revStr.append(string);
//append string to revStr
revStr.reverse();
//reverse it

System.out.println("Reverse of [" + string + "] is ["


+ revStr + "]");

run
Reverse of [I love Chaing Mai] is [iaM gniahC evol I]

4
Java

Array String

129

string "I love Chiang Mai" object


StringBuffer revStr = new StringBuffer() string
revStr method append()
revStr.reverse() reverse revStr
reverse
object string revStr
revStr
StringBuffer revStr = new StringBuffer(string)
Java method object class StringBuffer

1. StringBuffer()
2. StringBuffer(int len) buffer
3. StringBuffer(String str) object class String
method string
string
4.2 method class StringBuffer
4.2 method class StringBuffer
method
capacity()
length()
setLength(new length)
append(value)
insert(index, value)
replace(start index, end index, String)
delete(start index, end index)
deleteCharAt(index)
setCharAt(index, character)
charAt(index)
substring(index)
substring(start index, end index)
toString()
reverse()

StringBuffer
StringBuffer
StringBuffer
StringBuffer
StringBuffer
String




substring String
substring
object String StringBuffer
StringBuffer

array string (Array of Strings)


string object
string array string
array array
method main()
public static void main(String[] args) {
() String [] args args
array of strings array
string array of
strings
//ArrayOfStrings.java
import java.io.*;

4
Java

Array String

130

class ArrayOfStrings {
public static void main(String[] args) {
//declare array of 5 strings
String[] names = new String[5];
//initialize array
names[0] = "Kafe";
names[1] = "River Side";
names[2] = "Good View";
names[3] = "Cottage";
names[4] = "Club G";
String word = names[2].substring(0, 4);
System.out.println("First word from names[2] is " + word);

for(int i = 0; i < 5; i++) {


System.out.println(names[i]);
}

names array of Strings


5
String[] names = new String[5];
array names
names[2]
for loop
run
First word from names[2] is Good
Kafe
River Side
Good View
Cottage
Club G
array of Strings
array array of Strings
array array of
Strings

array String StringBuffer


object class String class StringBuffer
method



9
9
9
9
9
9
9
9

array
array index
array length
Array array
object string class String

string method length()
String method string
string
class StringBuffer

4
Java

9
9

Array String

131

StringBuffer method string


string class StringBuffer method length() object
StringBufer method capacity()

1. int keyboard 10 array




2. Math.random() 100 array

5 20
3.
array 2 3 x 3 2
int
array Math.random()
1 9
array 2 (Matrix addition) array
array
4. object class String keyboard
string

string

5. array string 10 day/month/year
02/10/00 string
2 October 2000
6. array char 10 reverse

array array
7. StringBuffer string 10 string
string string
char
string
char ()
8. array 20
user keyboard

9. array1 array2 array int 10


array array
array
array
10. String 1

(space) Micha Sapporo String 2 1
1
11. 10
keyboard
12. String 2 keyboard String

String

13. String 2 keyboard String

user user String
String
14.

4
Java

Array String

132

String 112 Newell Street, Walla Walla, WA 99210


String
No.
Street:
City:
State:
Zip:

112
Newell Street
Walla Walla
WA
99210

15.

String String I love Chiang Mai
Mai Chiang love I

class
( class) Java object class String class
StringBuffer class object class
class

o
o
o
o
o
o
o
o

class class
constructor
method
overload method
object class
attribute class
nested class
package

Class class
class

class Object-Oriented
Programming (OOP) class (prescription)
( class ) class
class ( ) object
keyboard










start OOP




(
method class String code )
class String
method

object class String
method
object class
class


class

5
Java

Objects Classes

134

Field object
object class field Data member
class variable (identifier)

Method (operation) object class



data member

Field Data member


(reference) object class (
String array

) class
Method method
data member (
method main())
class class Student

class name

Data member

Instance variable

class Student {
String id;
String firstname;
String lastName;
String dateOfBirth;
static int count = 0;

Class variable

Constructor
Student(String iden, String fName,

}
Method

Parameter list

public int getCount() {


return count;
}

//method

5.1 class Student

Class Student
data member method

class data member
class (Class variable Instance variable)
Object class instance class object class
class class
variable instance variable
object object copy class
object object

5
Java

Objects Classes

135

object class Student


object
copy
instance variable
class variable object class

object
class class class object
object class

instance variable object (copy)
object class
variable static 5.2

class Student {
static int count = 0;
String
String
String
String

Object share
count

id;
firstname;
lastName;
dateOfBirth;

0
Joe
id
firstNAme
lastName
dateOfBirth

Joe Jon copy

Jon
id
firstNAme
lastName
dateOfBirth

5.2 class variable instance variable

class variable
object


class count object
instance variable class
object class
object class Student id


class object
class


data
method
execute
execute

object
class class

execute

data
execute

5
Java

Objects Classes

136

Method
5.1 method class Student () method
( )
class class
method
class method instance
method
Class method method object
method main() object class method
main() class method class variable
static
instance method method
instance variable
method class object
instance method
method class
method class
object class . (dot) method
studentA.firstName;

studentB.getAge();

method method Java
error method
class
class class Student

//Student.java - Simple class for student
import java.lang.Integer;
import java.util.Calendar;
class Student {
String id;
String firstName;
String lastName;
String dateOfBirth;

//student id
//student's first name
//student's last name
//student's date of birth in
//the form: dd/mm/yyyy
static int count = 0; //number of object created
//class constructor to initialize fields to given values
Student(String iden, String fName, String lName, String dOfB) {
id = iden;
firstName = fName;
lastName = lName;
dateOfBirth = dOfB;
count++;
}
//method to return count
public int getCount() {

5
Java

Objects Classes

137

return count;

//method to return student's id


public String getId() {
return id;
}
//method to returnstudent's first name
public String getFirstName() {
return firstName;
}
//method to return student's last name
public String getLastName() {
return lastName;
}
//method to return student's date of birth
public String getDateOfBirth() {
return dateOfBirth;
}
//method to calculate student's age from
//year of birth
public int getAge() {
//retrieve a year
String year = dateOfBirth.substring(6);
//convert it to an int
int birthYear = Integer.parseInt(year);

//get current year from system's calendar


Calendar now = Calendar.getInstance();
int thisYear = now.get(Calendar.YEAR);
//return the difference
return thisYear - birthYear;

//method to display students' info to screen


public void display() {
System.out.print(getId() + " ");
System.out.print(getFirstName() + " ");
System.out.print(getLastName() + " ");
System.out.println("Age: " + getAge());
}

class Student field 5 field id, firstName, lastname, dateOfBirth,


count
instance variable object
class variable object
method 7
method
class method Student
Student(String iden, String fName, String lName, String dOfB) {
id = iden;
firstName = fName;
lastName = lName;

5
Java

Objects Classes

138

dateOfBirth = dOfB;
count++;

Student() method constructor class constructor


object class
field field field ( constructor )
constructor field field ( class variable
count)
parameter list constructor
constructor
constructor Java object
constructor method method
method method
method
method
method parameter ()
method () method
o
o

Method

method
Method

method

method

Parameter ()

void

returnType methodName( arg1, arg2, , argn ) {


// body of method

method (body of method)

5.3 method

method getAge() class Student


method
public int getAge() {
String year = dateOfBirth.substring(6);
int birthYear = Integer.parseInt(year);

5
Java

Objects Classes

139

Calendar now = Calendar.getInstance();


int thisYear = now.get(Calendar.YEAR);
return thisYear - birthYear;


method
Parameter

int
getAge

String year = dateOfBirth.substring(6);


int birthYear = Integer.parseInt(year);
Calendar now = Calendar.getInstance();
int thisYear = now.get(Calendar.YEAR);
return thisYear - birthYear;

method getAge() public public


method
method

return method getAge()


Java

return

Java error
compile
method class Student
public void display() {
System.out.print(getId() + " ");
System.out.print(getFirstName() + " ");
System.out.print(getLastName() + " ");
System.out.println("Age: " + getAge());
}


method
Parameter

display

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


System.out.print(getFirstName() + " ");
System.out.print(getLastName() + " ");
System.out.println("Age: " + getAge());

Method display() object class Student


method class Student method
void method method void
return
return ; (semicolon)
void return ; method
display()
public void display() {
System.out.print(getId() + " ");
System.out.print(getFirstName() + " ");
System.out.print(getLastName() + " ");
System.out.println("Age: " + getAge());

5
Java

Objects Classes

140

return ;

method method
method
return

method

method
return
;
method void


parameter list
method parameter list
class Student
//Parameters.java
class Parameters {
public static void main(String[] args) {
double radius = 2.0;
double area = findArea(radius);
}

System.out.println("Area of a circle is : " + area);

public static double findArea(double r) {


return Math.PI * r * r;
}

Parameters.java method class method (


method class method class variable
static ) method
( 2) method findArea() Parameter
double

class Parameters method findArea(()

double area = findArea(radius);


Java Java execute method findArea() parameter
double 2.0

area 5.4 parameter list

5
Java

Objects Classes

141

class Parameters {
public static void main(String[] args) {
double radius = 2.0;
double area = findArea(radius);

radius
r

public static double findArea(double r) {


return Math.PI * r * r;
}

area

5.4 parameter method method

parameter list
1) pass-by-value
method 2) pass-by-reference
primitive type Java pass-by-value
5.5
class PassByValue {
public static void main(String[] args) {
int total = 10;

int newTotal = increment(total);

copy
total

total
10

copy total
10

public static int increment(int sum) {


sum += 10;
}

return sum;
sum
copy
total
main()

5.5 pass-by-value

total
method main()

method increment() total
copy total

5
Java

Objects Classes

142

method pass-by-value method



method
pass-by-reference
pass-by-value
//PassByValue.java
class PassByValue {
public static void main(String[] args) {
int total = 10;
System.out.println("Before calling: total is " + total);

System.out.println("Value returns from increment() is " +


increment(total));
System.out.println("After calling: total is " + total);

public static int increment(int sum) {


sum += 10;

return sum;

run
Before calling: total is 10
Value returns from increment() is 20
After calling: total is 10
increment() main() System.out.println("Value returns from
increment() is " + increment(total)); total ( 10)
increment()

sum increment() sum
10 sum 20 main()
20 total

total 10 total
increment() ( sum) total
increment()
//PassByValue2.java
class PassByValue2 {
public static void main(String[] args) {
String myString = "Business Computers";
System.out.println("Before string is: " + myString);
changeString(myString); //calling changeString()
}

System.out.println("After myString is: " + myString);

public static void changeString(String string) {


System.out.print("\tInside changeString(), ");
System.out.println("myString is: " + string);
string = "at Far Eastern College";

5
Java

Objects Classes

143

PassByValue2.java string "Business Computers" string


method changeString() string "at Far
Eastern College" run
Before string is: Business Computers
Inside changeString(), myString is: Business Computers
After myString is: Business Computers
string

changeString()
myString
pass-by-reference
pass-by-reference method
object address
object pass-by-reference
5.6

public static void main(String[] args) {


Circle red = new Circle(5.0);

red
red.change(red, 2.0);
copy red

object
copy
red

red
reference

Circle object
Radius: 5.0

copy made

copy of red
reference

c
copy
red

c.changeRadius(radius)

object
copy red

public Circle change(Circle c, double radius) {

c.changeRadius(radius);
return c;

5.6 pass-by-reference

pass-by-reference 5.6 object class Circle



red radius 5.0 method change() object red
object red radius method change() parameter
Java copy red copy c red c
object object

red copy red ()
method changeRadius() radius code

5
Java

Objects Classes

144

//PassByReference.java
//a Circle class to demonstrate pass-by-reference scheme
class Circle {
private double radius;
//a radius of a circle
//constructor to initialize radius
Circle(double r) {
radius = r;
}
//method to calculate area of a circle
public double area() {
return Math.PI * radius * radius;
}
//a method to change radius of a given circle
public Circle change(Circle c, double radius) {
c.changeRadius(radius); //calling method changeRadius()
return c;
//with a given radius
}
//a method to change a given radius
private void changeRadius(double r) {
radius = r;
}

//a method to return radius


public double getRadius() {
return radius;
}

//a class to test pass-by-reference scheme


class PassByReference {
public static void main(String[] args) {
//create a red circle with a radius of 5.0;
Circle red = new Circle(5.0);
//calculate area of a red circle
double area = red.area();
System.out.println("Radius of red circle is " +
red.getRadius());
System.out.println("Area of red circle is " + area);

//change radius of a red circle


red.change(red, 2.0);
area = red.area();
System.out.println("Radius of red circle now is " +
red.getRadius());
System.out.println("Area of red circle now is " + area);

class class class class Circle class


method

5
Java

Objects Classes

145

class
class object class Circle
pass-by-reference run
Radius of red circle is 5.0
Area of red circle is 78.53981633974483
Radius of red circle now is 2.0
Area of red circle now is 12.566370614359172
radius
radius
method primitive type int
double method method
object method method (
object ) object
method ?

//Swap.java
import java.io.*;
class Values {
int val1;
int val2;
//default constructor
Values() {
val1 = val2 = 0;
}
//assignment constructor
Values(int a, int b) {
val1 = a;
val2 = b;
}

//display val1 and val2


public void show() {
System.out.println("(" + val1 + ", " + val2 + ")");
}

class Swap {
public static void main(String[] args) {
//create two objects from Values
Values obj1 = new Values(10, 20);
Values obj2 = new Values(30, 50);
obj1.show();
obj2.show();

//display values of obj1


//display values of obj2

swap(obj1, obj2); //swap contents of obj1 and obj2


obj1.show();
obj2.show();

5
Java

Objects Classes

146

}
//swapping contents of given objects
private static void swap(Values pointA, Values pointB) {
Values temp = new Values();

temp = pointA;
pointA = pointB;
pointB = temp;

//copy pointA to temp


//copy pointB to pointA
//copy temp to pointB

object swap() 100%


run
(10,
(30,
(10,
(30,

20)
50)
20)
50)

swap() code swap()


code
private static void swap(Values pointA, Values pointB) {
Values temp = new Values();
temp.val1 = pointA.val1;
temp.val2 = pointA.val2;
pointA.val1 = pointB.val1;
pointA.val2 = pointB.val2;

pointB.val1 = temp.val1;
pointB.val2 = temp.val2;

(10,
(30,
(30,
(10,

20)
50)
50)
20)

swap()
object copy object parameter object
swap() object
object swap()

class Student method


method method class Student
object class Student
method
class Student method
//TestStudent.java

5
Java

Objects Classes

147

class TestStudent {
public static void main(String[] args) {
//create two student objects with given info.
Student stu1 = new Student("19757", "Jim", "Jones",
"02/10/1962");
Student stu2 = new Student("20135", "Ray", "Smith",
"12/09/1977");
//display each student's info.
stu1.display();
stu2.display();
//display total number of students
System.out.println("Total number of objects created: " +
stu1.getCount());

//access field in class via object


String date = stu1.dateOfBirth;
System.out.println("Date of birth of stu1 is " + date);

object stu1 stu2 class Student


Student stu1 = new Student("19757", "Jim", "Jones", "02/10/1962")
Student stu2 = new Student("20135", "Ray", "Smith", "12/09/1977")
method display() object
method display() method class Student
public void display() {
System.out.print(getId() + " ");
System.out.print(getFirstName() + " ");
System.out.print(getLastName() + " ");
System.out.println("Age: " + getAge());
return ;
}
method getId() getFirstName() getLastName() method
getAge() System.out.println() method field

object

System.out.println("Total number of objects created: " +
stu1.getCount());
String date = stu1.dateOfBirth;
System.out.println("Date of birth of stu1 is " + date);
object object
stu1
run

19757 Jim Jones Age: 41


20135 Ray Smith Age: 26
Total number of objects created: 2
Date of birth of stu1 is 02/10/1962

5
Java

Objects Classes

148

method class object . (dot)


method

stu1.display();
data member object . (dot)


stu1.dateOfBirth;
method
class

class method getAge() class Student


method getAge()
method class Calendar
public int getAge() {
//retrieve a year
String year = dateOfBirth.substring(6);
//convert it to an int
int birthYear = Integer.parseInt(year);

//get current year from system's calendar


Calendar now = Calendar.getInstance();
int thisYear = now.get(Calendar.YEAR);
//return the difference
return thisYear - birthYear;

field dd/mm/yyyy
method substring() string
int Integer.parseInt()


Calendar now = Calendar.getInstance();
int thisYear = now.get(Calendar.YEAR);
instance class Calendar
method get()

method (
Windows

)
class Student field method
private public
protected
method class class (
private TestStudent.java
method ?)

5
Java

Objects Classes

149

class (attributes)
class Circle radius
private

private double radius;
?
private

class Circle

1.
2.
3.
4.

(friendly)
private (not too friendly)
public (friendly)
protected (somewhat friendly)


class
class package ( package )


//Access.java
class Dot {
//no access control
String name;
int value;

Dot(String s, int v) {
name = s;
value = v;
}

class Access {
public static void main(String[] args) {
Dot myDot = new Dot("I am a dot.", 10);

//access both name and value fields from class Dot


System.out.println("Name is " + myDot.name);
System.out.println("Value is " + myDot.value);

run
Name is I am a dot.
Value is 10
Access.java
field class Dot
object myDot (
?)
private
private String name;

5
Java

Objects Classes

150

private int value;


compile error
Access.java:20: name has private access in Dot
System.out.println("Name is " + myDot.name);
^
Access.java:21: value has private access in Dot
System.out.println("Value is " + myDot.value);
^
2 errors
private
method ( class Dot) class
Circle
radius class Circle private data member
method radius
public double getRadius() {
return radius;
}
(object) private
method changeRadius() class Circle
private
method
method
class method object
Java compiler error
protected
public object method

method


encapsulation
OOP
private method

method
Constructor

Constructor class constructor


constructor object class
object class Circle
Circle red = new Circle(5.0);


execute
Constructor Circle 5.0 radius class Circle
5.0 address object
red constructor class
Circle
System.out.println("Constructor activated with parameter value of " +
radius);

5
Java

Objects Classes

151

constructor class Circle


Circle(double r) {
radius = r;
System.out.println("Constructor activated with value of " +
radius);
}
object class Circle
class PassByReference {
public static void main(String[] args) {
Circle red = new Circle(5.0);
Circle blue = new Circle(3.5);
}
compile run

Constructor activated with value of 5.0


Constructor activated with value of 3.5
object radius 5.0 3.5
method main()
constructor
class Circle

constructor class
Java parameter constructor
parameter parameter (
signature)
//TestMean.java
class Mean {
private double x, y, z;
//constructor with one value
Mean(double value) {
x = value;
y = 0.0;
z = 0.0;
}
//constructor with two values
Mean(double value1, double value2) {
x = value1;
y = value2;
z = 0.0;
}
//constructor with three values
Mean(double value1, double value2, double value3) {
x = value1;
y = value2;
z = value3;
}

5
Java

Objects Classes

152

public double findMean() {


return (x + y + z) / 3;
}

class Mean constructor parameter constructor



parameter constructor
parameter class
method findMean() class
constructor
class TestMean {
public static void main(String[] args) {
//create objects with diferent parameters
Mean m = new Mean(12.0);
Mean n = new Mean(10.0, 20.0);
Mean p = new Mean(10.0, 20.0, 30.0);

System.out.println("Mean of m is " + m.findMean());


System.out.println("Mean of n is " + n.findMean());
System.out.println("Mean of p is " + p.findMean());

TestMean.java object class Mean parameter


method findMean()
object run
Mean of m is 4.0
Mean of n is 10.0
Mean of p is 20.0
Java constructor
constructor overloading overload constructor
parameter
//TestMean1.java
class Mean {
private double x, y, z;
//constructor with three values
Mean(double value1, double value2, double value3 {
x = value1;
y = value2;
z = value3;
}
//constructor with three values (different type)
Mean(double value1, int value2, String value3) {
x = value1;
y = (double)value2;
z = Double.parseDouble(value3);
}

public double findMean() {


return (x + y + z) / 3;
}

5
Java

Objects Classes

153

class Mean constructor parameter


double constructor
parameter double int String
double parameter double constructor
class TestMean1 {
public static void main(String[] args) {
//create objects with diferent parameters
Mean p = new Mean(10.0, 20.0, 30.0);
Mean q = new Mean(10.0, 20, "40.0");

System.out.println("Mean of p is " + p.findMean());


System.out.println("Mean of q is " + q.findMean());

TestMean1.java object p q class Mean


parameter run
Mean of p is 20.0
Mean of q is 23.0333333333333332
constructor Java
overload constructor constructor
constructor
constructor constructor
constructor constructor
Java
constructor constructor this
//TestMean2.java
class Mean {
private double x, y, z;
//constructor with one value
Mean(double value) {
x = value;
y = 0.0;
z = 0.0;
}
//constructor with two values
Mean(double value1, double value2) {
//calling constructor with one argument
this(value1);
y = value2;
}
//constructor with three values
Mean(double value1, double value2, double value3) {
//calling constructor with two arguments
this(value1, value2);
z = value3;
}

5
Java

Objects Classes

154

public double findMean() {


return (x + y + z) / 3;
}

class TestMean2 {
public static void main(String[] args) {
//create objects with diferent parameters
Mean m = new Mean(12.0);
Mean n = new Mean(10.0, 20.0);
Mean p = new Mean(10.0, 20.0, 30.0);

System.out.println("Mean of m is " + m.findMean());


System.out.println("Mean of n is " + n.findMean());
System.out.println("Mean of p is " + p.findMean());


constructor
constructor
Mean(double value) {
x = value;
y = 0.0;
z = 0.0;
}
Mean(double value1, double value2) {
//calling constructor with one argument
this(value1);
y = value2;
}
Mean(double value1, double value2, double value3) {
//calling constructor with two arguments
this(value1, value2);
z = value3;
}
constructor constructor

constructor
class Mean this() constructor
constructor this(value1) Java
constructor
class Java
constructor parameter object execute
constructor x value1 y z 0.0
y value2 constructor
constructor
constructor parameter 2
z
( TestMean2.java )
constructor
code

5
Java

Objects Classes

155

overload method
constructor method overload constructor

overload method
overload method
overload constructor method
method
//Overload.java
class Ball {
private double x, y, z;
//constructor
Ball() {
x = y = z = 0.0;
}

//display coordinates
public void display() {
System.out.println("(" + x + ", " + y + ", " + z + ")");
}

class Overload {
public static void main(String[] args) {
Ball ball = new Ball();
//create object

display(25);
//display int
display(350.0);
//display double
display("I love overloading."); //display string
display('A');
//display char
display(ball);
//display object

//accept int as a parameter


public static void display(int data) {
System.out.println(data);
}
//accept double as a parameter
public static void display(double data) {
System.out.println(data);
}
//accept string as a parameter
public static void display(String data) {
System.out.println(data);
}
//accept char as a parameter
public static void display(char data) {
System.out.println(data);
}
//accept object as a parameter
public static void display(Ball blue) {
blue.display();
//calling display() from class Ball
}

5
Java

Objects Classes

156

}
Overload.java method display() parameter 5
int double string char object overload constructor method
signature java method
run
25
350.0
I love overloading.
A
(0.0, 0.0, 0.0)
overload
method parameter
method Java method
overload
user
method
method

overload method
method overload
class class (nested class)
class class

method class class class
class class Java
class class method
class
//NestedClass.java
class Parent {
private String name;
Child c = new Child("Galvin");

//create a Child object

Parent(String n) {
name = n;
}
public void showName() {
System.out.println("Parent: " + name);
c.showName(); //calling Child's showName()
}
class Child {
private String name;
//create a GrandChild object
GrandChild gc = new GrandChild("Jeff");
Child(String n) {
name = n;
}
public void showName() {
System.out.println("Child: " + name);
gc.showName(); //calling GrandChild's showName()

5
Java

Objects Classes

157

}
class GrandChild {
private String name;
GrandChild(String n) {
name = n;
}
public void showName() {
System.out.println("GrandChild: " + name);
}
}//class GrandChild
}//class Child
}//class Parent
class NestedClass {
public static void main(String[] args) {
Parent p = new Parent("Rebecca");

p.showName();

NestedClass.java object class Parent class


method showName()
Parent: Rebecca
Child: Galvin
GrandChild: Jeff
class Parent class class Child class Child
class class GrandChild class method showName()
class object class Child class
Parent c method showName() class Child method showName()
class Parent object class GrandChild class Child
method showName() class GrandChild method showName() class Child

execute
Parent.showName() Child.showName() GrandChild.showName()

object class object


class NestedClass {
public static void main(String[] args) {
Parent p = new Parent("Rebecca");

p.showName();
Parent.Child newChild = p.new Child("John");
Parent.Child.GrandChild newGrandChild =
newChild.new GrandChild("Jen");
newChild.showName();
newGrandChild.showName();

5
Java

Objects Classes

158

class NestedClass object class

Parent.Child newChild = p.new Child("John");


object class Child object class Parent p.new
Child("John") object class Parent
object class Child class Parent
Parent.Child newChild = Parent.new Child("John");
compile Java error
object class GrandChild class
run
Parent: Rebecca
Child: Galvin
GrandChild: Jeff
Child: John
GrandChild: Jeff
GrandChild: Jen
object class Child class Parent method
showName()
Child: John
GrandChild: Jeff
object class GrandChild method showName()
GrandChild: Jen
nested class
nested
class nested class class
class class
class

object
class method object class


class Array
Java
class MyArray array Object

class MyArray

//MyArray.java
class MyArray {
Object []arr; //array of objects
int maxSize; //maximum size of array
int count;
//number of items in array
//default constructor
MyArray() {

5
Java

Objects Classes

count = 0;
maxSize = 10;
arr = new Object[maxSize];

159

//no item as yet


//default maximum size
//allocate space for arr

//constructor
MyArray(int size) {
count = 0;
//no item as yet
maxSize = size;
//set maximum size
arr = new Object[maxSize];
//allocate space for arr
}
//method to add item into arr
public void add(Object item) {
//expand capacity if arr is full
//double the size
if(count == maxSize) {
//double arr's size
maxSize *= 2;
//create temporary array
Object []temp = new Object[maxSize];
//copy items into new array: temp
System.arraycopy(arr, 0, temp, 0, arr.length);
//refer arr to temp
arr = temp;
}
arr[count++] = item; //add new object into arr
}
//overload method add to accomodate double
public void add(double item) {
add(String.valueOf(item));
}
//overload method add to accomodate int
public void add(int item) {
add(String.valueOf(item));
}

//return formatted output when user uses System.out.println()


//10 items per line
public String toString() {
//create new buffer to hold data
StringBuffer buffer = new StringBuffer();
for(int i = 0; i < maxSize; i++) {
//append newline if this line already has 10 items
if(i % 10 == 0)
buffer.append("\n");
//stop appending when there is no item left (null)
if(arr[i] == null)
break;
//append tab + item in arr
buffer.append("\t" + arr[i]);
}
//returning an output String
return new String(buffer + "\n");
}

5
Java

Objects Classes

160

constructor default constructor


array 10
constructor
array array array dynamic array

array
array method add()
public void add(Object item) {
//expand capacity if arr is full
//double the size
if(count == maxSize) {
//double arr's size
maxSize *= 2;
//create temporary array
Object []temp = new Object[maxSize];
//copy items into new array: temp
System.arraycopy(arr, 0, temp, 0, arr.length);
//refer arr to temp
arr = temp;
}
arr[count++] = item; //add new object into arr
}
method add() count ( array) maxSize
()
array array temp array

maxSize *= 2;
Object []temp = new Object[maxSize];
array array temp
System.arraycopy(arr, 0, temp, 0, arr.length);

arr index = 0 temp index 0


(arr.length) arr
array array arr
arr = temp;
overload method add() double
int array


() array
array
overload method class String String.valueOf()
public void add(double item) {
add(String.valueOf(item));
}
String Object add String array

5
Java

Objects Classes

161

//TestMyArray.java
import java.lang.Integer;
class TestMyArray {
public static void main(String[] args) {
//create array of 10 objects
MyArray array = new MyArray(10);
//add 40 objects into array (randomized)
int count = 0;
while(count < 40) {
int data = (int)(Math.random() * 100 + 1);
array.add(new Integer(data));
++count;
}
System.out.println(array);
//display contents

array.add(45.23);
array.add(88.23);

//add double

array.add(89);
array.add(12);
System.out.println(array);

//add int


9
54
3
1

76
65
91
70

9
76
54 65
3
91
1
70
45.23

20
83
87
27

86
3
72
47

98
36
3
14

12
96
12
51

27
24
7
22

35
63
46
74

41
19
96
95

31
75
11
98

20 86
83 3
87 72
27 47
88.23

98
36
3
14
89

12
96
12
51
12

27
24
7
22

35
63
46
74

41
19
96
95

31
75
11
98

( double
int display )

method toString()

method toString()
System.out.println(array);
System.our.println() String primitive datatype

object class MyArray ?
Object System.out.println() method toString()
Java String primitive datatype Java
method toString() Java method toString() error

method toString()

5
Java

Objects Classes

162

public String toString() {


//create new buffer to hold data
StringBuffer buffer = new StringBuffer();
for(int i = 0; i < maxSize; i++) {
//append newline if this line already has 10 items
if(i % 10 == 0)
buffer.append("\n");
//stop appending when there is no item left (null)
if(arr[i] == null)
break;
//append tab + item in arr
buffer.append("\t" + arr[i]);
}
//returning an output String
return new String(buffer + "\n");
}
method toString() StringBuffer


array (arr[i])
tab (\t)
newline (\n)

buffer method append() 10


append newline buffer array
buffer
null

String ( System.out.println() String)
return new String(buffer + "\n");
System.out.println()

class

array
Java

Package
Package class method class
Java package java.lang java.io class
package class
package
package class package
package
package

package package class
( comment)
//package Shape
package Shape;

5
Java

Objects Classes

163

public class Rectangle {

}
public class method package

class
package class class
package package Sample Sample
class One class Two package Sample oneMore
package oneMore class Three code
//sample package
package Sample;
public class One {
public One() {
System.out.println("This is class One in Sample package.");
}
}
//sample package
package Sample;
public class Two {
public Two() {
System.out.println("This is class Two in Sample package.");
}
}
//sample package
package Sample.oneMore;
public class Three {
public Three() {
System.out.println("This is class Three in Sample.oneMore
package.");
}
}
compile javac -d e:\bc221Book\source
javac -d e:\bc221Book\source One.java
option -d compile Java
class compile class e:\bc221Book\source
One.java Two.java package Sample class
Three.java package Sample.oneMore class
(directory)

5
Java

Objects Classes

164

Package Sample e:\bc221Book\source

Package oneMore e:\bc221Book\source\Sample

Class

5.7 class file compile option -d

package
class import
//test the package
import Sample.One;
import Sample.Two;
import Sample.oneMore.Three;
class TestPackage {
public static void main(String[] args) {
One object1 = new One();
Two object2 = new Two();
Three object3 = new Three();
}
}
compile TestPackage.java
javac -classpath e:\bc221Book\source TestPackage.java
option classpath
class compile
run

This is class One in Sample package.


This is class Two in Sample package.
This is class Three in Sample.oneMore package.
package Java

sub-directory . (dot) (Sample.oneMore)
public class method
class method package
compile option classpath compile
package Java Java

class package
Java class option d compile
classpath compile

5
Java

Objects Classes

165

set classpath=e:\bc221Book\source
classpath compile classpath
autoexec.bat Windows Windows
classpath
environment variables ( path Java ) package
; classpath
set classpath=e:\bc221Book\source; c:\myOthers\Shape

class object method method


constructor
signature parameter
class nested class package

9
9
9
9
9
9
9
9
9

class
class class
class variable static
instance variable object class
method parameter ()
Method static object
class private public protected (

)
class class
package public class method
package

1. class -
object class
2. class
constructor object parameter parameter
method
object

3. class MyArray
object
method object array getCount() method dataAt()


Object obj = arr.dataAt(7);
7 obj
method
4. method parameter
method int double float String "234"
method
5.
overloaded constructor instance
variable class

5
Java

Objects Classes

166

6. class
method

method
7. class dd:mm:yyyy
keyboard Method
12 .. 2546 Monday
12 August 2003
8. class Matrix

9. class user keyboard
dd/mm/yyy

10. class MyString method string


string string string
string

class
class method


class class
class class class
class

o
o
o
o
o

class class (Extended class)


(Inheritance)
polymorphism
abstract class abstract method
interface

class class

code
code
Java class class

( code
)
class class
class class
class class (motor vehicle)
(make) (model) (year) (seats)
method
class MotorVehicle
class
class MotorVehicle
diagram ( class )
MotorVehicle

Car

Compact

Motorcycle

OffRoad

6.1 base-class derived-class

Scooter

Chopper

6
Java

class class

168

class MotorVehicle class parent class ( base class


super class) class class class
MotorVehicle class (children) class class Car class Motorcycle class
class class class Car class Compact
class OffRoad class Motorcycle class Scooter class Chopper class
class
class class MotorVehicle
method class MotorVehicle
//MotorVehicle.java Inheritance
class MotorVehicle {
protected String make;
protected String model;
protected int year;
protected int seats;

//e.g.
//e.g.
//e.g.
//e.g.

Ford, Honda
Taurus, Steed
2001, 2003.
4, 2

//constructor
MotorVehicle(String make, String model, int year, int seats) {
this.make = make;
this.model = model;
this.year = year;
this.seats = seats;
}
public String getMake() {
return make;
}
public String getModel() {
return model;
}
public int getYear() {
return year;
}

public int getSeats() {


return seats;
}

class MotorVehicle protected


class class MotorVehicle class
class constructor
object this class parameter
MotorVehicle(String make, String model, int year, int seats) {
this.make = make;
this.model = model;
this.year = year;
this.seats = seats;
}
this Java object

this.make = make;

6
Java

class class

169

Java constructor Java make parameter


constructor make class copy object

this parameter list


class (
) method
method class

//Car.java - Derived from MotorVehicle


class Car extends MotorVehicle {
protected int doors;
Car(String make, String model, int year, int seats, int doors) {
super(make, model, year, seats);
this.doors = doors;
}
public int getDoors() {
return doors;
}
//display Car's information as string
//using base class methods
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(super.getMake() + ", " +
super.getModel() + ", " +
super.getYear() + ", " + " seating: " +
super.getSeats() + ", " + doors + "doors.");
return new String(buffer);
}
}

class Car class MotorVehicle class Car extends MotorVehicle


Java class
class
class Car
method toString()
object class Car
class
MotorVehicle
super.getMake();
Java Java method getMake() class class
super class method getMake()
class Car

class MotorVehicle class object class


Car TestVehicle.java
//TestVehicle.java
class TestVehicle {
public static void main(String[] args) {
//create two cars, ford and honda

6
Java

class class

170

Car ford = new Car("Ford", "Taurus", 2001, 5, 5);


Car honda = new Car("Honda", "City", 2003, 4, 4);

//display informatin about cars


System.out.println(ford);
System.out.println(honda);

run
Ford, Taurus, 2001, seating: 5, 5 doors.
Honda, City, 2003, seating: 4, 4 doors.
protected
protected class
class class ( method protected )
class private class

method
Car(String make, String model, int year, int seats, int doors) {
super(make, model, year, seats);
this.doors = doors;
System.out.println("base class: " + super.make);
}
class MotorVehicle make private
private String make;

System.out.println("base class: " + super.make);


constructor class Car class MotorVehicle
super.make Java compile
method getMake()
public
class ( class )
private class
method base class protected
protected class package
method class

class class
class MotorVehicle {
private String make;
private String model;
private int year;
private int seats;

//e.g.
//e.g.
//e.g.
//e.g.

Ford, Honda
Taurus, Steed
2001, 2003
4, 2

//constructor
MotorVehicle(String make, String model, int year, int seats) {
this.make = make;
this.model = model;
this.year = year;

6
Java

class class

171

this.seats = seats;

protected String getMake() {


return make;
}
protected String getModel() {
return model;
}
protected int getYear() {
return year;
}

protected int getSeats() {


return seats;
}

class Car extends MotorVehicle {


private int doors;
Car(String make, String model, int year, int seats, int doors) {
super(make, model, year, seats);
this.doors = doors;
}
protected int getDoors() {
return doors;
}

public String toString() {


StringBuffer buffer = new StringBuffer();
buffer.append(super.getMake() + ", " +
super.getModel() + ", " +
super.getYear() + ", " + "seating: " +
super.getSeats() + ", " + doors + " doors.");
return new String(buffer);
}

method toString() protected


Java method toString() public
override
override
class Compact class class Compact class
class Car
//Compact.java Derived from Car
class Compact extends Car {
//constructor -using base class (Car) constructor
Compact(String make, String model, int year,
int seats, int doors) {
super(make, model, year, seats, doors);

6
Java

class class

172

}
//override Car's toString() method
//presenting Comapct car's details as string
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("Compact car: ");
buffer.append(super.toString());

return new String(buffer);

class Compact class


constructor
class Car ( constructor class Car constructor class MotorVehicle)
method toString() class Car "Compact car: "
method append() class StringBuffer
buffer.append("Compact car: ");
buffer.append(super.toString());
run
Compact honda = new Compact("Honda", "City", 2003, 4, 4);
System.out.println(honda);

Compact car: Honda, City, 2003, seating: 4, 4 doors.
run ( object class Car)
method overriding object class
Compact override ( overload overload method
class method
parameter list ) method class
base class
code
override method method class
method class

override method class


object class
derived class method
override Java method
class method class
class Compact override
method override method
toString()
Method
override class

method class public


class

private private
class private

public
class
class
diagram

6
Java

class class

173

Shapes

Polygons

Triangle

Rectangle

Circle

Square

6.2 class shape

diagram Shapes base class


Polygons Circle class Shapes Triangle Rectangle Square
class Polygons
class method what() method
code
//Shapes.java - Base class for all shapes
class Shapes {
//self info.
protected String what() {
return "I am a shape";
}
//Polygons.java Polygon
class Polygons extends Shapes {
//self info.
protected String what() {
return "I am a polygon.";
}
}
//Circle.java - sub-class of Shapes
class Circle extends Shapes {
//self info
protected String what() {
return "I am a circle.";
}
}
//Triangle.java - sub-class of Polygons
class Triangle extends Polygons {
//self info.
protected String what() {
return "I am a triangle.";
}
}
//Square.java - sub-class of Polygons

6
Java

class class

174

class Square extends Polygons {


//self info.
protected String what() {
return "I am a square.";
}
}
//Rectangle.java - sub-class of Polygons
class Rectangle extends Polygons {
//self info.
protected String what() {
return "I am a rectangle.";
}
}

//TestShapes.java - driver program


class TestShapes {
public static void main(String[] args) {
//creating different shape objects from Shapes
Shapes shape = new Shapes();
Shapes poly = new Polygons();
Shapes sq = new Square();
Shapes cir = new Circle();

//display info. about particular shapes


System.out.println(shape.what());
System.out.println(sq.what());
System.out.println(cir.what());
System.out.println(poly.what());

object class Shapes


constructor class
Shapes sq = new Square();
sq
object
Shapes constructor Square Java
object Square class class Shapes ( Circle
Shapes ) class Shapes method what() class
method class method what()
method what() method
class (overriding)

I
I
I
I

am
am
am
am

a
a
a
a

shape
square.
circle.
polygon.

6
Java

class class

175

Polymorphism (

)
late binding
polymorphism
object
late binding compiler
execute (run ) compile
Polymorphism method class
object class
method object

class Shapes method class ( class )
object

shape shape
Java (declare) method class
(define) class abstract class
Abstract class class
method class
class
//Shapes.java - Base class for all shapes
public abstract class Shapes {
private String iAm;
Shapes(String whatIam) {
iAm = new String(whatIam);
}
//self info.
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("I am a " + iAm);
return new String(buffer);
}

//dummy method - implementation is done in derived classes


//to calculate a perimeter of a shape
public abstract double perimeter();

class Shapes abstract class method perimeter()


code class
class
Shapes
//Polygons.java Polygon
public abstract class Polygons extends Shapes {
//constructor
Polygons(String type) {
super(type);
}
//self info.
public String toString() {
return super.toString();

6
Java

class class

176

//dummy method to be implemented by derived classes


public abstract double perimeter();

//Triangle.java - sub-class of Polygons


public class Triangle extends Polygons {
private double side1, side2, side3;
//constructor
Triangle(String type, double side1, double side2, double side3) {
super(type);
//calling base-class constructor
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}
//self info.
public String toString() {
return super.toString();
}

//calculating a perimeter of this triangle


public double perimeter() {
return side1 + side2+ side3;
}

//Circle.java - sub-class of Shapes


public class Circle extends Shapes {
private double radius;
//constructor
Circle(String type, double radius) {
super(type);
this.radius = radius;
}
//self info
public String toString() {
return super.toString();
}

//calculating a perimeter of this circle


public double perimeter() {
return 2.0 * Math.PI * radius;
}

//Square.java - sub-class of Polygons


public class Square extends Polygons {
double side;
//constructor

6
Java

class class

177

Square(String type, double side) {


super(type);
this.side = side;
}
//self info.
public String toString() {
return super.toString();
}

//calculating a perimeter of this square


public double perimeter() {
return side * 4;
}

class Polygons class Circle class Triangle class Square


method perimeter() class Circle class Triangle class Square
method

//TestShapes.java - driver program
class TestShapes {
public static void main(String[] args) {
Shapes cir, tri;
Polygons sq;
//instantiate shapes
sq = new Square("square", 4.0);
cir = new Circle("circle", 2.0);
tri = new Triangle("triangle", 3.0, 4.0, 5.0);

//display info. about particular shapes


System.out.println(sq + " with a perimeter of: " +
sq.perimeter());
System.out.println(cir + " with a perimeter of: " +
cir.perimeter());
System.out.println(tri + " with a perimeter of: " +
tri.perimeter());

TestShapes.java cir tri class Shapes sq class


Polygons object Java
class Shapes class Polygons class abstract class
object (instantiation) class Circle class Square
class Triangle
object
sq = new Square("square", 4.0);
cir = new Circle("circle", 2.0);
tri = new Triangle("triangle", 3.0, 4.0, 5.0);
object class Shapes
base class class class Polygons base class class Square class

6
Java

class class

178

Triangle object sq cir tri


shape (e.g. a square is a shape, a circle is a shape, a triangle is a shape etc.)
run
I am a square with a perimeter of: 16.0
I am a circle with a perimeter of: 12.566370614359172
I am a triangle with a perimeter of: 12.0
Polymorphism method object
object class

array shape


//TestShapes.java - driver program
class TestShapes {
public static void main(String[] args) {
Shapes []shapes = new Shapes[5];
//instantiate 5 shapes
for(int i = 0; i < 5; i++)
shapes[i] = randomShape();
//display info. about particular shapes
for(int i = 0; i < 5; i++) {
System.out.print(shapes[i] + " with a perimeter of: ");
System.out.println(shapes[i].perimeter());
}

public static Shapes randomShape() {


switch((int)(Math.random() * 3)) {
default:
case 0: return new Circle("circle", Math.random() * 12.0);
case 1: return new Square("square", Math.random() * 10.5);
case 2: return new Triangle("triangle", 2.5, 4.0, 5.5);
}
}

random method randomShape()


method
random() class Math
run
I
I
I
I
I

am
am
am
am
am

a
a
a
a
a

square with a
triangle with
circle with a
triangle with
circle with a

perimeter of: 15.282560130191253


a perimeter of: 12.0
perimeter of: 0.209235603993188
a perimeter of: 12.0
perimeter of: 7.8292546239806695

object
class method
getClass() method getName() class Class Java object
shapes[0] class

6
Java

class class

179

Class object = shapes[0].getClass();


System.out.println(object.getName());
object class method getSuperclass()
Class shape = object.getSuperclass();
System.out.println(shape.getName());
method class Class
method method
class ( Java)
object
object method object
method

//SquareToCircle.java - Passing and returning object to/from method
class SquareToCircle {
public static void main(String []args) {
Shapes square; //a square object
Shapes circle; //a circle object
//creating a square with side = 3
square = new Square("square", 3.0);
System.out.println(square + " with an area of " +
square.area());

//creating a circle from a square


circle = SqToCir(square);
System.out.println(circle + " with an area of " +
circle.area());

//method to convert a square to a circle


public static Shapes SqToCir(Shapes square) {
//finding a radius from an area of a square
double SqArea = square.area();
double radius = Math.sqrt(SqArea / Math.PI);
//instantiating a circle
Circle circle = new Circle("circle", radius);

return circle;

abstract method area() class Shapes


class Polygons method area() class Square class Circle

class Shapes ( class Polygons )


public abstract class Shapes {

6
Java

class class

180

//code

public abstract double perimeter();


public abstract double area();

class Circle code method area()


//calculate area of this circle
public double area() {
return Math.PI * radius * radius;
}
class Square code method area()
//calculate area of this square
public double area() {
return side * side;
}
object square circle square
3.0 square square
method SqToCir() method square circle
object
public static Shapes SqToCir(Shapes square) {
//finding a radius from an area of a square
double SqArea = square.area();
double radius = Math.sqrt(SqArea / Math.PI);
//instantiating a circle
Circle circle = new Circle("circle", radius);
}

return circle;

square

circle
run
I am a square with an area of 9.0
I am a circle with an area of 9.0
base class abstract class
method
class method method perimeter()
method area() shape object
Circle Square

object class

6
Java

class class

181

Interface
polymorphism method class
method class class
polymorphism class class

class interface
Interface abstract method class
interface interface class interface
class

class
class Shapes class Polygons abstract method perimeter() area()
class Shapes
public abstract class Shapes implements Calculate {
private String iAm;
Shapes(String whatIam) {
iAm = new String(whatIam);
}

//self info.
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("I am a " + iAm);
return new String(buffer);
}

implements Calculate
class Shapes
interface Calculate interface Calculate
interface method

class
//interface for Shapes
public interface Calculate {
double perimeter();
double area();
}
Method interface
class (implement) interface
class
class Triangle method
//calculating an area of this triangle
//using Huron's formula
public double area() {
double s = perimeter() / 2.0;
double area = Math.sqrt((s * (s-side1) * (s-side2) * (s-side3)));
}

return area;

6
Java

class class

182

class Circle method


//calculate area of this circle
public double area() {
return Math.PI * radius * radius;
}
class Square method
//calculate area of this square
public double area() {
return side * side;
}

code
//TestShapes.java - driver program
import java.text.DecimalFormat;
class TestShapes {
public static void main(String[] args) {
Shapes []shapes = new Shapes[5];
//instantiate 5 shapes
for(int i = 0; i < 5; i++)
shapes[i] = randomShape();
//display info. about particular shapes
DecimalFormat f = new DecimalFormat("0.00");
for(int i = 0; i < 5; i++) {
System.out.print(shapes[i] + " perimeter = ");
System.out.print(f.format(shapes[i].perimeter()));
System.out.println(" area = " +
f.format(shapes[i].area()));
}

public static Shapes randomShape() {


switch((int)(Math.random() * 3)) {
default:
case 0: return new Circle("circle", Math.random() * 12.0);
case 1: return new Square("square", Math.random() * 10.0);
case 2: return new Triangle("triangle", 4.0, 5.0, 6.0);
}
}

I
I
I
I
I

am
am
am
am
am

a
a
a
a
a

triangle perimeter
square perimeter =
circle perimeter =
triangle perimeter
circle perimeter =

= 15.0 area = 9.90


10.32 area = 6066
45.32 area = 163.46
= 15.00 area = 9.92
6.76 area = 3.64

6
Java

class class

183

interface Calculate class


interface Calculate class class class
class Shapes implements Calculate

code
interface Java interface
ActionListener

interface
Interests.java
class
class Account balance class interface BankRate
class Timer class Java
class Interests1
interface BankRate RATE
interface ActionListener
class diagram
Account

GetInterest

BankRate

ActionListener

interface

Timer

6.2 interface

interface BankRate class Account


//interface for bank rate
public interface BankRate {
double RATE = 5.0;
}
//Account.java
public class Account implements BankRate {
private double balance;
//constructor - initializing balance
Account(double balance) {
this.balance = balance;
}
//method to get balance
protected double getBalance() {
return balance;
}
//method to deposit

6
Java

class class

184

protected void deposit(double amount) {


balance += amount;
}
//method to calculate interest
protected double interest() {
return balance * RATE / 100.0;
}

//method to display info. about this account


public String toString() {
return "Balance = " + getBalance();
}

class Account method balance


method toString() class Interests1
class interface
//Interests1.java
import
import
import
import

java.awt.event.ActionEvent;
java.awt.event.ActionListener;
javax.swing.JOptionPane;
javax.swing.Timer;

class Interests1 {
public static void main(String[] args) {
//create account with initial balance of 1000
final Account acc = new Account(1000);
//inner class performing interest calculation
//and listening to event from user
//stop performing when user hit stop button in
//the dialog window
class GetInterest implements ActionListener {
public void actionPerformed(ActionEvent event) {
double ints = acc.interest();
acc.deposit(ints);
System.out.println(acc);
}
}
//create object from class GetInterest
GetInterest intsPeek = new GetInterest();
//set performing time interval to one second
final int DELAY = 1000;
//calling actionPerformed() every 1000 milliseconds
Timer t = new Timer(DELAY, intsPeek);
//start the timer
t.start();

//display dialog window - stop performing and exit


//program when user hit the button
JOptionPane.showMessageDialog(null, "Stop?");
System.exit(0);

6
Java

class class

185

Interests1.java object acc class Account balance 1000


method main() class GetInterest interface ActionListener Java
(event) user
method actionPerformed() object intsPeek class Timer delay 1

Timer t = new Timer(DELAY, intsPeek);

method start() class Timer t.start()


user OK dialog window
dialog window
JOptionPane.showMessageDialog(null, "Stop?");

user
OK System.exit(0);
run
Balance
Balance
Balance
Balance
Balance
Balance
Balance
Balance
Balance
Balance
Balance
Balance
Balance
Balance

=
=
=
=
=
=
=
=
=
=
=
=
=
=

1050.0
1102.5
1157.625
1215.50625
1276.2815624999998
1340.0956406249998
1407.1004226562497
1477.4554437890622
1551.3282159785153
1628.894626777441
1710.3393581163132
1795.8563260221288
1885.649142323235
1979.931599439397

interface Java
Java

method
1. class abstract class method

method class

6
Java

class class

186

2. class interface method class


method

class class class class


override method polymorphism interface

9
9
9
9
9
9

class class
extends class
extends base class parent class sub
class child
abstract class abstract class abstract class
method method class
object abstract class
sub class constructor super class
method private class class
method
class object class
method class
abstract class class method class
interface abstract method inner class
class method interface
abstract class

1. super class
sub class

2. class RumRaisin extends class Icecream


Java
RumRaisin scoop1 = new RumRaisin();
Icecream scoop2 = new Icecream;
scoop2 = scoop1;
scoop1 = scoop2;
scoop2 = new RumRaisin();
scoop1 = new Icecream();
3. diagram class

6
Java

class class

187

4. method clone() array override method clone()


object class Shapes
5. method withdraw() class Account

6. class Shapes class class
Rectangle code class Rectangle
7. class Student sub class

method method toString() class
object class
8. class Employee sub class TempEmployee RegularEmployee

method
TempEmployee

40

(RegularEmployee)

polymorphism

* class Employee abstract class
9. class Shapes sub class
Shapes method object
class object class
object Circle
Square

exception error
compile run

o
o
o
o

exception
exception
throws try
exception

Java exception error




array index
null

error if-else
code error
code error
exception
code code error
code
code
exception
error
error code
compile

exception error
exception
exception exception
user
exception

exception Java (throw) error
code error code
(catch) code error

error exception exception
error
Java
web sit Java
Exception object sub class (class class ) class Throwable
Java class class class Throwable class
class class error class Error class Exception ( 7.1)

7
Java

error (Exceptions)

189

Throwable

Error

Other sub classes

Exception

Other sub classes

7.1 Class Throwable sub classes

Java
catch error class Error
error error () class
ThreadDeath LinkageError VirtualMachineError class
error
error ( error )
exception error

//ThrowException.java
class ThrowException {
public static void main(String[] args) throws Exception {
int number = 10;
int divider = 0;

System.out.println("Divide " + number + " by " + divider);


int result = number / divider;
System.out.println("Result is " + result);

throw exception exception


( int 0 error )
error

run
Divide 10 by 0
java.lang.ArithmeticException: / by zero
at ThrowException.main(ThrowException.java:10)
Java error error (ArithmeticException)
int 0

error try
catch

7
Java

error (Exceptions)

190

//TryAndCatchExample1.java
//adopted from Ivor Horton's
class TryAndCatchExample1{
public static void main(String[] args) {
int number1 = 15;
int number2 = 0;
try {
System.out.println("Try to divide by zero in
a try block.");
int result = number1 / number2;
System.out.println("Leaving a try block.");
}
catch(ArithmeticException ex) {
System.out.println("Exception caught in a catch block.");
}

System.out.println("After a try block.");

TryAndCatchExample1.java try catch


int 0 ( throws exception ) number1
15 number2 0
result = number1 / number2;
block try exception block catch
block catch exception ArithmaticException
error run
Try to divide by zero in a try block.
Exception caught in a catch block.
After a try block.
code

block try 2
block catch
block catch

block catch
ex parameter list method catch()
error
block catch
System.out.println(ex.getMessage());
ex.printStackTrace();
method getMessage()

error run
code block catch
Try to divide by zero in a try block.
Exception caught in a catch block.
/ by zero
java.lang.ArithmeticException: / by zero

7
Java

error (Exceptions)

191

at TryAndCatchExample1.main(TryAndCatchExample1.java:11)
After a try block.


error
error

Java try catch


block
block try catch
compile
block

System.out.println("Leaving a try block.");

}
System.out.pritnln("In between try and catch blocks.");
catch(ArithmeticException ex) {

compile error
TryAndCatchExample1.java:9: 'try' without 'catch' or 'finally'
try {
^
TryAndCatchExample1.java:15: 'catch' without 'try'
catch(ArithmeticException ex) {
^
2 errors
try catch classic try catch loop

//TryAndCatchExample2.java
//adopted from Ivor Horton's
class TryAndCatchExample2 {
public static void main(String[] args) {
int number = 10;
for(int index = 5; index >= -1; index--)
try {
System.out.println("try block: index = " + index);
int result = number / index;
System.out.println("Leaving a try block.");
}
catch(ArithmeticException e) {
System.out.println("Exception caught in
a catch block.");
System.out.println(e.getMessage());
e.printStackTrace();
}

System.out.println("After a try and catch blocks.");

7
Java

error (Exceptions)

192

run
try block: index = 5
Leaving a try block.
try block: index = 4
Leaving a try block.
try block: index = 3
Leaving a try block.
try block: index = 2
Leaving a try block.
try block: index = 1
Leaving a try block.
try block: index = 0
Exception caught in a catch block.
/ by zero
java.lang.ArithmeticException: / by zero
at TryAndCatchExample2.main(TryAndCatchExample2.java:11)
try block: index = -1
Leaving a try block.
After a try and catch blocks.
block try index 0
block catch
block try

error (terminate)
code error

code (resumption)
error

class
NumberFormatException error
//NumFormatException.java
import java.lang.Integer;
class NumFormatException {
public static void main(String[] args) {
int inputNum, sum = 0;

//reading input from argument list


//only those in [0..9]
for(int i = 0; i < args.length; i++) {
try {
inputNum = Integer.parseInt(args[i]);
sum += inputNum;
}
//ignore input that's not a number
catch(NumberFormatException e) {
e.printStackTrace(System.out);
}
}
System.out.println("Sum is " + sum);

command line argument



( run)

7
Java

error (Exceptions)

193

<enter> catch block


NumberFormatException int

>java NumFormatException 1 2 3 4 p 5 6
java.lang.NumberFormatException: For input string: "p"
at
java.lang.NumberFormatException.forInputString(NumberFormatException.
java:48)
at java.lang.Integer.parseInt(Integer.java:426)
at java.lang.Integer.parseInt(Integer.java:476)
at NumFormatException.main(NumFormatException.java:12)
Sum is 21
block catch error catch block block
catch block catch exception sub class
super class
block
try {

}
catch(Exception e) {

}
catch(ArithmeticException ex) {

..
}
class ArithmeticException class class Exception
error
catch block catch block

error
//MultipleCatches.java
class MultipleCatches {
public static void main(String[] args) {
//force divide by zero at index = 2
int []number = {1, 2, 0, 4};
int num = 12;
//force array index out of bound at index = 4
for(int i = 0; i < number.length + 1; i++) {
try {
num /= number[i];
System.out.println("result = " + num);
}
catch(ArithmeticException e) {
System.out.println("error message: " +
e.getMessage());
e.printStackTrace();
}
catch(ArrayIndexOutOfBoundsException e) {

7
Java

error (Exceptions)

194

System.out.println("error message: " +


e.getMessage());
e.printStackTrace();

}
}
System.out.println("After a for loop.");

error index array


index = 2 for loop run

result = 12
result = 6
error message: / by zero
java.lang.ArithmeticException: / by zero
at MultipleCatches.main(MultipleCatches.java:11)
result = 1
error message: 4
java.lang.ArrayIndexOutOfBoundsException: 4
at MultipleCatches.main(MultipleCatches.java:11)
After a for loop.
error index
array

error
Java block block catch error block catch
block finally
Finally error finally block
catch block finally block

}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("error message: " + e.getMessage());
e.printStackTrace();
}
finally {
System.out.println("In finally block.");
}

finally block block

7
Java

error (Exceptions)

195

at MultipleCatches.main(MultipleCatches.java:13)
In finally block.
After a for loop.
finally code (
) method main()

//ThrowsWithTry.java
import java.io.*;
import java.lang.Integer;
class ThrowsWithTry {
public static void main(String[] args) throws IOException {
BufferedReader buffer;
InputStreamReader isr;
String input;
int first, divider;
//keep looping until error occur
while(true) {
System.out.print("Enter a number: ");
isr = new InputStreamReader(System.in);
buffer = new BufferedReader(isr);
//get first number
input = buffer.readLine();
first = Integer.parseInt(input);
//get second number
System.out.print("Enter a divider: ");
input = buffer.readLine();
divider = Integer.parseInt(input);

try {
double result = first / divider;
System.out.println("Result = " + result);
}
catch(ArithmeticException e) {
System.out.println("Exception: " + e.getMessage());
e.printStackTrace();
}

ThrowsWithTry.java throws try catch

keyboard int


run
Enter a number: 23
Enter a divider: 5
Result = 4.0
Enter a number: 56

7
Java

error (Exceptions)

196

Enter a divider: 0
Exception: / by zero
java.lang.ArithmeticException: / by zero
at ThrowsWithTry.main(ThrowsWithTry.java:27)
Enter a number: 12
Enter a divider: 3
Result = 4.0
Enter a number: pop
Exception in thread "main" java.lang.NumberFormatException: For input
string: "pop"
at
java.lang.NumberFormatException.forInputString(NumberFormatException.
java:48)
at java.lang.Integer.parseInt(Integer.java:426)
at java.lang.Integer.parseInt(Integer.java:476)
at ThrowsWithTry.main(ThrowsWithTry.java:20)
int (

"pop")

code
//ThrowsWithTry1.java
import java.io.*;
import java.lang.Integer;
class ThrowsWithTry1 {
public static void main(String[] args) throws IOException {
BufferedReader buffer;
InputStreamReader isr;
String input;
int first = 0, divider = 0;
while(true) {
System.out.print("Enter a number: ");
isr = new InputStreamReader(System.in);
buffer = new BufferedReader(isr);
//get first number
input = buffer.readLine();
first = readInt(input);
//get second number only if first number is valid
if(first != -1) {
System.out.print("Enter a divider: ");
input = buffer.readLine();
divider = readInt(input);
}
//perform division if both numbers are valid
if(first != -1 && divider != -1) {
try {
double result = first / divider;
System.out.println("Result = " + result);
}
catch(ArithmeticException e) {
System.out.println("Exception: " + e.getMessage());

7
Java

error (Exceptions)

197

e.printStackTrace();

//method to convert an int from a string


public static int readInt(String in) throws IOException {
try {
int num = Integer.parseInt(in);
return num;
}
catch(NumberFormatException e) {
System.out.println("Exception caught: " + e.getMessage());
return -1;
}
}

method readInt() string buffer int try


catch error
-1 code while loop

code while loop

//get second number only if first number is valid
if(first != -1) {
System.out.print("Enter a divider: ");
input = buffer.readLine();
divider = readInt(input);
}
//perform division if both numbers are valid
if(first != -1 && divider != -1) {
try {
double result = first / divider;
System.out.println("Result = " + result);
}
catch(ArithmeticException e) {
System.out.println("Exception: " + e.getMessage());
e.printStackTrace();
}
}

first divider
-1

Enter a number: 23
Enter a divider: 3
Result = 7.0
Enter a number: p
Exception caught: For input string: "p"
Enter a number: 3
Enter a divider: p
Exception caught: For input string: "p"
Enter a number: 32
Enter a divider: 0

7
Java

error (Exceptions)

198

Exception: / by zero
java.lang.ArithmeticException: / by zero
at ThrowsWithTry1.main(ThrowsWithTry.java:34)
Enter a number: -1
Enter a number: Exception caught: null
Enter a number:


-1 ?
<crtl> + c


error

exception
Java exception
error

//TestInputValidation.java
import java.io.*;
import java.lang.Integer;
class TestInputValidation {
public static void main(String[] args) throws Exception {
BufferedReader buffer;
InputStreamReader isr;
String input;
int first, divider;
while(true) {
//get first number
first = readInt();
//get second number only if first number is valid
divider = readInt();

//perform division if both numbers are valid


try {
//calling method divide()
int result = divide(first,divider);
System.out.println("Result = " + result);
}
//catching user defined exception
catch(ZeroDivideException e) {
e.printStackTrace(System.err);
}

//method to get an int from the keyboard

7
Java

error (Exceptions)

199

public static int readInt() throws Exception {


BufferedReader buffer;
InputStreamReader isr;
String input = null;
int result = 0;
boolean ok = false;

isr = new InputStreamReader(System.in);


buffer = new BufferedReader(isr);
//keep looping until user enter an int
while(!ok) {
System.out.print("Enter a number: ");
try {
input = buffer.readLine();
result = Integer.parseInt(input);
ok = true;
}
catch(NumberFormatException e) {
System.out.println(e.getMessage());
e.printStackTrace(System.err);
}
}
return result;

//method to divide first number by the second number


public static int divide(int first, int second)
throws ZeroDivideException {
int result;
try {
result = first / second;
}
catch(ArithmeticException e) {
throw new ZeroDivideException(); //throw new exception
}
return result;
}
}


exception method readInt()

Method

method divide()
parameter 2

method divide() error



ArithmeticException throw exception
catch(ArithmeticException e) {
throw new ZeroDivideException(); //throw new exception
}
exception code exception
class ZeroDivideException class Exception
class Exception code
class ZeroDivideException
//ZeroDivideException.java

7
Java

error (Exceptions)

200

class ZeroDivideException extends Exception {


//default constructor
ZeroDivideException() {
super("divide by zero"); //call super class' constructor
}

ZeroDivideException(String message) {
super(message);
}

constructor class Exception


error
(divide by zero)
method main() code

try {
//calling method divide()
int result = divide(first,divider);
System.out.println("Result = " + result);
}
//catching user defined exception
catch(ZeroDivideException e) {
e.printStackTrace(System.err);
}
method divide() try error catch block
object class ZeroDivideException run

Enter a number: 45
Enter a number: 36
Result = 1
Enter a number: 0
Enter a number: 3
Result = 0
Enter a number: pop
For input string: "pop"
java.lang.NumberFormatException: For input string: "pop"
at
java.lang.NumberFormatException.forInputString(NumberFormatException.
java:48)
at java.lang.Integer.parseInt(Integer.java:426)
at java.lang.Integer.parseInt(Integer.java:476)
at TestInputValidation.readInt(TestInputValidation.java:47)
at TestInputValidation.main(TestInputValidation.java:16)
Enter a number: 3
Enter a number: 0
ZeroDivideException: divide by zero
at TestInputValidation.divide(TestInputValidation.java:64)
at TestInputValidation.main(TestInputValidation.java:23)
Enter a number: null ( <crtl> + c )
java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:394)
at java.lang.Integer.parseInt(Integer.java:476)

7
Java

error (Exceptions)

201

at TestInputValidation.readInt(TestInputValidation.java:47)
at TestInputValidation.main(TestInputValidation.java:16)
Enter a number:
error
loop method main() loop <crtl> + c
error

error
System.err Java


error

//CheckRange.java
import java.lang.Integer;
class CheckRange {
public static void main(String[] args) {
try {
//getting input from argument list
int first = Integer.parseInt(args[0]);
int second = Integer.parseInt(args[1]);
int third = Integer.parseInt(args[2]);
//check if the third input is between first and second
checked(first, second, third);
System.out.println("Number " + third +
" is in the given range");

}
catch(OutOfRangeException e) {
e.printStackTrace(System.err);
}

//method to validate range


public static void checked(int start, int stop, int num) throws
OutOfRangeException {
if(num < start) {
String errMsg = new String(num + " < " + start);
throw new OutOfRangeException(errMsg, start, stop);
}
if(num > stop) {
String errMsg = new String(num + " > " + stop);
throw new OutOfRangeException(errMsg, start, stop);
}
}

argument list


throw exception
OutOfRangeException
//OutOfRangeException.java

7
Java

error (Exceptions)

202

public class OutOfRangeException extends Exception {


//default constructor
OutOfRangeException() {}
//constructor
OutOfRangeException(String message, int p, int q) {
super(message);
}

super class constructor


code
error
run
>java CheckRange 12 45 569
OutOfRangeException: 569 > 45
at CheckRange.checked(CheckRange.java:31)
at CheckRange.main(CheckRange.java:15);
E:\bc221Book\source>java CheckRange 12 45 2
OutOfRangeException: 2 < 12
at CheckRange.checked(CheckRange.java:27)
at CheckRange.main(CheckRange.java:15)
E:\bc221Book\source>java CheckRange 12 45 15
Number 15 is in the given range

error
error
error error
error run error
Index array

Exception Java


exception Java
exception
error exception error

error

9
9
9
9
9
9

Exception
error
Exception object class Throwable

exception Java
exception method code try block
try block block block
Code exception catch block try block
try block catch block
Finally block try finally block

7
Java

error (Exceptions)

203

1. keyboard int exception


error


2.
3. keyboard

Celsius
(step)
Fahrenheit


>java Temperature 0 100 10
CELSIUS
0
10
20
30
40
50
60
70
80
90
100

FAHRENHEIT
32.0
50.0
68.0
86.0
104.0
122.0
140.0
158.0
176.0
194.0
212.0

error

(negative number)
error
>java Temperature 0 100 -5
3rd arg < 0 NUMBER = -5
>java Temperature 40 20 5
Ordering Err FIRST = 40 SECOND = 20
>java Temperature 10 40
java.lang.ArrayIndexOutOfBoundsException:
at Temperature.main(Temperature.java:41)
4.
mn m n command line argument
list error
5. class Account
error

method

6. error

stream



o
o
o
o
o

stream
Class Java stream
directory
file file file
text file binary file

Java stream
(input) (output) stream
keyboard 10 byte
keyboard (disk)
scanner light-pen memory-card keyboard disk

(monitor) (printer)
Java
binary streams character streams
stream byte
byte binary data (
) stream
memory memory
streams
memory
character streams (text)
character streams text Java
character streams

17
character stream ASCII '1' '7' 0x310x37 ( 16)
727 stream 0x310x370x370x320x37

Java Unicode stream


character () (local code)
code
(Java localization) Java

local code Unicode Java
Unicode

8
Java

Streams I/O

205



input output
FileInfo.java
//FileInfo.java
import java.io.*;
class FileInfo {
public static void main(String[] args) {
//get path from command-line argument
File path = new File(args[0]);

//display some info. about this file


if(path.exists()) {
System.out.println(path + " does exist.");
System.out.println("Readable
: " +
statusOk(path.canRead()));
System.out.println("Writable
: " +
statusOk(path.canWrite()));
System.out.println("Directory? : " +
statusOk(path.isDirectory()));
System.out.println("File?
: " +
statusOk(path.isFile()));
System.out.println("Hidden?
: " +
statusOk(path.isHidden()));
}
else {
System.out.println(path + " does not exist.");
}

//return "Yes" or "No"


public static String statusOk(boolean yes) {
return yes ? "Yes" : "No";
}

object path class File command-line


argument
e:\bc221Book\source
e:\bc221Book\source
\source
\bc221Book\source\FileInfo.java
absolute path
relative path
absolute path drive relative path
drive directory run

>java FileInfo \bc221Book


\bc221Book does exist.
Readable
: Yes
Writable
: Yes

8
Java

Directory?
File?
Hidden?

Streams I/O

206

: Yes
: No
: No

>java FileInfo \bc221Book\source\FileInfo.java


\bc221Book\source\FileInfo.java does exist.
Readable
: Yes
Writable
: Yes
Directory?
: No
File?
: Yes
Hidden?
: No
>java FileInfo \bc221Book\FileInfo.java
\bc221Book\FileInfo.java does not exist.
run relative path directory file
absolute path
E:\bc221Book\source>java FileInfo e:\bc221Book\source\FileInfo.java
e:\bc221Book\source\FileInfo.java does exist.
Readable
: Yes
Writable
: Yes
Directory?
: No
File?
: Yes
Hidden?
: No
method class File file file
file Java file ( )
file file directory ( folder)
Java method file method

//FileInfo1.java
import java.io.*;
import java.util.Date;
class FileInfo1 {
public static void main(String[] args) {
//explain how to use if no argument is given
if(args.length < 1) {
System.out.println("Usage: FileInfo1 file-name");
System.exit(1);
}
//display information about this file
echoFileInfo(new File(args[0]));
}
private static void echoFileInfo(File file) {
//display if file is a file or a directory
if(file.isFile())
System.out.println("\n" + file + " is a file.");
if(file.isDirectory()) {
String []list = file.list();
System.out.println("\n" + file + " is a directory.");
System.out.println("There are " + list.length +
" items in this directory.");

8
Java

Streams I/O

207

}
//lastModifeid() returns amount of milliseconds the file
//was last modified, e.g. 1045375241775 since
//January 1, 1970, 00:00:00 GMT. We have to create a date
//object from this data.
long lastModified = file.lastModified();
Date dateModified = new Date(lastModified);
//display information about this file
System.out.println(
"Absolute path: " + file.getAbsolutePath() +
"\n Name: " + file.getName() +
"\n Parent: " + file.getParent() +
"\n Path: " + file.getPath() +
"\n Length: " + file.length() +
"\n Last modified: " + dateModified);

FileInfo1.java method 5 (
command-line argument) method
method method lastModified()
lastModified() long

millisecond 1045375241775
class Date
long lastModified = file.lastModified();
Date dateModified = new Date(lastModified);

>java FileInfo1 e:\bc221Book\source
e:\bc221Book\source is a directory.
There are 328 items in this directory.
Absolute path: e:\bc221Book\source
Name: source
Parent: e:\bc221Book
Path: e:\bc221Book\source
Length: 0
Last modified: Wed Feb 26 07:47:48 GMT+07:00 2003
>java FileInfo1 FileInfo1.java
FileInfo1.java is a file.
Absolute path: E:\b221Book\source\FileInfo1.java
Name: FileInfo1.java
Parent: null
Path: FileInfo1.java
Length: 1236
Last modified: Tue Feb 25 14:06:13 GMT+07:00 2003
>java FileInfo1
Usage: FileInfo1 file-name

directory subdirectory

8
Java

Streams I/O

208

//DirListing.java
//adopted from Bruce Eckel's
import java.io.*;
import java.util.Arrays;
//extract file name from path
//must implements FilenameFilter and override method accept()
//to get files with given information into a list
class DirFilter implements FilenameFilter {
String fileName;
//constructor
DirFilter(String fileName) {
this.fileName = fileName;
}

//this method is called by method list() from class File


//to include a file if it contains a given info
public boolean accept(File path, String name) {
//get only file name
String file = new File(name).getName();
//if in fact the file exists we will get the first index
//of this file, which causes accept() to return true,
//otherwise we will get -1 and returns false
return file.indexOf(fileName) != -1;
}

class DirListing {
public static void main(String[] args) {
//create file object with a default directory
File path = new File(".");
String[] fileList;
//list of files with given criteria
//no argument provided, get all files on this directory
if(args.length == 0)
fileList = path.list();
//information provided, get rid of path and extract files
//with given info.
else
fileList = path.list(new DirFilter(args[0]));

Arrays.sort(fileList);
showDir(fileList);

//sort the list


//display the list

//display files to screen


public static void showDir(String[] list) {
for(int i = 0; i < list.length; i++)
System.out.println(list[i]);
}
}

()
>java DirListing java

8
Java

Streams I/O

209

Access.java
Account.java
Add1To100.java

AddNumbers2.java
ThrowsWithTry.java
ThrowsWithTry1.java
Triangle.java
TryAndCatchExample1.java
TryAndCatchExample2.java
Two.java
UpperLower.java
UpperLower2.java
Variables.java
Vowels.java
ZeroDivideException.java
p.java
>java DirListing te
BankRate.class
BankRate.java
ByteShort.class
ByteShort.java
Calculate.class
Calculate.java
DirListing.java directory
DirListing


"te"
DirListing te
interface FileNameFilter override method accept()
method list() class File method
accept() path
method
list() list
args.length 0
array list
fileList = path.list();
method accept()


fileList = path.list(new DirFilter(args[0]));
args[0] "te" () "te"
path
Calculate.java
Method list() parameter
object class FileNameFilter
method accept()
path


String file = new File(name).getName();

8
Java

Streams I/O

210

method indexOf() class String "te"


indexOf() "te" -1
-1 list() (true = false = )
return file.indexOf(fileName) != -1;
method list() fileList
fileList method sort()
class Arrays


method list() class File code
method accept()
Method list() class File parameter parameter
method parameter parameter object class FileNameFilter

class class override method accept()
run

code method accept()

directory list() accept()


Input streams
Input and Output streams ( )
Java

(standard I/O)


1. character code
Text editor

text file
2. binary data

MS Word

binary file
text file code
//ReadingTextFile.java
import java.io.*;
class ReadingTextFile {
//don't want to deal with error, let Java takes care of it
public static void main(String[] args) throws IOException {
BufferedReader in;//input buffer
FileReader file; //input file
String str;
//string to store characters read from file
file = new FileReader(args[0]); //open an input file
in = new BufferedReader(file); //store contents in buffer
int lineNo = 1;

8
Java

Streams I/O

211

//keep reading from buffer until null is reached


while((str = in.readLine()) != null) {
System.out.println(lineNo + " " + str);
lineNo++;
}
in.close();
//manually close the file

FileReader() BufferedReader()
str buffer

close() ReadingTextFile.java
1 //ReadingTextFile.java
2
3 import java.io.*;
4
5 class ReadingTextFile {
6
//don't want to deal with error, let Java takes care of it
7
public static void main(String[] args) throws IOException {
8
BufferedReader in; //input buffer
9
FileReader file;
//input file
10
String str;
//string to store characters read
from file
11
12
file = new FileReader(args[0]); //open an input file
13
in = new BufferedReader(file); //store contents in
buffer
14
15
int lineNo = 1;
16
//keep reading from buffer until null is reached
17
while((str = in.readLine()) != null) {
18
System.out.println(lineNo + " " + str);
19
lineNo++;
20
}
21
in.close();
//manually close the file
22
}
23 }
FileInputStream() read()
//ReadTextFile.java
import java.io.*;
class ReadTextFile {
public static void main(String[] args) throws IOException {
FileInputStream in;
//file input stream
int ch;
//store each character read
try {
in = new FileInputStream(args[0]);
while((ch = in.read()) != -1) {
System.out.print((char)ch);
}
in.close();
}

8
Java

Streams I/O

212

//file not found


catch(FileNotFoundException e) {
System.err.println("Cannot find: " + args[0]);
System.exit(1);
}
//no argument specified
catch(ArrayIndexOutOfBoundsException e) {
System.err.println("Usage: ReadTextFile file-name");
System.exit(1);
}

FileInputStream() read() byte


FileInputStream ch
-1 EOF (End Of File)
cast ch
error


run ReadTextFile.java
//ReadTextFile.java
import java.io.*;
class ReadTextFile {
public static void main(String[] args) throws IOException {
FileInputStream in;
//file input stream
int ch;
//store each character read

try {
in = new FileInputStream(args[0]);
while((ch = in.read()) != -1) {
System.out.print((char)ch);
}
in.close();
}
//file not found
catch(FileNotFoundException e) {
System.err.println("Cannot find: " + args[0]);
System.exit(1);
}
//no argument specified
catch(ArrayIndexOutOfBoundsException e) {
System.err.println("Usage: ReadTextFile file-name");
System.exit(1);
}

character streams text



text binary data
Binary file text file

8
Java

Streams I/O

213

TextWithStreamTok.java text

format
String

double int

Notebook
CoffeeMug
PaperCutter

12.00
5.00
12.50

30
40
25

3 StreamTokenizer
keyboard

//TextWithStreamTok.java - Reading text data from a file


import java.io.*;
class TextWithStreamTok {
public static void main(String[] args) throws IOException {
BufferedReader in = null;
//input buffer
FileReader file = null;
//input file
StreamTokenizer stream = null; //tokens
try {
file = new FileReader(args[0]); //get a file from
argument-list
in = new BufferedReader(file); //storage buffer
//create tokens
stream = new StreamTokenizer(in);
stream.eolIsSignificant(true); //EOL counted but ignored
}
catch(FileNotFoundException e) {
System.err.println("Cannot find file: " + args[0]);
System.exit(1);
}
//arrays to store data only 3 items as example e.g.
//description prices unit
//Coffee-Mug 12.5 30
String[] descs = new String[3];
double[] prices = new double[3];
int[] units = new int[3];
int i = 0, j = 0, k = 0; //arrays' indices
boolean first = true;
//make sure correct data is read
try {
//reading tokens into corresponding arrays
//until EOF is reached
while(stream.nextToken() != StreamTokenizer.TT_EOF) {
//data is a string
if(stream.ttype == StreamTokenizer.TT_WORD) {
descs[i++] = stream.sval;
}
//data is a number (price or unit)
if(stream.ttype == StreamTokenizer.TT_NUMBER) {
//first data in line is price

8
Java

Streams I/O

214

if(first == true) {
prices[j++] = stream.nval;
first = false;
}
//next one is unit price
else {
units[k++] = (int)stream.nval;
first = true;
}

}
//ignore EOL
if(stream.ttype == StreamTokenizer.TT_EOL) {
/* do nothing */
}

}
in.close();

//close the stream


}
//trouble reading file
catch(IOException e) {
System.err.println("Error reading file.");
e.printStackTrace();
System.exit(1);
}
//too many items for arrays
catch(ArrayIndexOutOfBoundsException e) {
System.err.println("Array index out of bound.");
e.printStackTrace();
System.exit(1);
}
}

display(descs, prices, units);

//display data

//display data to screen


private static void display(String[] d, double[] p, int[] u) {
double total = 0.00;
for(int i = 0; i < d.length; i++) {
total = p[i] * u[i];
System.out.print(d[i] + "\t" + p[i]);
System.out.println("\t" + u[i] + "\t" + total);
}
}


format

file = new FileReader(args[0]); //get a file from argument-list


in = new BufferedReader(file); //storage buffer
//create tokens
stream = new StreamTokenizer(in);
stream.eolIsSignificant(true); //EOL counted but ignored
token stream string
while(stream.nextToken() != StreamTokenizer.TT_EOF) {
//data is a string

8
Java

Streams I/O

215

if(stream.ttype == StreamTokenizer.TT_WORD) {
descs[i++] = stream.sval;
}
//data is a number (price or unit)
if(stream.ttype == StreamTokenizer.TT_NUMBER) {
//first data in line is price
if(first == true) {
prices[j++] = stream.nval;
first = false;
}
//next one is unit price
else {
units[k++] = (int)stream.nval;
first = true;
}
}
//ignore EOL
if(stream.ttype == StreamTokenizer.TT_EOL) {
/* do nothing */
}

string descs[] double prices[] int


units[]

prices units first

prices[]
units[]
arrays display()
run
>java TextWithStreamTok data.dat
Notebook
12.0
30 360.0
CoffeeMug
5.0
40 200.0
PaperCutter
12.5
25 312.5
data.dat
Notebook 12.0 30
CoffeeMug 5.0 40
PaperCutter 12.5 25

Notebook 12.0 30 CoffeeMug 5.0 40 PaperCutter 12.5 25
nextToken()





(
string
) text file primitive type
text file text
StreamTokenizer

text
//WordCount.java - Using StreamTokenizer to count word

8
Java

Streams I/O

216

import java.io.*;
class WordCount {
public static void main(String[] args) throws IOException {
//exit if there's no file specified
if(args.length < 1) {
System.out.println("Usage: WordCount file-name.");
System.exit(1);
}
FileReader inFile = null;
//file stream
StreamTokenizer stream = null; //tokens stream
int count = 0;
//number of words in the file

try {
inFile = new FileReader(args[0]);
stream = new StreamTokenizer(inFile);
count = wordCount(stream);
System.out.println(count + " words counted in " +
args[0]);
}
catch(FileNotFoundException e) {
System.err.println("Cannot find: " + args[0]);
e.printStackTrace();
System.exit(1);
}
finally {
//close the file
if(inFile != null) {
try {
inFile.close();
}
catch(IOException e) { /* do nothing */ }
}
}

//method to count word in the stream


private static int wordCount(StreamTokenizer s)
throws IOException {
int count = 0;
try {
while(s.nextToken() != StreamTokenizer.TT_EOF) {
//count only word
if(s.ttype == StreamTokenizer.TT_WORD)
count++;
}
}
catch(IOException e) {
System.err.println("Error reading stream: " + s);
e.printStackTrace();
System.exit(1);
}
return count;
}

8
Java

Streams I/O

217

WordCount.java
command-line
argument StreamTokenizer string
string "s13" string
WordCount.java object FileReader
StreamTokenizer BufferedReader
FileReader

BufferedReader

run Windows Xp vbe6.dll 2,498,560


bytes BufferedReader
>java WordCount vbe6.dll
Start: Fri Feb 28 10:08:52 GMT+07:00 2003
279829 words counted in vbe6.dll
Stop: Fri Feb 28 10:08:54 GMT+07:00 2003
>java WordCount vbe6.dll
Start: Fri Feb 28 10:10:35 GMT+07:00 2003
279829 words counted in vbe6.dll
Stop: Fri Feb 28 10:10:36 GMT+07:00 2003
BufferedReader FileReader (
1 ) Date
code

BufferedReader buf = null;

//buffer holding data

try {
System.out.println("Start: " + new Date());
inFile = new FileReader(args[0]);
buf = new BufferedReader(inFile);
stream = new StreamTokenizer(buf);

finally {
//close the file
if(inFile != null) {
try {
inFile.close();
}
catch(IOException e) { /* do nothing */ }
}
//close stream
if(buf != null) {
try {
buf.close();
System.out.println("Stop: " + new Date());
}
catch(IOException e) { /* do nothing */ }
}

8
Java

Streams I/O

218

finally
finally finally
finally
( finally
)

Java method

method currentTimeMillis()

//ElapsedTime.java
class ElapsedTime {
public static void main(String[] args) {
long startTime, stopTime;
//get starting time
startTime = System.currentTimeMillis();
//do some looping
for(int i = 0; i < 100000; i++)
for(int j = 0; j < 100000; j++) ;
//get ending time
stopTime = System.currentTimeMillis();
//calculate elapsed time
double elapsedTime = (double)(stopTime - startTime) / 1000.0;

System.out.print("Elapsed time: ");


System.out.println(elapsedTime + " seconds.");

run
Elapsed time: 85.093 seconds.
ElapsedTime.java currentTimeMillis() loop
loop

text
(delimiter)

"|"


//TokenWithDelimiter.java - Using '|' as delimiter in a text file
import java.io.*;
import java.util.StringTokenizer;
import java.lang.Integer;
class TokenWithDelimiter {
public static void main(String[] args) throws IOException {
//data to write to file
String[] items = {"Notebook", "Coffee Mug", "Paper cutter"};
double[] prices = {12.0D, 5.0D, 12.5D};

8
Java

Streams I/O

219

int[] units = {30, 40, 25};


//check to see if a file is provided
if(args.length < 1) {
System.err.println("Usage: TokenWithDelimeter filename.");
System.exit(1);
}
writeToFile(args[0], items, prices, units);
processData(args[0]);
}
//writing data in arrays to a given file
private static void writeToFile(String fileName, String[] items,
double[] prices, int[] units)
throws IOException {
File dataFile = null;
FileWriter fWriter = null;
BufferedWriter buffer = null;
PrintWriter out = null;
try {
dataFile = new File(fileName);
fWriter = new FileWriter(dataFile);
buffer = new BufferedWriter(fWriter);
out = new PrintWriter(buffer);
//printing data to file with '|' in between
for(int i = 0; i < items.length; i++) {
out.print(items[i]);
out.print('|');
out.print(prices[i]);
out.print('|');
out.println(units[i]);
}

}
catch(IOException e) {
System.err.println("Error writing to file");
e.printStackTrace();
System.exit(1);
}
finally {
if(out != null)
out.close();
}

//reading data from a given file & display to screen


private static void processData(String fileName)
throws IOException {
String item; //item read
double price; //price read
int unit;
//unit read
File dataFile = null;
FileReader fReader = null;
BufferedReader buffer = null;
String input = null;
try {

8
Java

Streams I/O

220

dataFile = new File(fileName);


fReader = new FileReader(dataFile);
buffer = new BufferedReader(fReader);
input = buffer.readLine();
//read first line of data
//keep reading until there's no more lines to read
while(input != null) {
//get token from input-line - skip '|'
StringTokenizer token = new
StringTokenizer(input, "|");
item = token.nextToken();
price = Double.parseDouble(token.nextToken());
unit = Integer.parseInt(token.nextToken());
//display to screen
System.out.print(item + "\t" + price + "\t" + unit);
System.out.println("\t" + price * unit);
input = buffer.readLine();
}

}
catch(IOException e) {
System.err.println("Error reading file");
e.printStackTrace();
System.exit(1);
}
finally {
if(buffer != null)
buffer.close();
}

'|' class StringTokenizer


arrays print()
println() '|'

dataFile = new File(fileName);


fWriter = new FileWriter(dataFile);
buffer = new BufferedWriter(fWriter);
out = new PrintWriter(buffer);
//printing data to file with '|' in between
for(int i = 0; i < items.length; i++) {
out.print(items[i]);
out.print('|');
out.print(prices[i]);
out.print('|');
out.println(units[i]);
}
readLine()
'|'
nextToken()
token
StringTokenizer token = new StringTokenizer(input, "|");
'|' String
double int

8
Java

Streams I/O

221

String

dataFile = new File(fileName);


fReader = new FileReader(dataFile);
buffer = new BufferedReader(fReader);
input = buffer.readLine();
//read first line of data
//keep reading until there's no more lines to read
while(input != null) {
//get token from input-line - skip '|'
StringTokenizer token = new StringTokenizer(input, "|");
item = token.nextToken();
price = Double.parseDouble(token.nextToken());
unit = Integer.parseInt(token.nextToken());
//display to screen
System.out.print(item + "\t" + price + "\t" + unit);
System.out.println("\t" + price * unit);
input = buffer.readLine();
}
PrintWriter class PrintWriter
print() println()
PrintWriter FileWriter
BufferedWriter ( buffer
)
run
>java TokenWithDelimiter tokens.dat
Notebook
12.0
30
360.0
Coffee Mug
5.0
40
200.0
Paper cutter
12.5
25
312.5
Binary file
binary data

binary data method Java



Method
writeBoolean(boolean)
writeShort(int)
writeInt(int)
writeLong(long)
writeFloat(float)
writeDouble(double)
writeChar(int)
writeChars(String)
writeUTF(String)

Throws
IOException
IOException
IOException
IOException
IOException
IOException
IOException
IOException
IOException

boolean 1 byte
short 2 byte
int 4 byte
long 8 byte
float 4 byte
double 8 byte
char 2 byte
String 2 byte 1
String 1 byte
2 byte String

method

8
Java

Method
readBoolean()
readShort()
readInt()
readLong()
readFloat(0
readDouble()
readChar()
readUTF()
skipBytes(int)

Streams I/O

Throws
EOFException
EOFException
EOFException
EOFException
EOFException
EOFException
EOFException
EOFException
EOFException

222

1 byte boolean
2 byte Short
4 byte int
8 byte long
4 byte float
8 byte double
2 byte char
String UTF
byte

binary data
record 3 record
record
Record

Java record class record
3 field
1. description
2. price
3. unit

//DataFile.java - Sequential Access file


import java.io.*;
class DataFile {
public static void main(String[] args) throws IOException {
FileOutputStream fout;
//file output stream
DataOutputStream dout;
//data output stream
FileInputStream fin;
//file input stream
DataInputStream din;
//data input stream
//setting up data to be written to a file
String[] desc = {"Coffee Mug", "Bookmark", "Note book"};
double[] prices = {5.00, 2.00, 10.00};
int[] unit = {12, 50, 30};
//variables storing data read from file
String description;
double price, total = 0.00;
int unitPrice;
//open file for writing
try {
fout = new FileOutputStream(args[0]);
dout = new DataOutputStream(fout);
for(int i = 0; i < desc.length; i++) {
dout.writeUTF(desc[i]);
dout.writeDouble(prices[i]);
dout.writeInt(unit[i]);
}
dout.close();

8
Java

Streams I/O

223

}
catch(FileNotFoundException e) {
System.err.println("Cannot open " + args[0]);
return;
}
catch(ArrayIndexOutOfBoundsException e) {
System.err.println("Usage: DataFile file-name.");
return;
}

//open file for input


try {
fin = new FileInputStream(args[0]);
din = new DataInputStream(fin);
System.out.println("Description\tPrice\tUnit\tTotal");
while(true) {
description = din.readUTF();
price = din.readDouble();
unitPrice = din.readInt();
total = price * unitPrice;
display(description, price, unitPrice, total);
}
}
catch(EOFException e) {
//use this exception to stop the while loop
//and exit the program
System.exit(1);
}
catch(IOException e) {
System.err.println("Error reading file: " + e.toString());
System.exit(1);
}

//display a record to screen


public static void display(String d, double p, int u, double t) {
System.out.println(d+"\t"+p+"\t"+u+"\t"+t);
}

DataOutputStream DataInputStream
for loop
fout = new FileOutputStream(args[0]);
dout = new DataOutputStream(fout);
for(int i = 0; i < desc.length; i++) {
dout.writeUTF(desc[i]);
dout.writeDouble(prices[i]);
dout.writeInt(unit[i]);
}

binary data
while loop infinite loop
error loop


(EOF) code

8
Java

Streams I/O

224

fin = new FileInputStream(args[0]);


din = new DataInputStream(fin);
System.out.println("Description\tPrice\tUnit\tTotal");
while(true) {
description = din.readUTF();
price = din.readDouble();
unitPrice = din.readInt();
total = price * unitPrice;
display(description, price, unitPrice, total);
}
run
>java DataFile data.dat
Description
Coffee Mug
Bookmark
Note book

Price
5.0
2.0
10.0

Unit
12
50
30

Total
60.0
100.0
300.0


class extends
class class PrintWritter method output()

override method print() println() class
FormatWriter
DataFile.java
//DataFile.java - Sequential Access file
//-(modified for formatted output)
import java.io.*;
//for pretty printing (formatted - right justified)
class FormatWriter extends PrintWriter {
private int width = 10;
//default constructor
FormatWriter(Writer output) {
super(output);
}
//constructor with specified width
FormatWriter(Writer out, int width) {
super(out);
this.width = width;
}
//set prefer output style
private void output(String str) {
//calculate spaces
int blanks = width - str.length();
//fill with blanks before actual data
for(int i = 0; i < blanks; i++)
super.print(' ');
//print data
super.print(str);
}

8
Java

Streams I/O

225

//our print() and println() methods with different types of data


public void print(String str) {
output(str);
}
public void println(String str) {
output(str);
super.println();
}
public void print(double value) {
output(String.valueOf(value));
}
public void print(int value) {
output(String.valueOf(value));
}

public void println(double value) {


this.print(value);
super.println();
}

class DataFile {
public static void main(String[] args) throws IOException {
FileOutputStream fout;
//file output stream
DataOutputStream dout;
//data output stream
FileInputStream fin;
//file input stream
DataInputStream din;
//data input stream
//setting up data to be written to a file
String[] desc = {"Coffee Mug", "Bookmark", "Note book"};
double[] prices = {5.00, 2.00, 10.00};
int[] unit = {12, 50, 30};
double[] total = new double[3];
//open file for writing
try {
fout = new FileOutputStream(args[0]);
dout = new DataOutputStream(fout);
for(int i = 0; i < desc.length; i++) {
dout.writeUTF(desc[i]);
dout.writeDouble(prices[i]);
dout.writeInt(unit[i]);
}
dout.close();
}
catch(FileNotFoundException e) {
System.err.println("Cannot open " + args[0]);
return;
}
catch(ArrayIndexOutOfBoundsException e) {
System.err.println("Usage: DataFile file-name.");
return;
}
//open file for input
//reuse variables desc, prices, and unit
//calculate total fro each data item

8
Java

Streams I/O

226

try {
fin = new FileInputStream(args[0]);
din = new DataInputStream(fin);
boolean endOfFile = false;
//EOF marker
int index = 0;
//array index
while(!endOfFile) {
try {
//store data in arrays before printing
desc[index] = din.readUTF();
prices[index] = din.readDouble();
unit[index] = din.readInt();
total[index] = prices[index] * unit[index];
index++;
}
catch(EOFException e) {
endOfFile = true; //stop while loop
din.close();
//close the file
}
}
//display data - right justified
display(desc, prices, unit, total);
}
catch(IOException e) {
System.err.println("Error reading file: " + e.toString());
System.exit(1);
}

//display a record to screen


private static void display(String[] d, double[] p,
int[] u, double[] t) {
//create object from FileWriter with width of 12
FormatWriter out = new FormatWriter(
new BufferedWriter(
new FileWriter(FileDescriptor.out)), 12);
//display header
out.print("Description");
out.print("Prices");
out.print("Unit");
out.println("Total");
//display contents of arrays
for(int i = 0; i < d.length; i++) {
out.print(d[i]);
out.print(p[i]);
out.print(u[i]);
out.println(t[i]);
}
out.close(); //close the stream
}

class FormatWriter class PrintWriter constructor 2


default constructor constructor class PrintWriter

FormatWriter(Writer out, int width) {


super(out);

8
Java

Streams I/O

227

this.width = width;

width
width 10
2
8 method
output() print()
class PrintWriter
Method output() print() println()
string double int print() println()

public void print(int value) {


output(String.valueOf(value));
}
public void println(double value) {
this.print(value);
super.println();
}
output()

string output()
display() parameter array
class FormatWriter
private static void display(String[] d, double[] p,
int[] u, double[] t) {
//create object from FileWriter with width of 12
FormatWriter out = new FormatWriter(
new BufferedWriter(
new FileWriter(FileDescriptor.out)), 12);
//display header
out.print("Description");
out.print("Prices");
out.print("Unit");
out.println("Total");
//display contents of arrays
for(int i = 0; i < d.length; i++) {
out.print(d[i]);
out.print(p[i]);
out.print(u[i]);
out.println(t[i]);
}
out.close(); //close the stream
}
standard output object out
class FileDescriptor ( FileDescriptor in out err
input output error ) object
BufferedWriter buffer
buffer parameter

constructor FormatWriter 12 ( width)


parameter object out


print() println() object

8
Java

Streams I/O

228

main() code array


display()

boolean endOfFile = false;


//EOF marker
int index = 0;
//array index
while(!endOfFile) {
try {
//store data in arrays before printing
desc[index] = din.readUTF();
prices[index] = din.readDouble();
unit[index] = din.readInt();
total[index] = prices[index] * unit[index];
index++;
}
catch(EOFException e) {
endOfFile = true; //stop while loop
din.close();
//close the file
}
}
//display data - right justified
display(desc, prices, unit, total);

EOF error loop


-1
boolean loop
run
>java DataFile data.dat
Description
Coffee Mug
Bookmark
Note book

Prices
5.0
2.0
10.0

Unit
12.0
50.0
30.0

Total
60.0
100.0
300.0



code

writeUTF() writeChars()
//WriteCharsAndWriteUTF.java - Differences between the to methods
import java.io.*;
class WriteCharsAndWriteUTF {
public static void main(String[] args) throws IOException {
File f = new File(args[0]);
DataOutputStream out = new DataOutputStream(
new BufferedOutputStream(
new FileOutputStream(f)));
out.writeUTF("If it does not work, blame the computer.");
int utfSize = out.size();

8
Java

Streams I/O

229

out.writeChars("If it does not work, blame the computer.");


int charsSize = out.size() - utfSize;

out.close();
System.out.println("writeUTF() writes " + utfSize +
" bytes.");
System.out.println("writeChars writes " + charsSize +
" bytes.");

run
>java WriteCharsAndWriteUTF difs.dat
writeUTF() writes 42 bytes.
writeChars writes 80 bytes.
string 40 writeUTF() writeChars()
run writeUTF() 1 byte 2 byte
string writeChars() 2 byte
Random-access file
- sequential access



-
Random-access
random-access

operator


random-access file (logical pointer)
- (
) offset Java
seek
(fixed length record) p p * length
record record
(first name)
(last name)
(year of birth)
(salary)
record class
method
record
//RandomAccessFileDemo.java
import java.io.RandomAccessFile;
import java.io.*;
class RandomAccessFileDemo {
public static void main(String[] args) throws IOException {
//data to be written to a file

8
Java

Streams I/O

230

String[] names = {"John", "Paul", "Stephen", "Hendrix"};


String[] lasts = {"Kawakami", "Collins", "Anderson", "McCoy"};
int[] years = {1965, 1978, 1985, 1972};
double[] pays = {2400.0, 500.0, 5000.0, 9500.0};
//use to randomly select the position in a file
//to write to/read from e.g. random[0] is at the second
//position, random[2] is at the frist position etc.
int []random = {2, 3, 0, 1};
//writing to a file
RandomAccessFile f = new RandomAccessFile("emp.dat", "rw");
try {
for(int i = 0; i < 4; i++) {
Employee emp = new Employee(names[i], lasts[i],
years[i], pays[i]);
emp.write(f, random[i]);
}
}
catch(IOException e) {
System.err.println("Error writing file");
e.printStackTrace();
System.exit(1);
}
finally {
if(f != null) {
f.close();
}
}

//reading from a file


RandomAccessFile fin = null;
try {
fin = new RandomAccessFile("emp.dat", "r");
Employee em = new Employee();
System.out.println("Number of records = " +
em.size(fin) + "\n");
for(int i = 0; i < 4; i++) {
em.read(fin, random[i]);
System.out.print("Record #" + (i+1) + ": ");
em.show();
}
}
catch(IOException e) {
System.err.println("Error reading file");
e.printStackTrace();
System.exit(1);
}
finally {
if(fin != null)
fin.close();
}

array 4 record
random array random
record

8
Java

Record
Record
Record
Record

2
3
0

Streams I/O

231

(random[0])
(random[1])
(random[2])
(random[3])

object class Employee class


record code
//Employee.java - Simple record for random-access file
import java.io.*;
import java.io.RandomAccessFile;
import java.lang.String;
class Employee {
private String firstName; //15 characters (30 bytes)
private String lastName; //15 characters (30 bytes)
private int year;
//4 bytes
private double salary;
//8 bytes
private static final int RECORD_SIZE = 72;
//default constructor
Employee() {
firstName = "";
lastName = "";
year = 0;
salary = 0.0D;
}
//setting up fields
Employee(String firstName, String lastName,
int year, double salary) {
this.firstName = firstName;
this.lastName = lastName;
this.year = year;
this.salary = salary;
}
//write a record to a file with a given position
public void write(RandomAccessFile file, int position)
throws IOException {
try {
//locate a position
file.seek((long)(position * RECORD_SIZE));
//write equal-length strings
writeString(file, firstName, 15);
writeString(file, lastName, 15);
//write int and double
file.writeInt(year);
file.writeDouble(salary);
}
catch(IOException e) {
System.err.println("Error writing file");
e.printStackTrace();
System.exit(1);
}
}

8
Java

Streams I/O

232

//reading a record from a file with a given position


public void read(RandomAccessFile file, int position)
throws IOException {
try {
//locate position to read
file.seek((long)(position * RECORD_SIZE));
//reading strings
firstName = readString(file, 15);
lastName = readString(file, 15);
//reading int and double
year = file.readInt();
salary = file.readDouble();
}
catch(IOException e) {
System.err.println("Error reading file");
e.printStackTrace();
System.exit(1);
}
}
//helper method to write a string with specified length
public void writeString(DataOutput out, String s, int len)
throws IOException {
for(int i = 0; i < len; i++) {
if(i < s.length())
out.writeChar(s.charAt(i));
else
out.writeChar(0);
}
}
//helper method to read a string
public String readString(DataInput in, int len)
throws IOException {
String s = "";
int i = 0;
while(i < len) {
char c = in.readChar();
if(c != 0)
s += c;
i++;
}
return s;
}
//number of records in file
public int size(RandomAccessFile file) throws IOException{
int size = 0;
try {
size = (int)file.length() / RECORD_SIZE;
}
catch(IOException e) {
System.err.println("Error reading file.");
System.exit(1);
}
return size;
}

8
Java

Streams I/O

233

//display a record to screen


public void show() {
System.out.print(firstName + " ");
System.out.print(lastName + " ");
System.out.print(year + " ");
System.out.println(salary);
}

method class Employee


write(RandomAccessFile, position)
read(RandomAccessFile, position)
writeString(DataOutptu, String, length)
readString(DataInput, length)
size(RandomAccessFile)
record
logical
pointer
record


method writeUTF()
writeChars() ()
record 72 byte
writeChar() 30 byte year salary 4 8
byte
write() field Employee object
seek()
file.seek((long)(position * RECORD_SIZE));
position RECORD_SIZE field 2
15 (30 byte)
field
writeString() byte 0
field 15
//write equal-length strings
writeString(file, firstName, 15);
writeString(file, lastName, 15);
field filed writeInt() writeDouble()

//write int and double


file.writeInt(year);
file.writeDouble(salary);
code writeString()
string string
0

public void writeString(DataOutput out, String s, int len)


throws IOException {
for(int i = 0; i < len; i++) {
if(i < s.length())
out.writeChar(s.charAt(i));
else

8
Java

Streams I/O

234

out.writeChar(0);

filed seek()
readString() field readInt() readDouble() field

Code readString() 0 0
string
public String readString(DataInput in, int len) throws IOException {
String s = "";
int i = 0;
while(i < len) {
char c = in.readChar();
if(c != 0)
s += c;
i++;
}
return s;
}
readChar()
0
string s
record
record
public int size(RandomAccessFile file) throws IOException{
int size = 0;
try {
size = (int)file.length() / RECORD_SIZE;
}
catch(IOException e) {
System.err.println("Error reading file.");
System.exit(1);
}
return size;
}
readChar() writeChar() byte
record
random access file field field field

run
Number of records = 4
Record
Record
Record
Record

#1:
#2:
#3:
#4:

John Kawakami 1965 2400.0


Paul Collins 1978 500.0
Stephen Anderson 1985 5000.0
Hendrix McCoy 1972 9500.0

(update)

8
Java

Streams I/O

235

update record
update
record
field update
update
f.seek((long)(recNum 1) * em.recSize());
em.write(f, recNum 1);
record
seek()
method
record method class Employee
public void setFirstName(String name) {
firstName = name;
}
public void setLastName(String name) {
lastName = name;
}
public void setSalary(double pay) {
salary = pay;
}
public int recSize() {
return RECORD_SIZE;
}
public void setYear(int y) {
year = y;
}
update
keyboard
update

System.out.print("Enter record number: ");


buffer = new BufferedReader(new InputStreamReader(System.in));
str = buffer.readLine();
recNum = Integer.parseInt(str);
System.out.print("Enter first name: ");
emp.setFirstName(buffer.readLine());
System.out.print("Enter last name: ");
emp.setLastName(buffer.readLine());
System.out.print("Enter year of birth: ");
emp.setYear(Integer.parseInt(buffer.readLine()));
System.out.print("Enter salary: ");
emp.setSalary(Double.parseDouble(buffer.readLine()));
code

f.seek((long)(recNum 1) * em.recSize());
em.write(f, recNum 1);
run
>java Update temp.dat

8
Java

Enter
Enter
Enter
Enter
Enter

236

record number: 1
first name: My name
last name: Is changing
year of birth: 1965
salary: 2500

Record
Record
Record
Record
>java
Enter
Enter
Enter
Enter
Enter

Streams I/O

#1:
#2:
#3:
#4:

My name Is changing 1965 2500.0


Hendrix McCoy 1972 9500.0
John Kawakami 1965 2400.0
John Kowalski 1990 5400.0

Update temp.dat
record number: 3
first name: Jennie
last name: Saiudom
year of birth: 1995
salary: 500

Record
Record
Record
Record

#1:
#2:
#3:
#4:

My name Is changing 1965 2500.0


Hendrix McCoy 1972 9500.0
Jennie Saiudom 1995 500.0
John Kowalski 1990 5400.0

update field record object


class Employee object
update field update update field


//Update.java - Updating Random-access file
import java.io.RandomAccessFile;
import java.io.*;
import java.lang.Integer;
class Update {
public static void main(String[] args) throws IOException {
RandomAccessFile f = null;
Employee em = new Employee();
if(args.length < 1) {
System.err.println("Usage: Update file-name");
System.exit(1);
}

try {
f = new RandomAccessFile(args[0], "rw");
int recNum = getNewData(f, em); //get new data
updateData(f, recNum, em);
//update record
showData(f, args[0]);
//display records
}
catch(IOException e) {
System.err.println("Error processing file");
e.printStackTrace();
System.exit(1);
}

8
Java

Streams I/O

237

//get new data from keyboard


private static int getNewData(RandomAccessFile f, Employee emp)
throws IOException {
BufferedReader buffer = null;
InputStreamReader iStream = null;
String str = "";
int recNum = 0;

try {
System.out.print("Enter record number: ");
buffer = new BufferedReader(
new InputStreamReader(System.in));
str = buffer.readLine();
recNum = Integer.parseInt(str);
System.out.print("Enter first name: ");
emp.setFirstName(buffer.readLine());
System.out.print("Enter last name: ");
emp.setLastName(buffer.readLine());
System.out.print("Enter year of birth: ");
emp.setYear(Integer.parseInt(buffer.readLine()));
System.out.print("Enter salary: ");
emp.setSalary(Double.parseDouble(buffer.readLine()));
}
catch(IOException e) {
System.err.println("Error readin file");
e.printStackTrace();
System.exit(1);
}
return recNum; //record number

//update record
private static void updateData(RandomAccessFile f,
int recNum, Employee em)
throws IOException {
try {
//locate record
f.seek((long)(recNum 1) * em.recSize());
//write the whole record
em.write(f, recNum 1);
}
catch(IOException e) {
System.err.println("Error writing file");
e.printStackTrace();
System.exit(1);
}
finally {
if(f != null)
f.close();
}
}
//display all records in this file
private static void showData(RandomAccessFile f, String fName)
throws IOException {
try {
f = new RandomAccessFile(fName, "r");
Employee em = new Employee();

8
Java

Streams I/O

238

int num = em.size(f);


for(int i = 0; i < 4; i++) {
em.read(f, i);
System.out.print("Record #" + (i+1) + ":");
em.show();
}

}
catch(IOException e) {
System.err.println("Error reading file");
e.printStackTrace();
System.exit(1);
}
finally {
if(f != null)
f.close();
}

text file binary file




9
9
9
9
9
9
9
9
9

File method ifFile() canRead()

FileReader FileWriter FileInputStream FileOutputStream


DataOutputStream BufferedOutputStream
StreamTokenizer StringTokenizer
text file
delimiter text file
binary file
Random-access file
update random-access file

1.

directory

directory directory
directory
2. copy command-line
3.
int 100
text file 10
4. 3
(
11
)
5. 4
(column)
6.
delimiter
10

8
Java

Streams I/O

239

John Longman+25.0+30.50+48.00
Peter Wang+35.00+50.00+98.00

Mike Kawakami+90.00+80.00+85.00
7.
binary file class Student

keyboard
String 15
String 15
array double 85.0 90.5




()
class Student {
String firstName;
String lastName;
double[] grades;
}
8.
random-access file Student 7
user record
method
record ( keyboard)
9. Update update field salary
10. 6 method

240

Java


1 Unicode characters
dec hex
char
Dec
0
0000 <NUL>
33
1
0001 <SOH> 34
2
0002 <STX>
35
3
0003 <ETX>
36
4
0004 <EOT> 37
5
0005 <ENQ> 38
6
0006 <ACK>
39
7
0007 <BEL>
40
8
0008 <BS>
41
9
0009 <HT>
42
10
000A <LF>
43
11
000B <VT>
44
12
000C <FF>
45
13
000D <CR>
46
14
000E <SO>
47
15
000F <SI>
48
16
0010 <DLE>
49
17
0011 <DC1>
50
18
0012 <DC2>
51
19
0013 <DC3>
52
20
0014 <DC4>
53
21
0015 <NAK> 54
22
0016 <SYN>
55
23
0017 <ETB>
56
24
0018 <CAN> 57
25
0019 <EM>
58
26
001A <SUB>
59
27
001B <ESC>
60
28
001C <FS>
61
29
001D <GS>
62
30
001E <RS>
63
31
001F <US>
64
32
0020 blank
65

128
hex
char
0021 !
0022 "
0023 #
0024 $
0025 %
0026 &
0027 '
0028 (
0029 )
002A *
002B +
002C '
002D 002E .
002F /
0030 0
0031 1
0032 2
0033 3
0034 4
0035 5
0036 6
0037 7
0038 8
0039 9
003A :
003B ;
003C <
003D =
003E >
003F ?
0040 @
0041 A

dec
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

hex
0042
0043
0044
0045
0046
0047
0048
0049
004A
004B
004C
004D
004E
004F
0050
0051
0052
0053
0054
0055
0056
0057
0058
0059
005A
005B
005C
005D
005E
005F
0060
0061
0062

2 Constants

Math.E
Math.PI
Float/Double.NEGATIVE_INFINITY
Float/Double.POSITIVE_INFINITY
Float/Double.NaN
Byte/Short/Integer/Long/Float/Double.MAXIMUM_VALUE
Byte/Short/Integer/Long/Float/Double.MINIMUM_VALUE
System.in
System.out
System.err

char
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z
[
\
]
^
_

dec
99
100
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

hex
0063
0064
0065
0066
0067
0068
0069
006A
006B
006C
006D
006E
006F
0070
0071
0072
0073
0074
0075
0076
0077
0078
0079
007A
007B
007C
007D
007E
007F
0080

char
c
d
e
f
g
h
i
j
k
l
m
n
o
p
q
r
s
t
u
v
w
x
y
z
{
|
}
~
<DEL>

a
b

e (natural logarithm)
PI (3.145)
infinity
infinity

(keyboard)
()
error ()

241

Java

byte
short
int
long
float
double

3 Numeric Types
bit

8
0
16
0
32
0
64
0
32
0.0f
64
0.0d

4 Escape Sequences
Escape Sequence
\b
\t
\n
\f
\r
\"
\'
\\
\uxxxx
\xxx

-128
-32768
-2147483648
-9223372036854775808
1.40129846432481707e-45f
4.94065645841246544e-324

127
32767
2147483647
9223372036854775807
3.40282346638528860e+38f
1.79769313486231570e+308

back space
tab
LF ()
FF ()
CR ()
double quote
single quote
back slash
Unicode \u 16
\101

5 Format Syntax
form

0000
314
0314
###0
314
314
##0.0#
3.10
3.1
#,##0
3000
3,000
##0.00%
3.1415
314.15%
\u00A4##0
314
$314

0 digit
# - digit
. -
, -
% - 100 %
\u00A4 locale

Anda mungkin juga menyukai