( )
()
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
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
1
Java
Java
3. Environment Variables
5. Edit
1
Java
Java
path
path (
path path )
Java
path path
Java
javac
compile (compiler)
source code
byte code
java
1
Java
Java
Text Editor
Javac
Java Program
Output
1-1 application
Text Editor
Javac
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
compile HelloWorld
( 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
(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
Dos Window
Java
Text Editor EditPlus ( Text Editor
EditPlus )
1
Java
Java
EditPlus Java
download www.editplus.com shareware
30
install menu
Tools
Preferences
1
Java
Java
10
Menu Text:
Command:
Argument:
Initial directory:
9 Capture output
1
Java
Java
11
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
(data) (variable)
(calculation evaluation)
Java
o
o
o
o
o
o
o
character boolean
(assignment)
(statement expression)
(calculation evaluation)
(casting)
(Mathematical Functions) Java
(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
Java
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';
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
)
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;
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;
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);
{
}
//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 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
Value of local x is 20
2
Java
22
2
Java
23
Value of local y is 20
x
y
7
1.
2.
3.
4.
5.
6.
7.
class variable
instance variable
array component
method parameter
constructor parameter
exception-handler parameter
local variable
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
//evaluate
i = j + k;
i = j - k;
i = j * k;
i = j / k;
i = 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
i = j % k;
k 2 j 5
( 1) i
int double
2
Java
25
operators
" + i);
" + i);
" + i);
" + i);
" + i);
Operators.java operator
i j
(random) method nextInt(max value) method 0
max value max value 1 10
1 method
=
=
=
=
1
1
1
1
+
+
+
+
(int)(Math.random()
(int)(Math.random()
(int)(Math.random()
(int)(Math.random()
*
*
*
*
10);
10);
10);
10);
2
Java
26
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 )
//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));
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 += 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);
(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
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;
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
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
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;
FloatingPoint.java
1075 1580 8.5% execute
Tax = 591.175
Total income = 6363.825
? 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
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
Tax = 591.18
Total income = 6363.82
class DecimalFormat NumberFormat format
DecimalFormat form = new DecimalFormat("#.00);
, (comma)
2
Java
37
integer
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;
2.0
cast cast
//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;
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);
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);
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));
degrees radians
/* Maths1.java - Other math functions */
import java.text.DecimalFormat;
class Maths1 {
2
Java
42
math function
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)
double
abs(arg)
absolute arg
max(arg1, arg2)
arg1
arg2
arg1
arg2
arg
arg
integer
arg
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
=
=
=
=
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");
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
& |
operator && & &&
false false
false
operator || &&
true
true
true
operator & |
2
Java
46
operator !
boolean
Operator
boolean
<
>
<=
>=
==
!=
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;
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
Java
2.8
P
true
false
true
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
of
of
of
of
of
of
bits
bits
bits
bits
bits
bits
is
is
is
is
is
is
1
2
4
8
16
32
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
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));
2
Java
52
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
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));
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
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)
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
2
Java
57
17. 865,000
7,600
17.1.
17.2.
17.3.
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(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);
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
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';
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
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';
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
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);
Conditional Operator (? :)
Java operator if else operator
Conditional operator operator expression (statement)
(expression) ? (true statement) : (false statement);
/* OddEven.java */
import java.io.*;
class OddEven {
public static void main(String[] args) {
int num;
String result;
/* Min.java */
import java.io.*;
class Min {
3
Java
(Repetition)
69
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
3
Java
(Repetition)
71
break;
}
System.out.println(month + " is in " + season);
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++;
3
Java
(Repetition)
System.out.println("Number
number++;
System.out.println("Number
number++;
System.out.println("Number
number++;
System.out.println("Number
73
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;
3
Java
(Repetition)
74
expression
expression1
expression initialization expression
expression1
expression2
( ?)
no
yes
statement
expression3
statement
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
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;
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);
Amount on deposit
12500.0
15625.0
19531.25
24414.0625
30517.578125
3
Java
(Repetition)
77
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));
<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++) ;
expression1 i = 0 sum = 0 ,
expression3 sum += i i++
for loop
expression3 ; ( {}) Java 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
i sum
i <= 10 while loop i
sum i while loop for
loop
i = 0;
sum = 0;
expression for loop
3
Java
(Repetition)
82
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
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;
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
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) {
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) {
3
Java
(Repetition)
89
*
**
***
****
*****
******
*******
********
*********
**********
for loop row loop index
row for loop column loop index
for loop
for loop
column row
'*' continue
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;
}
3
Java
(Repetition)
91
/* LabledContinue.java */
import java.io.*;
class LabeledContinue {
public static void main(String[] args) {
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.");
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
array
num
array
array
int
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
4
Java
Array String
98
=
=
=
=
=
=
=
=
=
=
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
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
=
=
=
=
=
2
3
1
56
90
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
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
/* 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]);
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
//original array
//new array
4
Java
Array String
102
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
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]);
}
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);
4
Java
Array String
104
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));
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
System.out.println("Face\tFrequency");
for(int i = 1; i < frequency.length; i++)
System.out.println(i + "\t" + frequency[i]);
}
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
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
4
Java
Array String
109
if(key == list[middle]) {
found = true;
break;
}
array
Java
()
method sort Java
4
Java
Array String
110
//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();
if(found >= 0)
System.out.println("Found " + key + " at index " + found);
else
System.out.println(key + " is not in the list!");
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]
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
4
Java
Array String
116
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");
4
Java
Array String
117
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;
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
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");
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");
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);
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
//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++;
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.
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);
}
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);
4
Java
Array String
125
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
4
Java
Array String
126
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
string.append(100);
string.append(" fish.");
System.out.println("string is " + string);
4
Java
Array String
128
string
string
string
string
string
is
is
is
is
is
2
2
2
2
2
fisher
fishermen
fishermen with
fishermen with 100 fish.
run
Reverse of [I love Chaing Mai] is [iaM gniahC evol I]
4
Java
Array String
129
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
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);
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
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
4
Java
Array String
132
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)
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
//method
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
class Student {
static int count = 0;
String
String
String
String
Object share
count
id;
firstname;
lastName;
dateOfBirth;
0
Joe
id
firstNAme
lastName
dateOfBirth
Jon
id
firstNAme
lastName
dateOfBirth
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;
5
Java
Objects Classes
138
dateOfBirth = dOfB;
count++;
Method
method
Method
method
method
Parameter ()
void
5.3 method
5
Java
Objects Classes
139
method
Parameter
int
getAge
method
Parameter
display
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);
}
5
Java
Objects Classes
141
class Parameters {
public static void main(String[] args) {
double radius = 2.0;
double area = findArea(radius);
radius
r
area
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;
copy
total
total
10
copy total
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
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()
}
5
Java
Objects Classes
143
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
c.changeRadius(radius);
return c;
5.6 pass-by-reference
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;
}
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;
}
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();
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;
20)
50)
20)
50)
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()
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());
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
5
Java
Objects Classes
148
stu1.dateOfBirth;
method
class
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);
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
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
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
5
Java
Objects Classes
153
5
Java
Objects Classes
154
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);
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
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");
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();
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
//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
//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));
}
5
Java
Objects Classes
160
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);
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
array (arr[i])
tab (\t)
newline (\n)
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 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
Class
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
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
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
class
class method
class class
class class class
class
o
o
o
o
o
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
Scooter
Chopper
6
Java
class class
168
//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;
}
6
Java
class class
169
6
Java
class class
170
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;
//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;
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());
6
Java
class class
173
Shapes
Polygons
Triangle
Rectangle
Circle
Square
6
Java
class class
174
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);
}
6
Java
class class
176
6
Java
class class
177
6
Java
class class
178
am
am
am
am
am
a
a
a
a
a
square with a
triangle with
circle with a
triangle with
circle with a
object
class method
getClass() method getName() class Class Java object
shapes[0] class
6
Java
class class
179
return circle;
6
Java
class class
180
//code
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
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()));
}
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 =
6
Java
class class
183
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
6
Java
class class
184
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();
6
Java
class class
185
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
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
6
Java
class class
187
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
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
Exception
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;
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.");
}
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
}
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();
}
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;
7
Java
error (Exceptions)
193
>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("After a for loop.");
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("error message: " + e.getMessage());
e.printStackTrace();
}
finally {
System.out.println("In finally 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();
}
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();
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();
7
Java
error (Exceptions)
199
exception method readInt()
Method
method divide()
parameter 2
7
Java
error (Exceptions)
200
ZeroDivideException(String message) {
super(message);
}
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);
}
argument list
throw exception
OutOfRangeException
//OutOfRangeException.java
7
Java
error (Exceptions)
202
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
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
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]);
8
Java
Directory?
File?
Hidden?
Streams I/O
206
: Yes
: No
: No
//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;
}
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);
()
>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
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
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
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);
}
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
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();
//display data
format
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 */
}
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 */ }
}
}
8
Java
Streams I/O
217
WordCount.java
command-line
argument StreamTokenizer string
string "s13" string
WordCount.java object FileReader
StreamTokenizer BufferedReader
FileReader
BufferedReader
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;
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
}
catch(IOException e) {
System.err.println("Error writing to file");
e.printStackTrace();
System.exit(1);
}
finally {
if(out != null)
out.close();
}
8
Java
Streams I/O
220
}
catch(IOException e) {
System.err.println("Error reading file");
e.printStackTrace();
System.exit(1);
}
finally {
if(buffer != null)
buffer.close();
}
8
Java
Streams I/O
221
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
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;
}
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
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
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);
}
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()
8
Java
Streams I/O
228
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.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
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])
8
Java
Streams I/O
232
8
Java
Streams I/O
233
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:
(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
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:
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:
//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
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
}
catch(IOException e) {
System.err.println("Error reading file");
e.printStackTrace();
System.exit(1);
}
finally {
if(f != null)
f.close();
}
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