Professional Documents
Culture Documents
Core Java
Core Java
I N T R O D U C T I O N
Java is an Object Oriented Programming Language developed by Sun Micro systems.
The language has its syntax similar to that of C. rogramming in Java is very similar to
C!C"".
#t is far easier to create bug free code using Java than using C""$ because of the follo%ing
differences&
1. pointer arithmetic is avoided.
2. manual memory allocation and deallocation due to %hich a lot of memory
though not used is bloc'ed . Memory in Java is automatically garbage
collected..
3. Introduction of true arrays i.e. the arrays li'e in C are not mixed %ith pointer
arithmetic. They are accessed totally using indexing mechanism to avoid the
confusion and malfunctioning of pointers.
4. Eliminated the confusion of an assignment with a test for equality.
The condition if (x ) * + is not correct in Java. #t must be %ritten as
if (x == *+.
HISTORY
The efforts to create Java have started from the year ,--,. #n fact the Sun company$ the
creator of Java %anted to design a small computer language that could be used for
consumer devices li'e cable T. s%itch boxes. Since these devices do not have a lot of
po%er nor lot of memory the language had to be small and generate a very tight code.
/lso$ because different manufacturers may choose different central processing units$ it %as
important not to be tied do%n to any single architecture.
The Sun engineers designed a portable language that generated intermediate code based
on the language called 0CS1 ascal. This intermediate code could then be used on any
machine that had the correct interpreter.
The interpreter understands the intermediate code and generates the machine code to
execute the program. Since intermediate code is not pac'ed %ith the machine code$ the
executable code is smaller than that of C2language executable code and %as portable to
any machine.
1
Since the Sun people are from 03#4 bac'ground$ they based their language on C"" and
made the language object2oriented rather than procedure oriented. #nitially this ne%
language %as given the name 56a'7. Sun realised later that 6a' %as the name of an
existing computer language and so they renamed the ne% language as 5Java7.
The 8orld 8ide 8eb exploded in popularity in ,--* and Sun people sa% the immediate
potential of using Java to create 8eb pages %ith dynamic content2/pplets. These %ere
Java programs %hich %ere loadable in a 9TM: 1ocument. To sho% off the po%er of
Java$ a bro%ser named 9ot Java %as developed in Java and made it capable of interpreting
the intermediate byte codes. This has increased the importance of Java.
FEATURES
The creators of Java have declared it to have the follo%ing features.
,. Simple 2 The language syntax is based on the familiar programming language C"
". Though the syntax of C"" %as adopted$ some features %hich %ere
troublesome %ere avoided ma'ing the Java programming simple.
;. Object oriented 2 The object oriented features of Java are comparable to C"".
6ne major difference bet%een Java and C"" lies in multiple inheritance. 6bject
oriented design is a techni<ue that focuses design on data (i.e objects+ and on the
interfaces to it.
*. Architectural Neutral - The Java compiler generates an intermediate byte code
%hich does not depend on any architecture of a computer i.e.$ %hether it is an
#=M C$ a Macintosh$ or a Solaris system. So the Java programs can be used on
any machine irrespective of its architecture and hence the Java program is
/rchitectural 3eutral.
>. Portable type 2The si?e of data types are al%ays same irrespective of the system
architecture.
2 That is an int in Java is al%ays *; bit unli'e in C!C"" %here the si?e may be ,@2
bit or *;2bit depending on the compiler and machine. 9ence %hen ported on
different machines$ there does not occur any change in the values the data types
can hold. /nd also Java has libraries that enables to port its application on any
systems li'e 03#4$ 8indo%s and the Macintosh systems.
A. Distributed 2 Javas net%or'ing capabilities are both strong and easy to use. Java
applications are capable of accessing objects across the net$ via 0B:s as easy as a
local file system.
2
@. Secure 2 Since Java is mostly used in net%or' environment$ a lot of emphasis has
been placed on security to enable construction of virus free and tamper free
systems.
C. Smaller code 2 The Java compiler generates an intermediate byte code to ma'e it
architecture neutral. Though Java interpreter is needed to run the byte code$ it is
one copy per machine and not per program.
D. Multithreaded 2 Multithreading is the ability for one program to do more than
one tas' at once. Compared to other languages it is easy to implement
multithreading in Java.
-. nterpreted 2 The Java #nterpreter can execute Java bytecode$ directly on any
machine to %hich the interpreter has been ported. #nterpreted code is slo%er than
compiled code.
,E. !igh per"ormance 2 The byte codes can be translated at run time into machine
code for the particular C0 on %hich the application is running.
,,. Applet programming is one of the important features %hich has attracted the
users of the #nternet. /pplets are Java programs that are typically loaded from the
#nternet by a bro%ser.
Ja#a $n#ironmentF Gigure sho%s a typical Java program development environment$
%hich normally goes through five phases.
hase , 2 $ditF Hditing a file usually through an editor program on %indo%s2-A
and 8indo%s 3T. Hither 16S editor or 3otepad can be
used.
hase ; 2 %ompileF The Java program needs to be compiled. The compiler translates
the Java program into byte codes %hich is called a class.
hase * 2 Load F #n order to execute the program$ the byte code!class is transferred
to memory. This is done by class loader.
hase > 2 Veri"y F =efore the byte codes are executed$ they are verified by the byte
code verifier$ to ensure that the byte codes are valid and do
not violate Javas security restrictions.
hase A 2 $&ecute F The computer$ under the control of its C0$ interprets the program
one byte code at a time.
3
A typical Ja#a $n#ironment
Hditor 1is' rogram is created in the
editor and stored on dis'.
Compiler 1is' Compiler creates bytecodes
and stores them on dis'.
rimary Memory
Class :oader
Class loader puts bytecodes in
. memory.
1is' .
.
rimary Memory
=ytecode .erifier
=ytecode verifier confirms
that all bytecodes are valid
. and do not violate Javas
. security restrictions.
.
rimary Memory
#nterpreter
#nterpreter reads bytecode
and translates them into
. machine language.
.
.
4
JD' (tilities
javac - the Java byte code compiler
java - the Java interpreter
appletviewer - to vie% the /pplets from command prompt.
javadoc - the document generator from java source files.
jdb - java debugger
javap - java disassembler
rmic - Creates Class files that support Bemote method invocation.
rmiregistry - Begistry used to gain access to BM# objects on a specific
machine.
jar - Java/rchive(J/B+ file generator. J/B files allo% multiple Java
classes and resources to be distributed in one compressed file.
javakey - #mplements digital signing of J/B and class files. /llo%s
/pplets to be certified by trusted authorities.
$ample) A Sample Program
SourceGile F Sample,.java
public class Sample1{
public static void main(String[] argv) {
Systemoutprintln(!"ava #rogram$%)&
'
'
#n Java$ a program is al%ays a set of one or more Classes. /ny variable$ or function
(called methods + must be a member of one class or the other. 5main7 is the method %here
the program execution starts.
*unning the Ja#a program
,. Hnter the program using 16S editor!8indo%s 3otepad %ith file name
Sample,.java and save it.
;. Compile using javac Sample1java (javac -verbose Sample1java+
*. Bun the Java program by loading the class through class loader (virtual machine+
java Sample1
>. java -pro( Sample1 gives a profile file java.prof giving details li'e time
spent in each method etc.
The java command creates a Java .irtual Machine %hich assumes all the resources of
the system as its o%n machine and uses the same.
Sample+,ja#a Analysis
5
Java Source Gile 3ameF Sample,.java. Sample, is a name of class.
This Java source code must be stored only in Sample,.java file. The name of Java source
file should tally %ith the public class defined in the file. This also implies that there can be
only one public class defined in one Java source file. public is the access modifier
discussed in detail separately$ classes are explained later. main is the method (or
function+ that must be defined in any application and is the method executed by default.
This serves as the program execution starting point similar to C programs. /s hinted
earlier any method or variable must be al%ays from a class or object. System is the class
available to all J/./ programs. out is the static object(rintStream+ in the class System.
println is a method defined in rintStream class. 9ence Systemoutprintln(!%)
prints the output on to the standard output device (console+.
6
JAVA LANGUAGE - BASICS
D$N-.$*S
,. /n identifier is a name given to a variable$ class$ method$ pac'age or interface
;. 3o limit on 3umber of characters in the name of an identifier.
*. The first character can be a letter$ an I(underscore+ or J.
%on#entions "or naming the identi"iers)
,. Class names have capital letter for the first letter of every %ord.
Hxample F Savings)ccount* +mployee* ,andom)ccess-ile
;. Gunction names start %ith a small letter for first %ord and every next %ord must
start %ith capitals for the first letter.
Hxample F get,adius()* get.alance()* debit()* set/nterest,ate()
*. .ariable names have same convention as method name has.
Hxample F name* date0(0pening)ccount* opening.alance
>. 3ames of :iterals or constant values have all letters in capitals and %ords are
separated by I.
Hxample F #3THBHSTIB/TH$
%omments in JAVA programs
There are * different types of comments in Java programs
,. 12 3ormal 4 language type o( comment enclosed between slas5 star
star slas5 pairs 21
;. 11 Single line comment
116reats its rig5t side as comment up to end o( line
*. 122java speci(ic comment enclosed between slas5 star star and
star slas5 pairs 21
Data Type !" JAVA #
$
1ata types provide a %ay to hold data of various nature. There are Gour categories of data
types supported in Java. They are primitive types$ /rrays$ classes and interfaces.
Primiti#e Data types
byte 2 D bit signed integer %ith values bet%een 2,;D to ",;C
s5ort 2 ,@ bit signed integer %ith values bet%een 2*;C@D to "*;C@C
int 2 *; bit signed integer %ith values bet%een 2;
*,
to " ;
*,
2,
long 2 @> bit signed integer %ith value bet%een 2;
@*
to ";
@*
2,
(loat 2 *; bit single precision floating point number %ith values bet%een
7,.>EH2>A to 7 *.>EH"* (approx.+
double 2 @> bit double precision floating point numbers %ith values bet%een
7 >.->H2*;> to 7 *ED (approx.+
c5ar 2 ,@ bit 0nicode characters. These are same as /SC## %ith high
byte set to E.
boolean 2 These have values of either true or false.
NO-$) 3o pointer data type is defined in Java.
LITERALS
:iterals are the values %hich remain constant through out the program. :iterals$ also
'no%n as constants$ are basically of "i#e typesF int$ floating point$ boolean$ character and
String.
/n integer literal by default is of type int. =ut to ma'e an integer a long$ default
behaviour can be overridden by adding letter : to the end of the integer. / floating literal
by default represents a double precision$ to mar' it as float number$ the G suffix is added
to the end of the literal. Gor the char datatype predefined escape se<uences can be used to
indicate special characters li'e Kn for a ne% line character. Gormats for :iterals of each
1atatype are given in the table belo%F
Decimal ntegers : decimal digits 89 should not start %ith 8
(byte* s5ort* int)
!e&adecimal : 8: follo%ed by hexadecimal digits 8-9* )--
(byte* s5ort* int)
Octal no, : 8 follo%ed by decimal digits
(byte* s5ort* int)
long : same as int but follo%ed by character l or ;
%
"loat : 1igits %ith decimal point and!or exponent$ follo%ed
by ( or -
double : same as float %ithout - or ( suffix
boolean : true or (alse
char : <nicode (or )S4//) %ith simple <uotation mar's
$&les
int = int count=1>8& int octcount=8?@&int 5e:count=8:1ac&
c5ar = c5ar c5 = A4B& c5ar newline = ACnB&
boolean = boolean done = true
(loat = (loat interest,ate = >?(& (loat price = >?D8-&
double = double balance = 1ED1& double amount = ?EDED8
long = long emp/d3umber = 1>?;&
E&p'e!(" ) Ope'at('
Hxpressions are combinations of identifiers$ symbols or operators and evaluate to a value
of some type. The value may be a number$ string$ or any other class or datatype depending
on the variables in expression. /n expression may again consist of expressions called as
subexpressions and they may themselves have subexpressions etc.
/s in C$ an assignment has a value of its o%n& namely$ the value of the assignment is the
value of the right hand side of assignment itself.
$&le= b = a = 1D implies a=1D and also b = 1D
Ope'at(' E&p'e!(" :
6ther type of expressions involve operators. /n operator is a symbol that transforms a
variable or combines it in some %ay %ith another variable or literal. The expression on
%hich an operator acts are called operands. /n operator that operates on single operand is
called a unary operator. /n operator that needs t%o operands is called binary operator.
$&leF a = b 2 c&
arg = sum1no&
aFF& a--& -a&
Type (* Ope'at(' :
+
Java operators are categorised into C types .
Arithmetic operators,
Relational operators,
Boolean operators,
Bitwise operators,
Assignment operators,
String operators,
Special operators
A'!t,-et!. (pe'at(' #
/rithmetic operators ta'e t%o values$ integer or float $ and return a third value %hose type
can be determined as follo%sF
2 T%o integer types (byte$ short$ int or long+ produce int or long
2 T%o floating points produce floating point (if either is double$ it produces a double+
2 /n integer and a float produces a float.
Operators
)ddition F
Subtraction -
Gultiplication 2
Hivision 1
Godulus I
36THFThe modulus operator %hich gives the remainder %or's %ith floating
point operands.
Re/at!("a/ (pe'at(' #
These operators compare t%o <uantities to determine if they are e<ual or if one is greater
than the other or not . The relational operators are F
J returns true i( le(t value is greater t5an rig5t value
K returns true i( le(t value is lesser t5an rig5t value
J= returns true i( le(t value is greater t5an or eLual to rig5t value
K= returns true i( le(t value is lesser t5an or eLual to rig5t value
== returns true i( le(t value is eLual to rig5t value
$= returns true i( le(t value is not eLual to rig5t value
$&le F i( (a J b) c = a&
else c = b&
0((/ea" (pe'at(' #
=oolean operators act on boolean operands and return a boolean result. They implement
the standard boolean algebraic operationsF /31$ 6B$ 36T and 46B
11
LL (/31+ - Beturns true if both operands are true
MM (6B+ 2 Beturns Galse if both operands are false
$ (36T+ 2 Beturns Galse if operand is true and viceversa
M (46B+ 2 Beturns true if the operands are not the same
The difference bet%een L$ LL isF
/ forces the evaluation of both the operands.
// %ill not evaluate the second operand if it can determine the result
after evaluating the first.
0!t2!e Ope'at('#
Operator Name Description
L bit%ise /31 The bits in the result are set to + if the
corresponding bits in the t%o operands are
both +.
N bit%ise inclusive 6B The bits in the result are set to + if at least
one of the corresponding bits in the
t%o operands is +.
M bit%ise exclusive 6B The bits in the result are set to + if exactly
one of the corresponding bits in the t%o
operands is +.
OO left shift Shifts the bits of the first operand left by
the number of bits specified by the second
operand& fill from the right %ith 0 bits.
PP right shift %ith Shifts the bits of the first operand right by
sign extension the number of bits specified by the second
operand. #f the first operand is negative$
+s are shifted in from the left& other%ise 0s
are shifted in from the left.
PPP right shift %ith ?ero Shifts the bits of the first operand right by
extension the number of bits specified by the second
operand& 0s are shifted in from the left.
Q ones complement /ll 0 bits are set to + and all + bits are set to 0
$&les)
OO :eft Shift HxF D OO ; gives *;
2D OO ; gives 2*;
PP Bight sign Shift HxF D PP ; gives ;
2D PP ; gives 2;
PPP Bight ?ero Shift HxF D PPP ; gives ;
2D PPP ; gives ,EC*C>,D;;
Q 3egation HxF D Q E gives 2-
11
2D Q E gives C
L /31 HxF D L ; gives E
2D L ; gives E
N 6B HxF D N ; gives ,E
2D N ; gives 2@
M 46B HxF D M ; gives ,E
2D M ; gives 2@
A!3"-e"t Ope'at('#
The assignment operator stores the value on the right side expression to variable given on
the left side of the operator.
variableIname ) expression
8here expession is a constant$ a variable or combination of the variables and operators.
") /dds the value on the right side to the value of the variable on left side and
assigns to the same.
HxF a ") ,E& expands to a ) a " ,E& value ,E is added to a and assigned to a
itself
-= Subtracts the value on the right side from the value of the variable on left side and
assigns to the same.
HxF a 2) ,E& expands to a ) a 2 ,E& .alue ,E is subtracted to a and assigned
to a itself
2= Multiplies the value on the right side to the value of the variable on left side and
assigns to the same.
HxF a R) ,E& expands to a ) a R ,E& .alue ,E is multiplied to a and
assigned to a itself
1= 1ivides the value of the variable on left %ith the value on right side and assigns
<uotient to the same.
HxF a !) ,E& expands to a ) a !,E& a is divided %ith value ,E and
assigned to a itself
PP) Shifts right %ith sign extension$ the value of the variable on left by number of
times given on the right side and assigns to the same.
HxF aPP);& expands to a ) a PP ;& .alue of a is shifted right by ; times
12
OO) Shifts left$ the value of the variable on left by number of times given on the right
side and assigns to the same.
HxF aOO);& expands to a ) a OO ;& .alue of a is shifted left ; times
PPP) Shifts right %ith ?ero extension $ the value of the variable on left by number of
times given on the right side and assigns to the same.
HxF aPPP);& expands to a ) a PP ;& .alue of a is shifted right by ; times %ith
?ero extension.
L) =it%ise L(/31+ operation on the value of the variable on left by value on
right and is assignment to the same.
HxF a L);& expands to a ) a L ;&
M= =it%ise M(46B+ operation on the value of the variable on left by value on right
and is assignment to the same.
HxF a M);& expands to a ) a M ;&
M= =it%ise M(6B+ operation on the value of the variable on left by value on right
and is assignment to the same.
HxF a M=>& expands to a ) a N ;&
%onditional Assignment)
N = has three operands. The first operand is a condition. Second and third are t%o
values. The assignment returns second argument if the condition is true else
returns third argument if the condition is false.
HxampleF b=18& c=>8&
a=(bJc)N b=c&
The value b is assigned if bP c else c is assigned.
3o% b P c is false. 9ence value of c i.e ;E is assigned to a.
String operators - Concatenation operator is the only operator for strings
String s&
s = !Oello% F !Porld%&
Concatenation operator has precedence of A and is left associative.
13
Special operators
-ype %ast Operator Converts one data type to otherF This is generally used %hen a
value of one type has to be assigned or passed to a variable of another type. The Cast
operator is formed by placing parentheses around a data type name. The cast operator is a
unary operator$ i.e.$ an operator that ta'es only one operand.
Cast operators associate from right to left and have the same precedence as other unary
operators such as unary 2
HxampleF long a=QEDR&
int b=(int) a&
The java compiler only 'no%s ho% to evaluate expressions in %hich the data types of the
operands are identical. To ensure that the operands are of the same type$ the compiler
performs an operation called promotion (also called implicit conversion+ on selected
operands. Gor example$ in an expression containing the data types int and double1 int
operands are promoted to double.
8hen promotion is not allo%ed type casting is used$ because %ithout them data might be
lost. 9o%ever %hen higher precision values li'e double or long are type casted by float or
int respectively$ values get changed if they are more than their maximum values.
Operator Precedence F Java %ill evaluate expressions in parentheses as a single unit.
6perator precedence is similar to C li'e multiplication has higher precedence than
addition.
Operator2s associati#ity) #f t%o operators have same precedence$ then associativity is
used to evaluate the expression.
Operator Precedence %hart
Operator -ype Asociati#ity
( + parentheses left to right
S T array subscript
member selection
14
"" unary preincrement right to left
"" unary postincrement
2 2 unary predecrement
22 unary postdecrement
" unary plus
2 unary minus
U unary logical negation
2 unary bit%ise complement
(type+ unary cast
R multiplication left to right
! division
V modulus
" addition left to right
2 subtraction
OO bit%ise left shift left to right
PP bit%ise right shift %ith sign extension
PPP bit%ise right shift %ith ?ero extension
O relational less than left to right
O) relational less than or e<ual to
P relational greater than
P) relational greater than or e<ual to
instanceof type comparison
Operator -ype Asociati#ity
) ) relational is e<ual to left to right
U) relational is not e<ual to
L bit%ise /31 left to right
M bit%ise exclusive 6B left to right
boolean logical exclusive 6B
N bit%ise inclusive 6B left to right
15
boolean logical inclusive 6B
LL logical /31 left to right
NN logical 6B left to right
W F ternary conditional right to left
) assignment right to left
") addition assignment
2) subtraction assignment
R) multiplication assignment
!) division assignment
V) modulus assignment
L) bit%ise /31 assignment
M) bit%ise exclusive 6B assignment
N ) bit%ise inclusive 6B assignment
OO ) bit%ise left shift assignment
PP ) bit%ise right shift %ith sign extension assignment
PPP) bit%ise right shift %ith ?ero extension assignment
16
S T A T E 4 E N T S
3loc4s And Statements
Methods5"unctions6 in Java are defined by bloc's of statements. / bloc' is a se<uence of
statements enclosed in curly braces XY . / statement can again be a bloc' statement.
$mpty StatementsF
#t is legal to create empty statements in Java.
Labelled StatementsF
/ny statement in Java can have a label. The label has the same properties as an identifier.
#t cannot have same name as an existing label or a reserved %ord. The label is follo%ed by
a colon.
$&le)
(irst=
a = b Fc&
d = eF(&
second= w5ile(i K >8){
Systemoutprintln(!iteration num=% F i)&
iFF&
i( (i K 18) continue second&
iFF&
i( ( i J 1R) break (irst&
'
Declaration Statements
The general syntax for the variable declaration has the formF
[modi(ier] 6ypename variablename [initialiSation] &
ModifiersF public* protected* private* or sync5ronised
$&pression Statements F
Statements %hich can be used as part of expressions called expression statements. Java
specification lists seven 'inds of expression statements.
1$
/ssignment F : = 9& 11assigns value 9 to : and value o(
e:pression is also 9
re2increment F FFa& 11 same as a=aF1 and value o( e:pression
is incremented value o( a
re2decrement F --a& 11same as a=a-1 and value o( e:pression is
decrement value o( a
ostincrement F aFF& 11same as a=aF1 and value o( e:pression is
same as o( a
ostdecrement F a--& 11same as a=a-1 and value o( e:pression is
same as o( a
Method call F accnt(1(>88*18)&
/llocation F score = new byte[>8]&
expression
Selection statements )
Three selection statements are available F
i+ i"
ii+ i"-else
iii+ s7itch
i" Statement
The statement executes a bloc' of statements depending on %hether a condition is true or
false.
Synta& )
i( (condition) {block' - /( t5e condition results in a true
value* t5en t5e {block' statements
are e:ecuted
i( (condition) {block1' - /( t5e condition results in a true value
t5en t5e statements in {block1'
will be e:ecuted*
else {block>' - else t5ose in {block>' will be
e:ecuted
Example :
i( (basic J 1>88)
incometa: = basic 2 18 1188&
else
incometa: = 8&
1%
S2!t., tate-e"t:
s%itch statement selects one from many alternatives(case values+. Gor each value of the
expression$ respective set of statements are executed. #f the expression value does not
exist in the list of alternatives$ then the default case bloc' is executed. #f t%o case values
are not separated by brea'$ the control falls through. #f a bloc' is common to more than
one case value$ then it may be given after the last case value. The expression and case
values must evaluate to integral data types.(byte$ short$ char or int+.
Syntax :
switc5 (e:pression) {
case value1= {block1'
break&
case value>= {block>'
break&
case value?= {block?'
break&
de(ault= {blockn'
'
Example :
switc5( option ) {
case AaB = Systemoutprintln(!append%)&break&
case AcB = Systemoutprintln(!create%)&break&
case AdB = Systemoutprintln(!delete%)&break&
case AlB =
case AtB = Systemoutprintln(!listing%)&break&
case AeB = e:it()&break&
de(ault = Systemoutprintln(!Prong c5oice%)&
'
-or t5e case AlB t5ere is no block given 65en t5e block given under
case AtB is e:ecuted /ndirectly we instruct t5at* w5en t5e c5oice is
eit5er AtB or AlB e:ecute t5e same block
Ite'at!(" State-e"t #
The iteration statements execute a statement or a bloc' statement more than once.
Three types of iteration statementsF while, do and for are similar to those in C
language. continue and break statements have labels %hich defines the next point
control .
1+
While F The while statement executes the statements enclosed in the bloc' as the
condition is true.
Synta& F w5ile (condition) { block'
$&le ) rogram to read a character from 'eyboard and display message
corresponding to the character read. The loop terminates %hen character < is piped.
Source (ile = +:P5ilejava
public class +:P5ile {
public static void main(String args[])
{
option =A A&
w5ile( option $= ALB) {
try {
option = Systeminread()& 11reads a c5aracter (rom t5e key board
switc5( option ) {
case AaB = Systemoutprintln(!append%)&break&
case AcB = Systemoutprintln(!create%)&break&
case AdB = Systemoutprintln(!delete%)&break&
case AlB = Systemoutprintln(!listing%)&break&
case AeB = e:it()&break&
de(ault = Systemoutprintln(!Prong c5oice%)&
'
' catc5(/0+:ception ioe){'
'
'
Note = Ho not worry about t5e try, catch. 8ill be covered in the coming
chapters.
do-while iteration F
The do while statement executes the statements enclosed in the do bloc' and tests the
condition given %ith while. The loop body is repeated till the condition is true.
Syntax = do { block ' w5ile (condition)&
21
Example: #rogram to read a c5aracter (rom keyboard and display message
corresponding to t5e c5aracter 65e loop terminates
w5ere
input c5aracter is ALB
Source (ile = +:HoP5ilejava
public class +:HoP5ile {
public static void main(String args[])
{
try {
do
{
option = Systeminread()&
11reads a c5aracter (rom t5e key board
switc5( option ) {
case AaB = Systemoutprintln(!append%)&break&
case AcB = Systemoutprintln(!create%)&break&
case AdB = Systemoutprintln(!delete%)&break&
case AlB = Systemoutprintln(!listing%)&break&
case AeB = e:it()&break&
de(ault = Systemoutprintln(!Prong c5oice%)&
'
' w5ile( option $= ALB)&
' catc5(/0+:ception ioe){'
'
'
Note = Ho not worry about t5e try, catch. 8ill be covered in the coming
chapters.
for loop )
65e (or loop e:ecutes t5e statements in t5e block .e(ore t5e actual
loop starts* t5e assignment statement is e:ecuted and t5en t5e
statements in t5e block are e:ecuted as long as t5e boolean e:pression
is true and (or eac5 iteration completed* t5e second statement is also
e:ecuted
Syntax
(or(assignment statement& boolean e:pression& assertive
statement)
{ block '
+:ample = 65e (ollowing block statement prints t5e multiplication
table (or t5e number 18
(or(i=8&iK=18&iFF) {
Systemoutprintln(!18 : ! F i F ! = ! F i218 F %Cn%)&
'
21
+:ample = Sum o( t5e integers (rom 1 to 18 -----
Source -ile : Sumjava
public class Sum{
public static void main(String[] args) {
int i* sum=8&
(or(i=8&iK=18&iFF) {
sum=sumFi&
Systemoutprintln(!Sum o( 18 natural
3umbers is ! F sum)&
'
'
'
Example = SLuares and cubes o( numbers
Source -ile : SLrs4ubejava
public class SLrs4ube{
public static void main(String[] args) {
int i* sLuare*cube&
(or(i=8&iK=18&iFF) {
sLuare=i2i&
cube=i2i2i&
Systemoutprintln(!SLuare is ! F sLuare F
!4ube is ! F cube)&
'
'
'
22
A R R A Y S
/n array is an indexed collection of variables of same type that can be referred by a
common name. The type can be primitive data type li'e int or an object li'e String. /n
array is an object$ and is handled by reference. There are three steps in creating an array.
R declaring an array R allocating the memory R populating it.
#t is possible to do in one or more of these steps in the same statement.
There are t%o formats of declaring an /rrayF
utting the brac'ets after the data type
- int[] myintvalues& 11de(ines an array o( integers
ut the brac'ets after the array name
- int myintvalues[]& 11 de(ines an array o( integers
/ multidimensional array is implemented as an array of arrays.
- int[][] matri:= new int[?][?]& 11 de(ines a two
dimensional array o( siSe ? : ?
$&lesF
1 long primes[] = new long[1888]& 11declare and assign memory
long[] +ven#rimes = new long[1]& 11declare and assign memory
+ven#rimes[8] = >& 11)ssign value to array
elements
> long -ibonacci[] = {1*1*>*?*D*Q*1?*>1*?E*DD*Q9*1EE'&
11declare and populate array partially
? long per(ects[ ] = {R*>Q'& 11declare and populate a two element
array
E long .lack-ly3um[]& 11declare an array not populated 5ence
null values
D long 6ower0(Oanoi[][] = { {18*9*Q*@*R*D*E*?*>*1'*{'*{''&
11declare a two dimensional array and
populate
R int[] row1 = {11*1>*1?'& 11declare an ? element array and
populate
int[] row> = {>1*>>*>?'& 11declare an ? element array and
populate
int[] row? = {?1*?>*??'& 11declare an ? element array and populate
int[][] matri: = new int[?][]& 11declare and assign memory to a
two d dimensional array
23
matri:[8] = row1&
matri:[>] = row>& 11populate rows o( two dimensional
arrays wit5 single
dimensional arrays row1*
row>* row? de(ined above
matri:[?] = row?&
@ long[][] 6wodobjs& 11declare a two dimensional array
o( long values
long[] (irst = new long[E]& 11declare and assign an array
o( long values
long[] second = new long[D]& 11declare and assign an array
o( long values
6wodobjs = new long[>][]& 11)ssign memory to >-d array
de(ined above
6wodobjs[8] = (irst& 6wodobjs[1] = second
11 populate above >-d array wit5 1-d
11 arrays (irst and second de(ined
above
#ndexing of array starts from E. /n array can be partially populated on initialisation. /rray
indexes must be type castable to int.(*; bit integer+.
Di""erences in Arrays bet7een % or %88 and JAVA
#n Java array must be created dynamically using ne% command. /n array in Java is an
object variable and not a pointer as in C or C"". #n Java an array element that has not
been created cannot be referenced$ because memory is protected.
$&le F Sum of the elements of an array 22
SourceGile ) ArraySum.java
public class )rraySum{
public static void main(String[] args) {
int a[]={18*>8*?8*E8*D8*R8*@8*Q8*98*188'&
int total=8&
(or(int i=8&iKalengt5&aFF)
totalF=a[i]&
Systemoutprintln(!Sum o( elements o( )rray is ! F
total)&
'
'
24
$&le F 0sage of string arrays 22
SourceGile F 8elcome.java
public class Pelcome {
public static void main(String[] args) {
String greeting[]new String[?]&
greeting[8]= !"ava is %&
greeting[1]=!0bject 0riented %&
greeting[>]=!;anguage%&
(or(int i=8&iKgreetinglengt5()&iFF)
Systemoutprintln(greeting[i])&
'
'
!"#!"= "ava is
0bject 0riented
;anguage
J5-p State-e"t #
Java has four 'inds of jump statementsF brea41 continue1 return and thro7
brea4 statement)
/n unlabelled brea' statement passes control to the next line after the current(inner most+
iteration or s%itch statement. 8ith a label the control is passed to the statement %ith that
label in the current method. The brea' %ith label %or's similar to a goto statement %hich
is not available in Java.
$&le F#llustrates the use of brea'&
w5ile (a K b) {
statement1&
statement>&
i( (condition)
break&
statement?&
statementE&
'
statementD&
The brea' statement in the %hile$ transfers the control out of the w5ile loop. The
statements statement*$ and statement> are not executed and the loop terminates i.e
statementA is executed.
25
$&le) The program executes the %hile loop until a becomes e<ual to A and then exits
from the loop. The statement s=sFa2D is not executed.
SourceGile F =rea'Test.java
public class .reak6est {
public static void main(String []args){
int a=1* s=8&
w5ile (aK18){
i( (a==D)
break&
s = s F a2D&
Systemoutprintln(Ta is TFaFT and s is TFs)&
aFF&
'
Systemoutprintln(T65e loop stopped at TFaFTand
t5e sum is TFs)&
'
'
6utput F
a is 1 and s is 5
a is 2 and s is 15
a is 3 and s is 30
a is 4 and s is 50
The loop stopped at 5 the sum is 50
continue Statement)
/ continue statement may appear only %ithin the bloc' of an iteration statement. The
effect of unlabelled continue statement is to s'ip through remaining statements of the
bloc' for current iteration and start next iteration through the same loop. The labelled
continue statement facilitates programmer to choose %hich iteration of the nested
iterations to return StatementF
$&le F The continue statement in the %hile transfers the control to the %hile loop.
The statements statement*$ and statement> are not executed.
w5ile (a K b) {
statement1&
statement>&
i( (condition)
continue&
statement?&
statementE&
Y
26
$&le) The program executes the %hile loop. 8hen a e<uals A then remaining
statements in the loop are s'ipped.
SourceGile F ContTest.java
public class ContTest.java{
public static void main(String []args){
int a=8* s=8
w5ile (aK18){
aFF&
i( (a == D)
continue&
s=sFa 2 D&
Systemoutprintln(Ta is TFaFT and s is TFs)&
'
Systemoutprintln(T65e loop skipped D t5e sum is TFs)&
'
'
6utput F
a is 1 and s is 5
a is 2 and s is 15
a is 3 and s is 30
a is 4 and s is 50
a is 6 and s is 80
a is 7 and s is 115
a is 8 and s is 155
a is 9 and s is 200
a is 10 and s is 250
The loop skipped 5 the sum is 250
MethodsF
Methods allo% the programmer to modularise a program. These programs modules are
executed %hen they are exclusively called. /ll variables declared in method definitions are
local variables. Methods have a list of parameters that provide the means for
communicating information bet%een methods.
.ormatF return-value-type met5od-name (parameter list)
{
declarations and statements
'
2$
return2value2type is the data type of the result value returned from the method to its caller$
The data type can be any basic type or an object of a class. The data type void indicates
that a method does not return a value.
Method name is any valid identifier.
arameter list if any$ is a comma2separated list containing the declarations of the
parameters received by the method %hen it is called.
A return statement)
This statement passes control to the caller of the method$ constructor or static initiali?er
containing the return statement. #f the return statement is in a method that is not declared
void$ it may have a parameter of the same type as method.
Synta& ) return (value)&
$&le) / method get/nterest() to calculate the interest given principal $ rate of
interest and time periods. The return statement passes the interest calculated to the
main() method.
SourceGile F /ccount.java
public class Account{
public double get/nterest(double rate* int principal* int period){
double interest=8&
i( (rate K= 8)
return (8)&
interest = (principal 2 rate 2 period)1188&
return (interest)&
'
public void printUalue (double d) { Systemoutprintln (d)& '
public static void main(String args[]){
)ccount accnt = new )ccount()&
double rt=188*intrest&
int amnt=1>88*terms=D&
intrest= accntget/nterest(rt*amnt*terms)&
Systemoutprint(T/nterest (or #rincipal TFamnt)&
Systemoutprint(T V TFrt)&
Systemoutprint(T in TFtermsF T terms is T)&
accntprintUalue(intrest)&
'
'
6utputF
/nterest (or #rincipal 1>88 V 188 in D terms is R888
%alling a Method)
2%
/ method can be called in t%o %ays. / method %hich has valid return type is called as a
part of an expression. Methods %hich have void return type are called as individual
statements.
HxampleF Statements from above program.
getInterest() method is called as a part of expression
double interest&
interest = accntget/nterest (>D* E888*?)&
%here as printUalue() is called as a single statement
accntprintUalue(interest)&
4et,(6 O7e'/(a6!"3:
Java allo%s several methods of the same name to be defined as long as these methods have
different sets of parameters 2 based on the number of parameters$ types of parameters and
order of parameters. Method overloading is commonly used to create several methods of
the same name that perform similar tas's$ but on different data types 2 Compiler selects
the proper method.
$&le)
T%o methods %ith the same name s<uare are defined each %ith parameters of different
data type. =oth are called by the same name but %ith different type of arguments i.e. one
%ith integer$ other %ith double.
Source F S<uares.java
public class SLuares{
public int sLuare (int pint){
int sLr&
sLr = pint 2 pint&
return sLr&
'
public double sLuare (double pdouble){
double db&
db = pdouble 2 pdouble&
return (db)&
'
2+
public static void main(String []args){
SLuares sL = new SLuares()&
int sLrint&
double sLrdb&
sLrint = sLsLuare(>DR)&
sLrdb = sLsLuare(>DR)&
Systemoutprintln(!SLuare root o( >DR is %F sLrintF%
>DR is !FsLrdb)&
'
'
31
OOP N JAVA
Java is totally object2oriented. #t is not possible to program it in the procedural style. /ny
66 language has four 'ey concepts to implement 2vi?.$ Abstraction1 $ncapsulation1
nheritance and Polymorphism ,
$ncapsulation F
8rapping up the data and the functions together into a single unit is called encapsulation.
The data is accessible only by the functions in the class. These functions provide the
interface bet%een the objects data and the program. This insulation of the data from
direct access by the program is called data hiding.
Abstraction F
/bstraction refers to the act of representing essential features %ithout including the
bac'ground details or explanations.
nheritance F
#nheritance is the process of creating a ne% class called the derived class$ from an existing
class called the base class. 8hen a class is inherited from a base class$ the data and the
methods defined in the base class are also inherited. The advantage of having inheritance is
reusability of classes.
Polymorphism )
The %ord olymorphism is derived from t%o :atin %ords poly(many+ and
morphos(forms+. olymorphism means the ability to ta'e more than one form. Gor
example area of different shapes is referred by the same name area. =ut the procedure is
different for different shapes. 9ence the same name area has different forms.
%lass )
/ collective term for data types and operations bundled together %ith access restrictions.
#ndividual elements in a class are called "ields1 or data members or instance #ariables
and operations!functions are called methods. #nstance variables can be of any basic data
type or objects of other classes.
%lass declaration )
The basic class declaration has the follo%ing form. The datatype given belo% may be any
one of the basic data types or a class defined in Java .
31
.ormat)
[modi(ier] class classname
{
modi(ier datatype dataWvariable1&
modi(ier datatype dataWvariable>&
modi(ier datatype dataWvariable?&
'
/ class to be executed as a program should contain a method %ith name main$ and is
defined as belo%.
public static void main(String args[])
{
11 met5od de(inition
'
Modi"iers )
Modifiers effect accessibility$ storage and lifetime of classes$ methods$ variables.
/ccessibility modifiers effect the accessibility of the instance variables and methods. There
are three modifiers %hich %hen applied$ control accessibility of member variables$
methods$ and classes. They are default1 public1 protected1 pri#ate1 pri#ate protected.
9aving no modifier comes under default accessibility mechanism.
32
public)
This ma'es the class visible to all the other classes. Zenerally methods %hich are provided
for the use in other classes or programs are defined %ith public modifier.
$&le ) The belo% declarations specify that the methods set6ime() and print6ime
() can be called in any method of any class or program.
public set6ime( int 5* int m* int s)
public void print6ime ()
pri#ate)
The private modifier ma'es variables and methods available only %ithin that class.
Zenerally the instance variables are defined %ith this modifier. Gunctions %hich are to be
used only by the methods of that class are also defined %ith pri#ate modifier.
Hxample F The private modifier in declarations say that the variables hour, minute,
second and the method setHour() can only be accessed by the member functions of
the class only.
private int 5our&
private int minute&
private int second&
private void setOour(int 5)
{
11 met5od de(inition
'
De*a5/t (' *'!e"6/y a..e!8!/!ty #
#n fact there is no modifier called [default accessibility [ modifier but this is assumed %hen
there is no modifier specified. The classes %ith [default accessibility modifier are
accessible %ithin the pac'age. The variables %ith default accessibility are accessible to all
classes %ithin the pac'age. =ut they are not accessible outside the pac'age even if it
happens to be a subclass of the class in %hich the variable is declared. The behaviour for
methods is same as variables %ith default accessibility.
$&le) The variables x and s can be accessed by any method of any class in the
pac'age
int x;
String s;
33
O89e.t#
6bject is the runtime entity in a Java program. #t contains a copy of instance variables. /
class can have more than one instance i.e. more than one object of a class can be defined.
#nstances!objects of a class are to be created using a ne7 operator. This creates a ne%
object by allocating the memory re<uired.
O89e.t 'e*e'e".e #
8ith new operator the objects are just created. The object cannot be used until a reference
is created. Beference to an object is created by assigning the object to a variable of the
class type. These variables are called the object references.
$&le F The declarations belo% are explained in comments.
4ircle c1&
11de(ines c1 as a variable t5at re(ers to any object o( class 4ircle
c1 = new 4ircle()&
11creates an object o( t5e class 4ircle and assigns it to variable c1
4ircle c> = new 4ircle()&
11de(ines and creates an object variable c> o( class 4ircle
The variables c, and c; are reference variables to objects created by new operator
class
data member,
data member>
Get5od1
Get5od>
0bject1 0bject>
data member1 data member1
data member> data member>
$ccessin% the instance variables and methods: )ny met5od1instance
variable is accessed in t5e (ollowing (ormat=
objectinstanceWvariable&
objectmet5od(parameters)&
34
Example = He(ining a class circle wit5 radius as instance variable
(or calculating t5e radius o( a circle
Source-ile = 4irclejava
public class 4ircle {
private double radius&
public 4ircle(){
radius=8& '
public 4ircle(double pWradius) {
radius = pWradius&
'
public double get,adius(){
return radius&
'
public double area() {
return (?1E 2 radius 2 radius)&
'
public static void main(String args[]){
4ircle a = new 4ircle(18)&
double rad* area1&
rad = aget,adius()&
area1 = aarea()&
Systemoutprintln(T)rea is = TFarea1)&
'
'
!"#!"=
,adius is = 18
)rea is = ?1E
#n the above class %e have defined a class Circle %ith radius as the instance #ariable
and methods area() *get,adius() and lastly the main() method to execute the
class.
35
C O N S T R U C T O R S
/ constructor is a special method that initiali?es the instance variables. The method is
called automatically %hen an object of that class is created and has the follo%ing
properties.
/ constructor method has the same name as the that of the class.
/ constructor al%ays returns objects of the class type hence there is no return type
specified in its definition.
E / constructor is most often defined %ith the accessibility modifier 5public7 so that
every program can create an instance but is not mandatory.
/ constructor is provided to initialise the instance variables in the class %hen it is
called. This is to prevent the code from having uninitialised instance variables and
hence have a clear set of values.
#f no constructor is provided$ a de"ault constructor is used to create instances of the
class. / default Constructor initialises the instance variables of the class %ith 0 for
numeric data type $ "alse to booleans and null for the reference variables.
Gunction overloading enables to %rite more than one constructor %ith a variation in
the number of parameters or type of the parameters. The parameters are used for the
initialisation of the instance variables.
public 4ircle(){ radius = 8&'
public 4ircle(double pWradius) {
radius =pWradius&
'
tat!. -(6!*!e' #
/ static class member represents class2%ide information. / copy of a static member is
shared by all objects of a class. The static member of a class can be referred by class
name. 9ence no object (or object reference+ needed to access a static member. The
declaration of a static member begins %ith 'ey%ord static.
(sage o" static :
.or instance #ariables F
Hach instance of a class has its o%n copy of member variable and a pointer to the
methods. That is a variable belongs to an object of the class. 8ith static as a modifier the
instance variable is designated as belonging to class itself. Gor the total definition of the
class the static instance variable has only one copy. That is same value is obtained for any
instance of the class.
$&le) The belo% declarations say that pi is static instance variable o(
t5e class Circle. )nd it 5as a value o( ?1E 65e instance variable pi
36
is available to met5ods o( any class and gives t5e same value w5ere
ever accessed
public static double pi=?1E&
area = 4irclepi 2 radius 2 radius&
.or methods =
Methods are normally invo'ed on objects and operate on instance variables of that
instance(object+ and is called %ith the object. 9o%ever it is possible to %rite methods that
are accessible on a per class basis i.e.$ the method has only one pointer to the function and
the method can also be called %ith the name of the class.
$&le) public static int get4ount()& 11static met5od
if c, and c; are objects of class Circle$ then get4ount() can be called as
4ircleget4ount()&
or
c1get4ount()&
or
c>get4ount()&
t,! Re*e'e".e:
5this7 is a reference to the object itself.
this is used to refer to the current instance %hen
it has to be passed as a parameter to any another method called %ith in the
object.
the parameters passed have the same name as that of the instance variables so
as to avoid ambiguity.
another object of same class is passed as parameter to the current method.
$&le) #n the method get,adius() the current instance of the object is referred by
this.
3$
public double get,adius(){
return t5isradius&
'
public void set,adius(int radius){
t5isradius = radius&
'
public boolean 5asSame)rea)s(4ircle a){
return (t5isarea == carea())&
'
The method areH<ual(+ ta'es t%o instances of the class Circle and returns true
i( bot5 t5e instances o( t5e Circle are eLual by seeing i( t5ey 5ave
same radius
public static boolean are+Lual(4ircle c1* 4ircle c>) {
return (c1get,adius() == c>get,adius())&
'
8e can define a method isH<ualto %hich ta'es one instance of a circle returns true if the
current object is e<ual to given circle in the parameter. The method just calls the static
method areH<ual by passing the current object and the object given by the parameter
%here the current object is represented using this.
$&le) The method isH<ualto ta'es an object of Circle one argument and uses
the above defined method are+Lual() and uses the this to refer to the current object
public boolean is+Lualto(4ircle cr) {
return (4ircleare+Lual(t5is*cr))&
'
this is also used in constructors. #n the Circle class above the constructors are defined as
belo%.
The same could be defined as belo%
public 4ircle(){ t5is(88)&'
public 4ircle(double pWradius) {
radius =pWradius&
'
3%
3o% the default constructor uses this and passes an argument to it invo'ing a call to the
second constructor. #n this case this acts as a call to a consturctor of the same class %ith
the method definition.
*!"a/ -(6!*!e' #
"or #ariable 2 #t declares them as constants and cannot be altered throughout the
program
$&le F #n the declarations belo% the instance variable pi is de(ined to be
(inal 5ence cannot be c5anged by any met5od o( t5e class
public (inal double pi=?1E&
area = 4irclepi 2 radius 2 radius&
"or methods 2 #ndicates that the method can not be redefined$ that is$ it cannot be
overloaded.
$&le) The declaration say that the method area()cannot be overridden
public (inal double area()
"or class 2 #ndicates that the class cannot be further extended or there cannot be any
subclass of this class,
$&le) The declaration of the class Cylinder indicates that the class Cylinder
cannot be extended further.
public (inal 4ylinder
F!"a/!:e'#
8hen an object of a class is loosing its scope then it may need to do some clean up steps.
Gor this purpose a (inaliSe() method may be defined in the class as
public void (inaliSe(){ '
) (inaliSer receives no parameters and returns no value
65e code given in t5e met5od is e:ecuted be(ore t5e object is removed
(rom t5e memory 4oding (inaliSe() method has to involve certain precautions as the
context of its running is not explicitly 'no%n.
Va'!a8/e Re*e'e".e- Ga'8a3e :
/ variable is a reference to an object of specified class, Sometimes a variable is created
and is not used temporarily i.e.$ the memory allocated is unutilised and hence is %asted.
$&le )
4ircle -irst4ir* Second4ir &
3+
11-irst4ir and Second4ir 5old objects o( class 4ircle and initially
11re(er to null
-irst4ir =new 4ircle(18)&
113ow -irst4ir is re(ering to a circle o( radius 18
Second4ir = -irst4ir&
113ow -irst4ir* Second4ir re(er to t5e same object 5aving radius 18*
-irst4irset,adius(>8)&
11-irst4irXs radius is set to >8 and 5ence t5e Second4irBs radius
11is also set to >8 since bot5 re(er to t5e same object
Systemoutprintln(Tsecond radiusT F Second4irget,adius())&
!"#!"= second radius >8
The above code demonstrates that both refer to the same object and to the same memory
location and hence fine.
$&le)
The .irst%ir and Second%ir refer to t%o Circle objects. #n the fourth statement both
.irst%ir and Second%ir refer to the same Circle object of radius ;E. The Circle object
of radius ,E is no more accessible as there is no variable holding reference to it. but
occupies memory. So the Circle object of radius ,E is no% a %aste and not needed by the
system. Java automatically reclaims memory not used by any object.
4ircle -irst4ir*Second4ir&
-irst4ir = new 4ircle(18)&
Second4ir = new 4ircle(>8)&
-irst4ir = Second4ir&
8hen no object variable refers to an object$ the memory occupied is called as 9arbage
and process of regaining such memory is 'no%n as Zarbage Collection. The garbage
collection process is run by the Ja#a Virtual Machine5JVM6. Zarbage collection can
also be done in a program %hile execution by a method Systemgc()
Systemgc() is an explicit call to garbage collector to execute it as soon as it can.
41
$&le) The program to illustrate explicit invo'ing of garbage collector gc()
method.
Source F Hmployees.java
public class +mployees {
private String (irst3ame&
private String last3ame&
private static int count&
public +mployees(String (3ame* String l3ame) {
(irst3ame=(3ame&
last3ame=l3ame&
FFcount&
Systemoutprintln((irst3ameFT TFlast3ameFT TFcount)&
'
public void (inaliSe() {
--count&
Systemoutprintln(T-inaliSerTF(irst3ameFT TFlast3ameFT T
Fcount)&
'
public String get-irst3ame() {
return new String((irst3ame)&
'
public String get;ast3ame() {
return new String(last3ame)&
'
public static int get4ount() {
return count&
'
public static void main (String[] args) {
Systemoutprintln(T3oo( +mployeesTF+mployeesget4ount())&
+mployees el=new +mployees(T,amaT* TYris5naT)&
+mployees e>=new +mployees(TYris5naT* TYumarT)&
Systemoutprintln(T3oo( +mployeesTFelget4ount())&
el=null&
e>=null&
Systemgc()&
Systemoutprintln(T)(ter garbage 4ollection=T F
+mployeesget4ount())&
'
'
41
utput :
3oo( +mployees8
,ama Yris5na 1
Yris5na Yumar >
3oo( +mployees>
-inaliSer,ama Yris5na 1
-inaliSerYris5na Yumar 8
)(ter garbage 4ollection=8
The program creates t%o strings e,$ e;. /fter creation the count is ;. :ater the e, and
e; are referenced to null. Then the call to Javas garbage collector removes the memory
occupied %ithout being referenced. =efore the data in memory is destroyed the finali?e
method is called %hich updates the counts value. 3o% the count value is E as there are
no Strings in memory.
I",e'!ta".e #
#nheritance is a form of soft%are reusability$ in %hich ne% classes (derived!subclass+ are
created from existing classes (parent!super!base class+ by inheriting their datamembers
and methods in the ne% class.
Consider a class called uardilateral. / Bectangle also is a <uardilateral. 9ence a class
!ectangle can be said to inherit!define from class uardilateral. Similarly this classes li'e
"quare# !hom$us etc.
\uadrilateral /ccount
Bectangle S<uare Bhombus Savings Current
/ccount /ccount
.ormatF class derived class name extends base class name
$&le)
class ,ectangle e:tends Zuadrilateral
- class !ectangle is derived from class uadrilateral
class Savings)ccount e:tends )ccounts
- class "avings%ccount is derived from class %ccounts
42
super 56 )
super is a reference to the parent classs constructor %ithin the code of a deri#ed class2s
constructor. This is called in the derived classs constructor$ to initialise the instance
variables of the parent class1 before the instance variables of the derived class.
super,method5param+1 param:1 ,,6 refers to the method defined in the parent class.
This is the procedure to call a method of the parent class in a method of the derived class.
1ata references are resolved at compile time. #f a member variable %ith same name is
available in both the super class and also in the derived class$ then the member of the
derived class is accessed. The member may be an instance variable or method.
4et,(6 (7e''!6!"3#
6verriding is a process of redining a super calss method in a subclass. The method in sub
class is said to override the method of super calss.
Gor example if a class Circle defines a method %ith signature
public class 4ircle {
public double area() {
'
'
Then a class 4ylinder inheriting 4ircle class can redefine the same method %ith same
signature as belo%
public class 4ylinder e:tends 4ircle {
public double area(){
'
'
9ere the method area() defined in the 4ylinder class is said to override the method
area() in the 4ircle class. The definition may call the super classs method if re<uired
as explained in next section.
43
Ua3e (* 4(6!*!e' !" !",e'!ta".e
protected access modi"ier)
Serves as an intermediate level of protection bet%een public access and private access.
rotected members of a super class may be accessed only by methods of the super class$
by methods of subclasses and by methods of other classes in the same pac'age. 8hen
applied to methods and variables$ it ma'es the method or variable visible to all methods
and classes %ithin pac'age.
;pri#ate protected; - access modi"ier )
8ith this modifier the access of a method or an instance variable is accessable only to the
immediate derived class irrespective of %hether they are inside or outside the same
pac'age.
$&le "or inheritance)
The example defines a class Circle and derives another class Cylinder from Circle.
SourceGile F Cylinder.java
class 4ircle { 11base class
protected double radius&
protected (inal static double pi=?1E&
11constant t5roug5out t5e program
public 4ircle(){ radius = 8&' 11constructors
public 4ircle(double pWradius) {
radius =pWradius&
'
public double get,adius(){
return radius&
'
public double area() { 11calculation o( area o( circle
return (pi 2 radius 2 radius)&
'
'
public class 4ylinder e:tends 4ircle
{ protected double 5eig5t&
public 4ylinder(double r* double 5) {
super(r)& 11calling base class constructor
setOeig5t(5)&
'
public void setOeig5t(double 5){
5eig5t=(5J8N5=8)&
'
public double getOeig5t() {
return 5eig5t&
'
44
public double area(){ 11Get5od overriding
return >2superarea()Fsuperpi 2 radius 2 5eig5t&
11calling base class met5od area()
'
public double volume() { 11and data member pi
return superarea()25eig5t&
11calling base class met5od area()
'
public static void main(String args[]){
double area1* area>&
4ircle cr1 = new 4ircle(188)&
11object o( base class circle
4ylinder cr> = new 4ylinder(188*R8)&
11object o( derived class cylinder
area1 = cr1area()&
11calling base class met5od
Systemoutprintln(T)rea o( circle is = TFarea1)&
area> = cr>area()&
11calling derived class met5od
Systemoutprintln(T)rea o( cylinder is = TFarea>)&
'
'
O(-P(-F
)rea o( circle is = ?1E
)rea o( cylinder is = Q1RE
Abstract classes )
These classes generally have methods declared as abstract. This means that these methods
are not implemented and hence are to be implemented by their subclasses. These classes
act as the super class for a hierarchy of classes. /n abstract class must be defined %ith an
abstract modifier.
abstract - modi"ier)
for a class 2 indicates that the class is not fully implemented and so objects of this
class can not be instantiated. #f a class has an abstract method then no
object of that class can be instantiated 2 hence the class is automatically an
abstract class. /bstract classes are used to enforce common functionality
of objects instantiated from the classes that extend the abstract base class.
for a method 2 indicates that the function code is to be implemented in a class that
extends the class.
$&le F
45
/ circle$ a cylinder$ a rectangle$ a s<uare fall into a single category shape. 9ence an
abstract class called 5S5ape7 can be defined. The common function for all the above
shapes is area. 9ence the S5ape is defined as an abstract class %ith area() as an abstract
method.
SourceGile F Shape.java
abstract class S5ape{
abstract public double area()&
'
SourceGile= 4irclejava
class 4ircle e:tends S5ape {
private double radius&
protected static (inal double pi=?1E&
public 4ircle(){ radius = 8&'
public 4ircle(double pWradius) {
radius=pWradius&
'
public double getradius(){
return radius&
'
public double area() {
return (pi 2 radius 2 radius)&
'
'
SourceGile = SLuarejava
public class SLuare e:tends S5ape{
protected double widt5&
public SLuare(double w) {
widt5 = w&
'
public void setPidt5(double w) {
widt5=(wJ8Nw=8)&
'
public double getPidt5() {
return widt5&
'
public double area() {
return widt52widt5&
'
46
public static void main(String args[]){
double area1* area>&
4ircle cr1 = new 4ircle(188)&
SLuare cr> = new SLuare(D8)&
area1 = cr1area()&
Systemoutprintln(T)rea o( 4ircle is = T F area1)&
area> = cr>area()&
Systemoutprintln(T)rea o( SLuare is = T F area>)&
'
'
O(-P(- F )rea o( 4ircle is = ?1E
)rea o( SLuare is = >D
;(/y-('p,!- #
olymorphism is the feature by %hich objects respond in an appropriate fashion even
though the method called on them is the same. #n the example of finding the areas of
different shapes$ in all the cases the same name area is used to find its area. =ut the
method of finding the area for different shapes is different. That is the function is
referenced by the same name but the method implementation is different in each context.
This ability of behaving in different %ays in different contexts but still be referenced by the
same name is called as polymorphism.
olymorphism in J/./ is accomplished by three techni<ues. 3amely "unction
o#erloading1 inheritance and inter"aces,
I"te'*a.e:
#mplementing identically named member functions that ta'e identical arguments in
different classes. The main difference is though the names and arguments are same the
implementation of the methods is different in different classes.
#n Java a class can have only one immediate superclass. Multiple inheritance %here a class
has more than one super class is not supported in J/./. 9o%ever the re<uired
functionality is achieved by defining inter"aces. /n inter"ace is a collection of constants
and abstract methods. /n interface is similar to class in definition. =ut no method is
implemented in its definitions. 6bjects of type interface cannot be instantiated$ that is no
invocation using [ne%[ . /nd no constructor method for interface. /n interface only
defines the functionality and the functionality is to be implemented by some other class,
The classes that provide the functionality define the code for the abstract methods
specified in the definition of the interfaceF
4$
$&le) SourceGile F savings.java
inter(ace savings {
public void deposit(double d)&
public double calint()&
(inal double intWrate = 1E&
(inal double minWbal = 1888&
'
SourceGile F chec'ing.java
inter(ace c5ecking {
public void wit5draw(double d)&
'
SourceGile F savechec'.java
class savec5eck implements savings* c5ecking
public static void main(String[ ] args){
savec5eck c = new savec5eck(1* new String(!"o5n%)* 1888)&
cdeposit(D88)&
cwit5draw(188)& cs5ow()&
cwit5draw(E888)& cs5ow()&
'
public savec5eck(int i* String s* double amt) {
accno = i& name = s&
balance = amt&
'
public void wit5draw(double d) {
double di(( = balance -d&
i( (di(( K minWbal)
Systemoutprintln(!4annot Pit5draw ! F d)&
else balance = di((&
'
public void deposit(double d) {
balance F=d&
'
public void s5ow() {
Systemoutprintln(!)ccount 3umber = ! F accno)&
Systemoutprintln(!3ame = !F name)&
double netWbalance = balance F calint()&
Systemoutprintln(!6otal .alance = !F netWbalance)&
'
public double calint() {
double interest = balance 2 intWrate 1 1888&
return interest&
'
private double balance&
private String name&
private int accno&
'
4%
4+
;a.<a3e #
ac'ages are groups of related classes in J/./ similar to libraries in many languages. /
pac'age is a grouping mechanism %ith t%o main purposesF
2 Beduce the problems in name conflicts.
2 Control the visibility of classes$ interfaces and the methods and data.
The classes used in a program can be <ualified %ith the pac'age name %hen they are
defined. /n alternative %ay is to specify it through [import[ statement in the beginning of
the program$ the classes that are to be imported along %ith the pac'age name
<ualifications.
import Gat5s2 & 11 imports all classes de(ined in package Gat5s
/ pac'age may contain many classes. Hach file that sends classes into particular pac'age
should indicate the same by the [pac'age[ statement.
Source-ile = Gat5sjava in a directory myGat5s
11package - calc sLuare and cube o( numbers
package myGat5&
public class Gat5s {
public static double sLuare (double :) {
return :2:&
'
public static double cube(double :) {
return :2:2:&
'
'
Source-ile = Gat5sjava in parent directory o( GyGat5s* (or t5e usage
o( myGat5 package
import myGat52&
public class matest {
public static void main (String args[] ) {
double a=188* b=8&
b = Gat5ssLuare(a)&
Systemoutprintln(aF%=SLuare is !FGat5ssLuare(a))&
Systemoutprintln(aF%=4ube is !FGat5scube(a))&
'
'
!"#!": 65e SLuare o( 18 is 1888
51
Hvery pac'age is mapped to a directory name in the system. /nd it is possible to nest
pac'ages %ithin pac'ages similar to directory structure. / classname is <ualified by the
pac'age name separated by a [.[. / full pac'age name is indicated (if it is inside a nested
set of pac'ages+ by specifying all pac'age names from the top level$ each separated by a
[.[2 similar to directory path. /t Bun time the Java virtual machine traverses through the
pac'age structure. =y default the Java virtual machine loo's for the classes and pac'ages
in the current directory. /lternately it can loo' at other places indicated by a
C:/SS/T9 environment variable similar to /T9 variable for binary executables of
16S.
Some o" Ja#a AP pac4ages are)
javaapplet 2 The Java /pplet pac'age
javaawt 2 The Java /bstract 8indo%ing Tool'it pac'age
javaio 2 The Java #nput!6utput pac'age
javalang 2 The Java :anguage pac'age
javanet 2 The Java 3et%or'ing pac'age
javasLl 2 The Java S\: pac'age
javautil 2 The Java 0tilities pac'age
Ot,e' 4(6!*!e' a"6 ./ae
nati#e)
The native modifier applies to methods only. #ndicates that the method is coded in a
language other than J/./$ li'e C etc.. So a native method has no code bloc'. Methods
for math$ input!output etc. may need native coding.
$&le) public static native double sin(double a)&
transient)
is used in conjunction %ith serialisation$ if a class has variables that should not be
serialised$ they should be mar'ed %ith transient modifier. The serialisation process %ill
ignore them.
#olatile )
/ volatile variable is one %hose value may change independent of the Java program itself.
They are also used to flag variables that could be changed by other threads of execution.
0se of this is rare as it re<uires a special .irtual machine.
51
The %lass ;Object; F
Hvery class that %e create extends the class Object by default. That is the 6bject class is
at the highest of the hierarchy. This facilitates to pass an object of any class to be passed
as an argument to methods %hich accept a generic object. Gor example in utilities li'e
Hnumeration$ Stac' etc. The methods in this class areF
eLuals(0bject re() 2 returns if both objects are e<ual
(inaliSe( ) 2 method called %hen an objects memory is destroyed
get4lass( ) 2 returns class to %hich the object belongs
5as54ode( ) 2 returns the hashcode of the class
noti(y( ) 2 method to give message to a synchroni?ed methods
noti(y)ll( ) 2 method to give message to all synchroni?ed methods
toString() 2 return the string e<uivalent of the object name
wait() 2 suspends a thread for a %hile
wait() 2 suspends a thread for specified time in seconds
The %lass 2 [ %lass [
Hvery object in J/./ has a %lass descriptor object associated %ith$ describing the class
to %hich it belongs. The %lass descriptor objects are of type [%lass[. The methods
available on these are F
get3ame() - gives t5e name o( t5e class
getSuper4lass() - gives name o( parent class i( t5ere e:ists one
toString() - converts t5e data o( t5e class into a string
is/nter(ace() - tells (boolean) w5et5er it is an inter(ace
get/nter(aces() - gives an array o( inter(aces(o( type 4lass)
implemented by t5e class
The class [%lass[ also has a static method (or3ame(String classname) %hich
instantiates a class descriptor object for the class given by classname parameter. This is
useful to 'no% information about certain dynamically loaded drivers.....
get4lass;oader() returns the description of the class:oader that loads the class.
65e 4lass;oader() is an abstract class %hich is extended and implemented by the Java
.irtual Machine.
52
A=T - A8t'a.t =!"6(2 T((/<!t
I"t'(65.t!("
/ Zraphical 0ser #nterface (Z0#+ gives a pictorial #nterface to a program. Java gives a
class library for basic Z0# progamming called java.a%t pac'age. The /8T has most of
the graphical components that are standard in Z0#s. /8T provides several major
subsystems that support the development of Z0# programs.
These su$systems are &
Zraphic primitives that allo% dra%ing and rendering of lines and images
Components li'e labels$ buttons and text fields$
Containers li'e frames$ panels and dialogs$
layout managers that control the appearance of display
The event system$ to respond to interactions bet%een the components and containers
in the application.
C/a ,!e'a'.,y #
Object %omponent %ontainer Panel Applet
<indo7 .rame
Dialog
3orderLayout 3utton
.lo7Layout %hec4bo&
9ridLayout %hoice
%ardLayout Label
9rid3agLayout List
Scrollbar
-e&t%omponent -e&t .ield
-e&t Area
53
Containers :
/ Container groups components and treats the group as a unit. Typically a container ta'es
on the appearance of a %indo% that holds components and that %hich can be moved$
resi?ed$ minimi?ed and restored by users. The container is itself an /8T component.
%ontainer class %hich is a subclass of Component class is an abstract class. The %indo%
class itself although not an abstract class is rarely used$ because its t%o children Grame and
1ialog provide so much more builtin functionality.
Graming the applications F
/ top level %indo% is a %indo% that is not contained inside any other %indo%. This top
level %indo% is called a frame. Grames are Java objects that have title bar and contains a
caption identifying the Grame. #n addition Grames have a set of icons2 maximi?e$ minimi?e
and restore $ that can be used to control their appearance on the des'top.
Steps to create a frame :
,. Create the frame by a call to its constructor %ith ne% operator
-rame ( = new -rame()&
;. Besi?e the Grame. 1efault si?e of frame is E $E.
(resiSe(D88*E88)&
,. Call the sho% method of frame class to display the Grame. / frame is not sho%n %hen
it is created.
(s5ow()&
The default si?e of a frame is E by E and so %ill not be visible. The si?e has to be explicitly
given. 9ence the frame is resi?ed every time it is created ne%ly.
$&le F rogram to display a frame %ith text.
SourceGile F 8elcome.java
import javaawt2&
public class Pelcome e:tends -rame{
public Pelcome(String name){
super(name)&
'
public boolean 5andle+vent(+vent e) {
i( (eid ==+ventP/3H0PWH+S6,0[)
Systeme:it(8)&
return super5andle+vent(e)&
'
54
public void paint(\rap5ics g) {
gdrawString(TPelcome to "ava T* @D*188)&
'
public static void main(String[] args) {
-rame (= new Pelcome()&
(resiSe(?88*>88)&
(s5ow()&
'
'
Output)
The program has inherited from a basic container class Grame and has an 5andle+vent()
method to handle the %indo% close event and paint method to print a string at a particular
position. #n the main method an instance of the class is created and the frame is resi?ed to
*EE x ;EE si?e and finally the method sho% is used to display the frame. =asically an
/8T program starts %ith a frame container and other components and events happen in
the frame %hich are handled in the 5andle+vent() method.
Event Handling :
Hvents are generated %hen something happens to a component . The system creates an
Hvent object and sends a handleHvent message to the affected component. rograms can
override the default 5andle+vent() method of the component class to provide
customised handling of events. Hach event is derived from the Hvent class and is assigned
an event2id for %hich it can be tested. Hvents can come from the follo%ing sourcesF the
'eyboard$ the mouse$ %indo% creation$ destruction and movement$ scrollbar activities$
listbox items selection and deselection $ change of input focus$ component and menu
actions.
55
Event class has the following fields.
id 2 identifier for the event
target 2 the component originating the event
x$y 2 x and y co2ordinates of mouse events
clic'count 2 number of clic's in a M60SHI1683 event
'ey 2 character or function 'ey in a 'eyboard event
modifier 2 describes the states of S9#GT$ CTB:$ /:T and Meta 'eys
Event handler procedures :
Hvery time an event is generated$ it is passed to a 5andle+vent() method. The object
%hose 5andle+vent() method is initially called is the one that is closest to the event.
Gor example$ %hen a user types a 'eystro'e into a component$ the component that
processes the 'eystro'e gets first chance to handle it . #f that component does not process
the event$ it is passed to the parent component (8indo% hierarchy+. There are three
possible exits from the handleHvent procedure F
return true 2 event is handled 2 don[t propagate
return false 2 event is not handled 2 propagate to parent in the %indo%
hierarchy.
return super5andle+vent(event) 2 event is not handled 2 propagate to the parent
in the inheritance hierarchy.
/l%ays handle an event or pass it to its parent class but not to its parent %indo%.
update() and paint() functions :
#n response to user action or external circumstances$ parts of an application %indo% may
need to be redra%n.
$&le F
8hen user resi?es a %indo% $ another %indo% pops up on a application %indo% and
disappears. 8hen a %indo% is displayed for first time$ its initial elements must be dra%n.
Hach time a %indo% needs to be redra%n for any reason$ the event handler calls its
update() function. The default implementation for update 2 i.e. in component base class
is to erase the bac'ground and call paint() method. /ll dra%ing in Java must go
through a Zraphics object. =oth update() and paint() methods ta'e Zraphics object
as a parameter.
repaint56 F222222 This method does not ta'e any arguments. / call to this method in
turn invo'es the paint() method.
Text and Fonts
56
To display text$ a Gont has to be selected. / font is specified by its name$ style and point
si?e. Gonts li'e 9elvitica$ TimesBoman$ Courier$ 1ialog$ Symbol are al%ays mapped by
Java to fonts that actually exist on the client machine. Gont is an object in Java and so
should be created %ith ne% before it can be used. The style of the font is represented by
the property as PLAN1 3OLD1 -AL% or 3OLD8-AL%.
Synta& ) -ont(String name* int property* int siSe)&
name 2 font name
property 2 style 2 can be #;)/3* .0;H* /6);/4* .0;HF/6);/4.
si?e 2 font si?e.
$&le ) -ont ( = new -ont(TOelveticaT* -ont.0;H* 1E)&
-ont d = new -ont(TOelveticaT* -ont.0;HF-ont/6);/4* 1E)&
Selects 9elvetica type of font and prints the text in =6:1!=6:1"#T/:#C %ith si?e of ,>
points.
To dra% a string in the current font$ method dra% string is used.
Synta& F void drawString(String str * int : * int y)&
str 2 String to be dra%n.
x 2 x2coordinate of the starting position of the string.
y 2 y2coordinate of the starting position of the string.
%olors) T%o colors are used in a graphical application. The fore ground color %ith %hich
the text or dra%ings are painted and bac'ground of the graphics i.e. the color %ith %hich
the container is filled before dra%ing some graphics on it. The color is set by using the
object of class 4olor. Gollo%ing methods of the \rap5ics object are used to set the
colors.
Goreground color F set4olor(4olor color)
=ac'ground color F set.ackground(4olor color)
The color is provided by creating an object of 4olor class. / color is assumed to be
formed from the colours red$ green and blue. The 4olor object is created by calling the
constructor and pass the combination of above colors.
5$
Synta& o" constructorF
4olor(int red* int green*int blue)
red 2 red value
green 2 green value
blue 2 blue value
Hach color value must be in the range of E to ;AA.
The 4olor class defines some commonly used ,* colors. They are the static and final
objects of the 4olor class defined %ithin. They are 2 black* blue* cyan*
dark\rey* grey* green* lig5t\ray* magenta* orange* pink * red* w5ite and
yellow
Synta& F void set4olor(4olor color)&
c 2 c is one of predefined colors as 4olorred or created as belo%
c= new 4olor(1>E*>?1*1R)&
Synta& F void set.ackground(4olor c)&
c 2 is one of predefined colors as 4olorred or created as belo%
c= new 4olor(1>E*>?1*1R)&
Graphical shapes :
Zraphics class provides a number of methods for dra%ing different lines and shapes.
$&le ) to dra% a line$ method available is
void draw;ine(int :1* int y1* int :>* int y>)&
This dra%s a line bet%een the points %ith coordinates (x,$y,+ and (x;$y;+.
$&le ) rogram to dra% rectangles %ith colors SourceGile F BectTest.java
import javaawt2&
class 4olor,ect{
int le(t*top*widt5*5eig5t&
protected 4olor ,ect4olor&
public 4olor,ect() {
t5is(8*8*8*8*null)&
'
public 4olor,ect(int pWle(t*int pWtop*int pWwidt5*int pW5eig5t*4olor
pWcol)
{
le(t = pWle(t& top = pWtop&
widt5 = pWwidt5& 5eig5t = pW5eig5t&
,ect4olor = pWcol&
'
5%
public void draw(\rap5ics g) {
gset4olor(,ect4olor)&
gdraw,ect(le(t*top*widt5*5eig5t)&
'
public void draw,ound(\rap5ics g) {
gdraw,ound,ect(le(t*top*widt5*5eig5t*widt5118*5eig5t118)&
'
public void draw-illed(\rap5ics g) {
gset4olor(,ect4olor)&
g(ill,ect(le(t*top*widt5*5eig5t)&
'
public void draw-illed,ound(\rap5ics g) {
g(ill,ound,ect(le(t*top*widt5*5eig5t*widt5118*5eig5t118)&
'
public String toString()
{
return new String(T4olor,ect = TFle(tFT=TFtopFT=TFwidt5FT=TF5eig5t)&
'
'
public class ,ect6est e:tends -rame{
4olor,ect br = new 4olor,ect(188*188*188*188*4olorblue)&
4olor,ect ro = new 4olor,ect(1?8*1?8*>8*>8*4olorred)&
4olor,ect r( = new 4olor,ect(1?8*1D8*>8*>8*4oloryellow)&
4olor,ect rr = new 4olor,ect(1D8*1?8*>8*>8*4olorgreen)&
4olor,ect rs = new 4olor,ect(1D8*1D8*>8*>8*4olororange)&
public ,ect6est(){
t5is(T,ect6estT)&
'
public ,ect6est(String str){
super (str)&
'
public boolean 5andle+vent(+vent evt){
i( (evtid == +ventP/3H0PWH+S6,0[)
Systeme:it(8)&
return super5andle+vent(evt)&
'
public void update(\rap5ics g)
{
paint(g)&
'
5+
public void paint (\rap5ics g){
gset4olor(ro,ect4olor)&
brdraw(g)&
rodraw-illed(g)&
r(draw-illed(g)&
rrdraw-illed(g)&
rsdraw-illed(g)&
'
public static void main(String[] arg){
-rame (rm = new ,ect6est()&
(rmresiSe(?88*?88)&
(rms5ow()&
'
'
A=T C(-p("e"t
Components are the building bloc's of the /8T. Hnd user directly interacts %ith these
components. Hach component is said to be contained in a container. 9ence a component
should be placed in its respective container using add() method. The container may be a
8indo%$ a anel or a Grame. / component in /8T generates an event. Hach such event
is handled by event handler of the component$ a method %hich is called %hen an action is
performed on the component. Components provided by /8T are as given belo%.
:abels F
61
/ :abel is simply a piece of text that can be used to identify another control or to
communicate information to the user %ith various fonts. Text string displayed by a :abel
can be aligned to left$ centre or right.
Creation F ;abel lbl = new ;abel (String str* int align)&
str 2 label text.
align 2 alignment F :HGT$ CH3THB or B#Z9T
1efault alignment is :HGT
Methods F get6e:t() - getting the Text
set6e:t(String te:t) - changing the text
$&le )
Creating :abels F ;abel lbl3ame = new ;abel(TYiranT)&
justifying :abels F ;abel lbl4omp = new ;abel(T+4/;T*;abel,/\O6 )&
getting the Text F String label6e:t = lbl3ameget6e:t()&
changing the text F lbl3ameset6e:t(TYaranT)&
3utton ) / =utton is li'e a :abel$ except that a =utton is a clic'able component.
$&le ) clic'ing an 6] button in file save 1ialog box$ starts saving the file$ or
C/3CH: button brings you out of the file save 1ialog box.
%reation F .utton()& !! button %ithout a label.
.utton(String name) & !! button %ith a label.
Methods F set;abel(String label) - Change the label
String get;abel() - Zet the label
$&les )
Create unlabeled =utton F .utton ok.utton = new .utton()&
Create labelled =utton F .utton cancel.ut = new .utton(T4ancelT)&
/dd the =utton to container F add(ok.utton)&
Change the label F ok.uttonset;abel(T)cceptT)&
Zet the label F String but;abel = cancel.uttonget;abel()&
61
$&le F rogram illustrates the usage of a =utton. SourceGile F =uttonTest.java
import javaawt2&
public class .utton6est e:tends -rame {
public .utton6est(String name) {
super(name)&
.utton +:it.utton = new .utton(T+:itT)&
add(TSout5%* +:it.utton)&
'
public boolean 5andle+vent(+vent e){
i( (eid==+ventP/3H0PWH+S6,0[)
Systeme:it(8)&
return super5andle+vent(e)&
'
public boolean action(+vent e* 0bject o)
{
i( (etarget instanceo( .utton){
i( (oeLuals(T+:itT)) {
Systeme:it(8)&return true&'
else return (alse&'
else
return (alse&
'
public void paint(\rap5ics g)
{
-ont (ont = new -ont(T6imes,oman%* -ont/6);/4*1E)&
gset-ont((ont)& gdrawString(TOello T*@D*118)&
'
public static void main(String[] args){
-rame ( = new .utton6est(T-irstT)&
(resiSe(?88*?88)&
(s5ow()&
'
'
62
Convenience Methods:
#f an action$ mouse$ 'eyboard or focus event %as not handled in a handleHvent(+ method$
then Java calls a convenience method to give the %indo% a second chance to process the
event. The convenience methods are only to ma'e code clearer. Convenience methods are
action$ mouseHnter$ mouseHxit$ mouseMove$ mouse0p$ mouse1o%n$ mouse1rag$
'ey1o%n$ 'ey0p$ lostGocus and gotGocus.
Synta& F boolean action(+vent event* 0bject obj)
event 2 the Hvent object representing the event .
obj 2 additional information on the event$ usually the label of the
originating component.
Event handling in 1.1 and aove:
Java supports t%o distinct models for handling events. The above method is one model.
Grom J1] ,., on%ards$ a ne% model is implemented using event listeners.
The listeners are provided in the form of interfaces %hich contain method declarations.
The applications %hich need to handle the events implement these methods. The objects of
class javaawtevent are used to model the events. These event objects are sent as
parameters to the methods %hich provide event handling.
63
The follo%ing table gives a cross reference of the original model to ne% mdoel event
6riginal model 3e% model
Source 6bject Hvent ! Method #nterface Methods
.utton* ;ist*
Genu/tem*
6e:t-ield
)46/03W+U+361action )ction;istener )ction#er(ormed()ct
ion+vent)
45eckbo:*
45oice
)46/03W+U+36
1action
/tem;istener itemState45anged(/t
em+vent )
Hialog* -rame P/3H0PWH+S6,0[
P/3H0PW+]#0S+
P/3H0PW/403/-[
P/3H0PWH+/403/-[
P/3H0PW4;0S+H
P/3H0PWG0U+H
P/3H0PWG0U+H
P/3H0PWG0U+H
P/3H0PWG0U+H
Pindow;istener
Pindow;istener
Pindow;istener
Pindow;istener
Pindow;istener
4omponent;istener
4omponent;istener
4omponent;istener
4omponent;istener
window4losing(Pindo
w+vent )
window0pened(Pindow
+vent )
window/coni(ied(Pin
dow+vent )
windowHeiconi(ied(P
indow+vent )
window4losed(Pindow
+vent )
componentGoved(4omp
onent+vent)
componentOidden(4om
ponent+vent)
component,esiSed(4o
mponent+vent)
componentS5own(4omp
onent+vent)
Scrollbar S4,0;;W;/3+W<#
S4,0;;W;/3+WH0P3
S4,0;;W#)\+W<#
S4,0;;W#)\+WH0P3
S4,0;;W).S0;<6+
S4,0;;W.+\/3
S4,0;;-+3H
)djustment;istene
r
)djustment;istene
r
)djustment;istene
r
)djustment;istene
r
)djustment;istene
r
)djustment;istene
r
)djustment;istene
r
)djustmentUalue45an
ged
()djustment+vent)
)djustmentUalue45an
ged
()djustment+vent)
)djustmentUalue45an
ged
()djustment+vent)
)djustmentUalue45an
ged
()djustment+vent)
)djustmentUalue45an
ged
()djustment+vent)
)djustmentUalue45an
ged
()djustment+vent)
)djustmentUalue45an
ged
()djustment+vent)
Chec'box$
Chec'boxMenu#tem
Choice$ :ist
;/S6WS+;+46
;/S6WH+S+;+46
/tem;istener
/tem;istener
itemState45anged(/t
em+vent )
itemState45anged(/t
em+vent )
64
Canvas$ 1ialog$
Grame$ anel$
8indo%
G0<S+WH,)\1mouseHra
g
G0<S+WG0U+1mouseGov
e
G0<S+WH0P31mouseHow
n
G0<S+W<#1mouse<p
G0<S+W+36+,1mouse+n
ter
G0<S+W+]/61mouse+:i
t
GouseGotion;isten
er
GouseGotion;isten
er
Gouse;istener
Gouse;istener
Gouse;istener
Gouse;istener
mouseHragged(Gouse+
vent)
mouseGoved(Gouse+ve
nt)
mouse#ressed(Gouse+
vent)
mouse4licked(Gouse+
vent)
mouse,eleased(Gouse
+vent)
mouse4licked(Gouse+
vent)
mouse+ntered(Gouse+
vent)
mouse+:ited(Gouse+v
ent)
Component Y+[W#,+SS1keyHown
Y+[W,+;+)S+1key<p
Y+[W)46/03W,+;+)S+1
key<p
\06W-04<S1got-ocus
;0S6W-04<S1lost-ocu
s
Yey;istener
Yey;istener
Yey;istener
-ocus;istener
-ocus;istener
key#ressed(Yey+vent
)
key,eleased(Yey+ven
t)
key6yped(Yey+vent)
key,eleased(Yey+ven
t)
key6yped(Yey+vent)
(ocus\ained(-ocus+v
ent)
(ocus;ost(-ocus+ven
t)
The ne% event handling is a three step process2 preparation$ listening and responding.
Preparation F import the classes in java.a%t.event pac'age.
Modify the class header as implements /ction:istener$... since all
listeners are interfaces
Listening ) Ma'e a connection bet%een the component (=utton$ TextGield$ ...+
%hich is the source of the /ctionHvents and the container.
This is done by invo'ing the add/ction:istener(+ method for
/ctionHvents on the component object.
*esponding) 8hen an action event occurs it should be responded for %hich
actionerformed(+ method for /ctionHvents is used.
Statements in the method body %ill be executed.
65
HxampleF The .utton6est %ritten earlier no% in J1] ,., version %ith events handled
using listeners is as under.
SourceGile F .utton6estjava
import javaawt2&
import javaawtevent2&
public class .utton6est e:tends -rame implements )ction;istener*
Pindow;istener {
.utton +:it.utton = new .utton(T+:itT)&
public .utton6est(String name) {
super(name)&
add(TSout5T*+:it.utton)& add Pindow;istener(t5is)&
+:it.uttonadd)ction;istener(t5is)&
'
public void action#er(ormed()ction+vent e){
i( (egetSource() == +:it.utton) {
Systeme:it(8)& dispose()&'
'
public void paint(\rap5ics g)
{
-ont (ont = new -ont(T6imes,omanT*-ont/6);/4*1E)&
gset-ont((ont)& gdrawString(TOello T*@D*118)&
'
public static void main(String[] args){
-rame ( = new .utton6est(T-irstT)&
(setSiSe(?88*?88)&
(s5ow()&
'
public void window4losed(Pindow+vent e) { '
public void window4losing(Pindow+vent e) {
setUisible((alse)&
dispose()&
Systeme:it(8)& '
public void windowHeiconi(ied(Pindow+vent e) { '
public void window/coni(ied(Pindow+vent e) { '
public void window0pened(Pindow+vent e) { '
public void window)ctivated(Pindow+vent e) { '
public void windowHeactivated(Pindow+vent e) { '
'
Chec!ox
/ chec' box consists of a s<uare button that can be clic'ed to cause it to change state.
The user chec's the box by clic'ing inside it %hich is indicated by a chec' mar'. The
user can turn off the chec' mar'. =y clic'ing inside the box again. This is mostly used to
ma'e one among t%o mutually exclusive choices li'e yes!no or male!female or on!off etc.
66
The state of the chec' box is represented as a boolean value.
true indicates on i.e.$ chec'ed
false indicates off i.e.$ unchec'ed
%reation F 45eckbo:( )&
45eckbo:(String label)&
ðods :
public String get;abel() 2 Zet the label of the chec'box
public void set;abel(String label) 2 Change label of chec'box
public boolean getState() 2 Zet the state of chec'box
public void setState(boolean state) - Set the state of chec'box
public void add/tem;istener(/tem;istener l)
/dds the specified item listener to
receive item events from this chec' box.
Listener ) /tem;istener
$&le ) 45eckbo: my45eckbo: = new 45eckbo:()&
Chec!oxGroup
/ Chec'boxZroup is a set of chec'boxes so that only one of them can be on or chec'ed
at any time. Such a set is commonly referred to as radio buttons. 8hen another box is
chec'ed$ current one is automatically unchec'ed
Creating Badio =uttons F Badio =uttons are special case of a chec'box
45eckbo:\roup cities = new 45eckbo:\roup()
Chec'box group can be created either before or after its member chec'boxes.
45eckbo:(String label * boolean state* 45eckbo:\roup g)&
State F true indicates the Chec'=ox is chec'ed %hen first displayed
45eckbo: my45eckbo: = new 45eckbo:(TUijayawadaT* true* cities )&
add(my45eckbo:)&
add(new 45eckbo:(TOyderabadT* true *cities))&
add(new 45eckbo:(TSecunderabadT * (alse* cities))&
6$
$&le ) rogram to illustrate usage of Chec'boxes. SourceGile F Chec's,.java
import javaawt2&
import javaawtevent2&
public class 45ecks1 e:tends -rame implements /tem;istener*
Pindow;istener
{
private 45eckbo: c5eck1* c5eck>* c5eck?* c5eckE* c5eckD* c5eckR&
private 6e:t-ield te:t1* te:t>&
public 45ecks1(){
super(T45eck .o:- HemoT)&
set;ayout(new -low;ayout())&
c5eck1 = new 45eckbo:(T45eckbo: 1T)& add(c5eck1)&
c5eck> = new 45eckbo:(T45eckbo: >T)& add(c5eck>)&
c5eck? = new 45eckbo:(T45eckbo: ?T)& add(c5eck?)&
te:t1 = new 6e:t-ield(T6e:t -ieldT*D8)& add(te:t1)&
45eckbo:\roup c5grp = new 45eckbo:\roup()&
c5eckE = new 45eckbo:(T45eckbo: ET*true*c5grp)& add(c5eckE)&
c5eckD = new 45eckbo:(T45eckbo: DT*(alse*c5grp)&
add(c5eckD)&
c5eckR = new 45eckbo:(T45eckbo: RT*(alse*c5grp)& add(c5eckR)&
te:t> = new 6e:t-ield(T6e:t -ieldT*D8)& add(te:t>)&
c5eck1add/tem;istener(t5is)&
c5eck>add/tem;istener(t5is)&
c5eck?add/tem;istener(t5is)&
c5eckEadd/tem;istener(t5is)&
c5eckDadd/tem;istener(t5is)&
c5eckRadd/tem;istener(t5is)&
addPindow;istener(t5is)&
'
public void itemState45anged(/tem+vent e) {
i((egetSource() == c5eck1) {
te:t1set6e:t(T45eck 1 clickedT)& '
i((egetSource() == c5eck>) {
te:t1set6e:t(T45eck > clickedT)&'
i( (egetSource() == c5eck?) {
te:t1set6e:t(T45eck ? clickedT)&'
i((egetSource() == c5eckE) {
te:t>set6e:t(T45eck E clickedT)& '
i((egetSource() == c5eckD) {
te:t>set6e:t(T45eck D clickedT)&'
i( (egetSource() == c5eckR) {
te:t>set6e:t(T45eck R clickedT)&'
'
public void window4losed(Pindow+vent e) { '
public void window4losing(Pindow+vent e) {
setUisible((alse)&
6%
dispose()& Systeme:it(8)&
'
public void windowHeiconi(ied(Pindow+vent e) { '
public void window/coni(ied(Pindow+vent e) { '
public void window0pened(Pindow+vent e) { '
public void window)ctivated(Pindow+vent e) { '
public void windowHeactivated(Pindow+vent e) { '
public static void main(String args[]){
-rame ( = new 45ecks1()&
(setSiSe(E88*E88)&
(setUisible(true)&
'
'
CHOICE (' D'(p6(2" L!t
The choice class contains a list of items from %hich the user can select a single item.
8hen the user clic's on the field$ this drops do%n a list of choices and the user can select
one of them. The currently selected item is visible in the component.
9elvetica
%reation) 45oice()&
Methods: public void add(String item) - /dds an item to this Choice
menu.
public void add/tem(String item) 2 /dds an item to this Choice.
public void insert(String item*int inde:) - #nserts the item into
this choice at the specified position.
public void add/tem;istener(/tem;istener l) - /dds the
specified item listener to receive item events from this Choice menu
Listener ) /tem;istener
6+
$&leF creating choicesF
45oice my45oice = new 45oice()&
To add items to Choice component
my45oiceadd(TjavaT)&
my45oiceadd(T40.0;T)&
To select either by name or index
my45oiceselect(TjavaT)&
my45oiceselect(1)&
To get the name of the item by index
String selectitem = my45oiceget/tem(>) &
LIST:
/ :ist is similar to choice$ except that all items are displayed along %ith scrollbars. This
can be configured to accept multiple selections. The :ist contains a box containing
choices$ one for each line. The :ist class allo%s to create a scrolling list of values that
may be selected either individually or many at a time.
9elvetica
Times Boman
%reationF
;ist()&
;ist(int rows) - Creates a ne% scrolling list initiali?ed %ith the
specified number of visible lines
;ist(int rows* boolean multipleselections)&
11(or multiple selection o( items
ro%s 2 no. of visible ro%s!items.
multipleselections 2 true to enable multiple selections.
2 false to disable.
Methods )
public void add(String item)
/dds the specified item to the end of scrolling list.
$1
public void add(String item* int inde:)
/dds the specified item to the the scrolling list at the position indicated by the
index
public void remove(int position)
Bemove the item at the specified position from this scrolling list.
public void replace/tem(String newUalue* int inde:)
Beplaces the item at the specified index in the scrolling list %ith the ne% string.
public String getSelected/tem()
Zet the selected item on this scrolling list.
public void select(int inde:)
Selects the item at the specified index in the scrolling list.
public void deselect(int inde:)
1eselects the item at the specified index.
$&le F Gonts in %indo% environment can be chosen from a list containing
the available fonts.
Creating :istsF ;ist my;ist = new ;ist()&
;ist my;ist = new ;ist(18* true)& 11 allo% multiple selections.
/dding items to the :ist F my;istadd(TjavaT)&
Beplacing a given item %ith a ne% item F my;istreplace/tem(T#ascalT*8)&
To clear all itemsF my;istremove)ll()&
To get the text of the selected itemF
String select/tem = my;istgetSelected/tem()&
$&le F rogram to illustrate the usage of Choice and :ist components.
SourceGile F Control.java
import javaawt2&
import javaawtevent2&
public class 4ontrol e:tends -rame implements Pindow;istener*
/tem;istener
{
private 45oice c5oice = new 45oice()&
private ;ist list = new ;ist()&
;abel selection = new ;abel()&
public 4ontrol() {
set6itle(T<nderstanding ;ist controlsT)&
set;ayout(new -low;ayout())&
add(c5oice)&
add(list)&
add(selection)&
c5oiceadd(T4T)& c5oiceadd(T4FFT)& c5oiceadd(T")U)T)&
c5oiceadd(T0,)4;+T)&
$1
listadd(T4T)& listadd(T4FFT)& listadd(T")U)T)&
listadd(T0,)4;+T)&
selectionset6e:t(THisplays selection and inde: (rom 45oice1;istT)&
c5oiceadd/tem;istener(t5is)&
listadd/tem;istener(t5is)&
addPindow;istener(t5is)&
setSiSe(?88*>88)&
setUisible(true)&
'
public void itemState45anged(/tem+vent e)
{
i((egetSource() == c5oice) {
String inde:=T/nde:= TFc5oicegetSelected/nde:()&
String item=T/tem= TFc5oicegetSelected/tem()&
selectionset6e:t(T45oice TFinde: FT=TFitem)&
'
i((egetSource() == list) {
String inde:=T/nde:= TFlistgetSelected/nde:()&
String item=T/tem= TFlistgetSelected/tem()&
selectionset6e:t(T;ist TFinde: FT=TFitem)&
'
return&
'
public void window4losed(Pindow+vent e) { '
public void window4losing(Pindow+vent e) {
setUisible((alse)&
dispose()&
Systeme:it(8)& '
public void windowHeiconi(ied(Pindow+vent e) { '
public void window/coni(ied(Pindow+vent e) { '
public void window0pened(Pindow+vent e) { '
public void window)ctivated(Pindow+vent e) { '
public void windowHeactivated(Pindow+vent e) { '
public static void main(String[] args){
-rame ( = new 4ontrol()&
(s5ow()&
'
'
$2
Te&t C(-p("e"t :
These t%o classes are derived from TextComponent class. =oth TextGield and Text/rea
define boxes in %hich a user can enter text.
Te&tF!e/6:
/ TextGield can hold a single ro% of text. #ts %idth %ill be set to accommodate a String
used in the constructor or can be specified giving the no. of columns.
%reation)
6e:t-ield()&
6e:t-ield(String te:t)&
6e:t-ield(String te:t* int cols)&11speci(ies no o( columns used
Methods )
public void set6e:t(String t)
Sets the text that is presented by this text component to be the specified text.
public String get6e:t()
Zets the text that is presented by this text field. This method is derived from
6e:t4omponent class
public void add6e:t;istener(6e:t;istener l)
/dds the specified text event listener to recieve text events from this
textcomponent.
$&les )
creating TextGieldsF 6e:t-ield my6e:t-ield = new 6e:t-ield()&
adding TextGield to the container F add(my6e:t-ield)&
controlling %hether the text in the component can be edited or read onlyF
my6e:t-ieldset+ditable((alse)&11read only
Te&tA'ea :
$3
/ Text/rea is used for multiple lines of text %ith scrollbars so that large amounts of text
can be entered and displayed. This facilitates insertion$ appending and replacement of text.
%reation F
6e:t)rea()&
6e:t)rea(int rows* int cols)&
6e:t)rea(String te:t)&
6e:t)rea(String te:t* int rows*int cols) !!specifies no. of ro%s and cols.
Methods )
public void append(String str)
/ppends the given text to the text area[s current text.
public int get,ows()
Zets the number of ro%s in the text area.
public void set,ows(int rows)
Sets the number of ro%s for this text area.
public void insert(String str* int pos)
#nserts the specified text at the specified position in this text area.
public void replace,ange(String str* int start* int end)
Beplaces text bet%een the indicated start and end positions %ith the specified
replacement text.
public void set4olumns(int columns)
Sets the number of columns for this text area.
public void set,ows(int rows)
Sets the number of ro%s for this text area.
public void add6e:t;istener(6e:t;istener l)
/dds the specified text event listener to recieve text events from this
textcomponent.
$4
$&les )
creating Text/reaF 6e:t)rea my6e:t)rea = new 6e:t)rea(TOelloT*D*>8)
11D rows*>8 columns
adding Text/rea to the container add(my6e:t)rea)&
append text to the textF my6e:t)reaappend6e:t(T)ppendingT)&
S.'(//8a'
Scrollbars are also 'no%n as sliders. This component scrolls through a range of integer
values bet%een the minimum and the maximum values assigned to the extreme possible
positions. Scrollbars can be either hori?ontal or vertical. The default range of values for
scrollbars is E to ,EE.
9ori?ontal
Scroll
arro% Scroll Scroll box Scroll visible
visible can be dragged area right
area left one left or right one unit
bloc'
%reation
Scrollbar()&
Scrollbar(int orientation)&
Scrollbar(int orientation*int initialUalue*int Uisible)rea* int
minUalue*int ma:Ualue) &
6rientation can be either ScrollbarO0,/^036); or ScrollbarU+,6/4);
Methods
public void add$djustment'istener()djustment;istener l)
/dds the specified adjustment listener to receive instances of )djustment+vent
from this scroll bar
public int %et(alue()
Zets the current value of this scroll bar.
public void set(alue(int newUalue)
Sets the value of this scroll bar to the specified value
public void set)lock*ncrement(int v)
Sets the bloc' increment for this scroll bar.
public int %et)lock*ncrement()
Zets the bloc' increment of this scroll bar.
$5
$&le F
Creating ScrollbarsF
Scrollbar myScrollbar = new Scrollbar()&
Scrollbar myScrollbar = new Scrollbar(ScrollbarU+,6/4);*D8*18*8*188)&
To set Scrollbar[s current position myScrollbarsetUalue(>D)&
To set scrollbar[s line increment myScrollbarset<nit/ncrement(>) &
11(or line up1down
To get Scrollbar[s current position myScrollbargetUalue()&
HxampleF rogram to illustrate the usage of Scrollbar.
SourceGile F ScrollTest.java
import javaawt2&
import javaawtevent2&
public class Scroll6est e:tends -rame implements Pindow;istener*
)djustment;istener
{
private Scrollbar scroll=new Scrollbar(ScrollbarU+,6/4);*D8*>8*8*>DD)&
;abel selection = new ;abel()&
public Scroll6est() {
set6itle(T<nderstanding Scroll .arT)&
set;ayout(new -low;ayout())&
add(scroll)&
add(selection)&
scrollset<nit/ncrement(>)&
selectionset6e:t(THisplays position o( Scroll barT)&
scrolladd)djustment;istener(t5is)&
addPindow;istener(t5is)&
setSiSe(>88*>88)&
setUisible(true)&
'
public void adjustmentUalue45anged()djustment+vent e) {
int position = scrollgetUalue()&
selectionset6e:t(TUalue =TF/ntegertoString(position))&
return&
'
public void window4losed(Pindow+vent e) { '
public void window4losing(Pindow+vent e) {
setUisible((alse)&
dispose()&
Systeme:it(8)& '
public void windowHeiconi(ied(Pindow+vent e) { '
public void window/coni(ied(Pindow+vent e) { '
public void window0pened(Pindow+vent e) { '
$6
public void window)ctivated(Pindow+vent e) { '
public void windowHeactivated(Pindow+vent e) { '
public static void main(String[] args){
-rame ( = new Scroll6est()&
'
'
C O N T A I N E R S
/ container is an /8T component %hich acts as a place holder for other components. /
component used in a java program is placed in a container to be visible to the user. /
container has to organise its contents. 9ence %e have to specify layout manager.
There are three types of containers namely 2 Grames$ 8indo%s and anels.
.rameF / frame is also a %indo% place holder for the actual program.
<indo7) / %indo% is in display separately on the screen.
Panel) The panel is also a container but cannot be displayed as a separate
%indo%. / panel must be placed in a frame or a %indo% container.
/ panel is to be added to its container. The steps to create and add a panel to a
container.
$$
S-$PS)
,. Create a panel using container panel 2 #anel pan=new #anel()&
;. Set layout to the panel 2 panset;ayout (new -low;ayout() )&
*. Create and add components to the panel
panadd (new .utton (!0Y%))&
panadd (new .utton(!4ancel%))&
>. /dd panel to its container. #f the container is a frame
add (pan)&
else if it is also a panel use its reference
piadd(pan)
%here pi is a panel containing the panel pan
$&le) SourceGile F anelTest.java
import javaawt2&
import javaawtevent2&
public class #anel6est e:tends -rame implements )ction;istener*
Pindow;istener
{
private int s5ape &
private .utton rect = new .utton(T,ectT)&
private .utton circle = new .utton(T4ircleT)&
private .utton +:it = new .utton(T+:itT)&
public #anel6est(String title) {
super(title)&
set;ayout(new .order;ayout())&
#anel p = new #anel()&
pset;ayout(new -low;ayout())&
padd(rect)&
padd(circle)&
padd(+:it)&
pset.ackground(4oloryellow)&
rectadd)ction;istener(t5is)&
+:itadd)ction;istener(t5is)&
circleadd)ction;istener(t5is)&
addPindow;istener(t5is)&
psetSiSe(188*188)&
add(T+astT*p)&
setUisible(true)&
setSiSe(E88*E88)&
'
public void action#er(ormed()ction+vent e) {
i((egetSource() == rect)
s5ape =1&
i( (egetSource() == circle)
s5ape = >&
$%
i( (egetSource() == +:it) {
setUisible((alse)&
dispose()&
Systeme:it(8)& '
repaint()&
'
public void paint(\rap5ics g){
switc5(s5ape) {
case 1 = gset4olor(4olorred)&
gdraw,ect(D8*1R8*188*188)&
break&
case > = gset4olor(4olorblue)&
gdraw)rc(D8*D8* 188*188* 8* ?R8)&
break&
'
return&
'
public void window4losed(Pindow+vent e) { '
public void window4losing(Pindow+vent e) {
setUisible((alse)&
dispose()&
Systeme:it(8)& '
public void windowHeiconi(ied(Pindow+vent e) { '
public void window/coni(ied(Pindow+vent e) { '
public void window0pened(Pindow+vent e) { '
public void window)ctivated(Pindow+vent e) { '
public void windowHeactivated(Pindow+vent e) { '
public static void main(String args[]){
-rame pan(rm = new #anel6est(T#anel 6estT)&
'
'
$+
Ca"7a#
/ Canvas is simply a rectangular area in %hich graphics objects can be dra%n. 0nli'e
panel components cannot be added to a Canvas. / Canvas is used li'e a blac' board on
%hich one can dra% graphical objects.
Canvas class is inherited from Component class. / Canvas class has its o%n graphics
context. /ny dra%ing is done in the paint method.
#n order to create a Canvas$ the ne% class should inherit from Canvas class and override
the paint(+ method.
$&leF SourceGile F anelTest.java
public class #anel6est e:tends -rame
{ public #anel6est()
{ set6itle (!#anel6est%)&
#anel p = new #anel()&
pset;ayout (new -low;ayout())&
padd(new .utton(!6ick%))&
padd(new .utton(!,eset%))&
padd(new .utton(!4lose%))&
add(!Sout5%* p)&
clock = new 4lock4anvas()&
add (!4enter%* clock)&
'
public boolean 5andle+vent (+vent evt)
{ i( (evtid = = +ventP/3H0PWH+S6,0[) Systeme:it(8)&
return super5andle+vent(evt)&
'
public boolean action(+vent evt0bject arg)
{ i( (argeLuals(!6ick%)) clocktick()&
else i( (argeLuals(!,eset%)) clockreset()&
%1
else i( (argeLuals(!4lose%)) Systeme:it(8)&
return true&
'
public static void main(String[ ] args)
{ -rame ( = new #anel6est()&
(resiSe(>88* >88)&
(s5ow()&
'
private 4lock4anvas clock&
'
4lass 4lock4anvas e:tends 4anvas
{ public void paint(\rap5ics g)
{ gdraw8val(8* 8* 188* 188)&
double 5our)ngle = > 2Gat5#1 2 (minutes - ?2R8) 1 (1>2R8)&
double minute)ngle = > 2Gat5#1 2 (minutes - 1D) 1 (R8)&
gdraw;ine(D8* D8* D8 F (int) (?8 2Gat5cos(5our)ngle))*
D8 F (int) (?8 2Gat5sin(5our)ngle)))&
gdraw;ine(D8* D8* D8 F (int) (ED 2Gat5cos(minute)ngle))*
D8 F (int) (ED 2Gat5sin(minute)ngle)))&
'
public void reset() {
minutes = 8&
repaint()&
'
public void tick()
{ minutesFF&
repaint()&
'
private int minutes = 8&
'
#n /8T$ components are placed in containers. =ecause java targets at platform
independence$ the components placed in a container are not given any fixed position.
1ifferent platforms have different scale and units. 9ence giving an absolute position
causes trouble in placing components. #nstead java uses layout managers %hich organise
the components in a container. The placing of components is relative to the dimensions of
the container. Java uses different layout structures. 3amely$ FlowLayout,
BorderLayout, GridLayout, GridBagLayout, CardLayout and CustomLayout. 6f
course one can place components %ithout using a layout$ but by using a layout$ one can
position the components according to a specific format in the container.
Spe.!*y!"3 a Lay(5t#
/ layout manager is an object of the specific :ayout class. To organise components in a
container$ layout must be specified before the components are added. 6ne can specify a
layout by add;ayout() method %ith layout object as parameter.
panel:add;ayout (new -low;ayout())&
%1
w5ere panel: is a container and t5e components added to panel: are
placed according to t5e (ormat o( -low;ayout
/fter setting layout manager the re<uired components can be added to the container %ith
the add() method.
panel:add (new .utton (!0Y%))&
%2
F/(2Lay(5t#
#n this type of layout the components added are placed one after the other in a ro% until
they fill it up. /fter filling a ro%$ the components are placed in the next ro%. The
alignment of components in a ro% can be specified as :HGT$ B#Z9T or CH3TBH.
1efault is %$N-*$. The alignment is given as integer parameter to the constructor .
ConstructorF -low;ayout (int align) align is one o(
-low;ayout;+-6
-low;ayout,/\O6
-low;ayout4+36,+
0('6e'Lay(5t#
The =order:ayout divides the area to be laid out into five areas$ called 36BT9$
S60T9$ H/ST$ 8HST and CH3TBH.
3orth
8est Centre Hast
South
The borders are defined first and the remaining available space is occupied by the centre.
8hen the container is resi?ed$ the thic'ness of the borders is unchanged$ but the centre
area changes its si?e.
Components are added by specifying a string %hich indicates the area %here the
component should be placed. 6ne can specify =North>1 =South>1 =$ast>1 =<est> 1 or
=%entre>, /ll the positions need not be occupied. 9eres an example of using a border
layout managerF
paneladd(!+ast%* new Scrollbar())&
=order :ayout is the default for frames and other %indo%s.
%3
G'!6Lay(5t#
The Zrid:ayout layout manager divides the container into a grid. So components can be
placed in ro%s and columns. Class Zrid:ayout is inherited directly from the class 6bject
and implements the :ayoutManager interface. Hach component is given the same si?e.
Components are added to Zrid:ayout starting at the top2left cell of the grid proceeding
from left2to2right until the ro% is full. Then$ the process continues left2to2right on the
next ro% etc. The Zrid:ayout classs constructors are summarised.
9ridLayout %onstructors
public \rid;ayout ( int rows * int columns )&
11rows - number o( rows
11columns - number o( columns
Constructs a Zrid:ayout of ro%s ro%s and columns columns.
public \rid;ayout (
int rows* 11number o( rows
int columns* 11number o( columns
int 5* 115oriSontal spacing between components
int v )& 11vertical spacing between components
Constructs a Zrid:ayout %ith each component separated hori?ontally by h pixels and
vertically by # pixels.
Zrid:ayout organises the components in ro%s and columns.
$&le) SourceGile F StudyZrid.java
import javaawt2&
import javaawtevent2&
public class Study\rid e:tends -rame implements )ction;istener*
Pindow;istener
{.utton a.utton[] = new .utton[9]&
.utton plus.tn = new .utton(T F T)&
.utton minus.tn = new .utton(T - T)&
.utton Luit.tn= new .utton(TZuitT)&
int 5\ap =8*v\ap =8&
public static void main(String args[])
{Study\rid t5e)pp = new Study\rid()&
'
public Study\rid()
{set6itle(T65e Study\rid )pplicationT)&
set-ont(new -ont( TOelveticaT*-ont.0;H*>Q))&
%4
set;ayout(new \rid;ayout(E*?))&
(or(int i=8&iKa.uttonlengt5&iFF)
{a.utton[i]=new .utton(T.uttonT Fi)&
add(a.utton[i])&
'
add(plus.tn)&
add(minus.tn)&
add(Luit.tn)&
plus.tnadd)ction;istener(t5is)&
minus.tnadd)ction;istener(t5is)&
Luit.tnadd)ction;istener(t5is)&
addPindow;istener(t5is)&
pack()&
setUisible(true)&
'
public void action#er(ormed()ction+vent t5e+vent)
{i( (t5e+ventgetSource()==plus.tn)
{5\apF=>&
v\apF=>&
reS5ow()&
return&
'
i( (t5e+ventgetSource()==minus.tn)
{ 5\ap-= (5\apJ8N>=8)&
v\ap-=(v\apJ8N>=8)&
reS5ow()&
return&
'
i( (t5e+ventgetSource()==Luit.tn)
Luit)pplication()&
'
public void window4losed(Pindow+vent e) { '
public void window4losing(Pindow+vent e)
{ Luit)pplication()& '
public void windowHeiconi(ied(Pindow+vent e) { '
public void window/coni(ied(Pindow+vent e) { '
public void window0pened(Pindow+vent e) { '
public void window)ctivated(Pindow+vent e) { '
public void windowHeactivated(Pindow+vent e) { '
public void Luit)pplication()
{ setUisible((alse)&
dispose()&
Systeme:it(8)&
'
public void reS5ow()
{
set;ayout(new \rid;ayout(E*?*5\ap*v\ap))&
pack()&
'
'
%5
G'!60a3Lay(5t
The most complex of the predefined layout managers is Zrid=ag:ayout. The
Zrid=ag:ayout layout manager is similar to the Zrid:ayout layout manager because
Zrid=ag:ayout also arranges components in a grid. 9o%ever Zrid=ag:ayout is more
flexible. The components can vary in si?e and can be added in any order.
9rid3ag%onstraints )
The Zrid=agConstraints specifies three pieces of information.
the si?e and location %ithin the container of the components cell F %idth and height
may span multiple ro%s and columns
the si?e and location %ithin the cell of the component
%hat happens to the cell %hen the container is resi?ed.
nstance #ariable Description
gridx The column in %hich the component %ill be placed.
gridy The ro% in %hich the component %ill be placed.
grid%idth The number of columns the components occupies.
gridheight The number of ro%s the component occupies.
%eightx The portion of extra space to allocate vertically. The
components in a ro% can become 5taller7 %hen extra
space is available.
%eighty The portion of extra space to allocate hori?ontally. The
components in a column can become 5%ider7 %hen extra
space is available.
%6
Steps in adding table components in 9rid3agLayout)
,. Create an object of Zrid=ag:ayout.
;. Set this Zrid=ag:ayout object as the layout manager for the container object.
*. Create an object of Zrid=agConstraints.
>. Gor each component to be placed in the containerF assign the values for the
Zrid=agConstraints instance attributes.
A. #n the layout object$ call method set4onstraints() %ith the component name
and constraints object defined above. This tells the layout manager %here to place
the component
@. /dd the component to the container as usually.
$&le)
\rid.ag;ayout layout = new \rid.ag;ayout()&
panelset;ayout (layout)&
\rid.ag4onstraints constraints = new \rid.ag4onstraints()&
constraintsweig5t: = 188&
constraintsweig5ty = 188&
constraintsgrid: = 8&
constraintsgridy = 8&
constraintsgridwidt5 = 1&
constraintsgrid5eig5t = ?&
;ist style = new ;ist (E)&
layoutset4onstraints (style* constraints)&
paneladd(style)&
(sing No layout managerF
#n this there is no layout manager used. The program has to give the absolute positions of
change to place the object.
The :ayout should be set to null using set:ayout(null+&
The components position and si?e can be specified using the method
void reshape(int x2position$ int y2position$ int %idth $ int height+
Ca'6Lay(5t#
#n Card:ayout$ unli'e the other layouts$ the components are placed one belo% the other
as a dec' of cards. 6ne can specify %hich card can be on the top. =y this a functionality
of more than one component is achieved in the same place. Hach card is mostly a panel.
The card i.e if it is a container can use any layout.
.ormat) add(String cardWobjectWname * #anel object)
%$
The procedure starts %ith setting the Card:ayout manager as belo%F
#anel cards = new #anel()&
4ard;ayout c;ayout = new 4ard;ayout()&
cardsset;ayout (c;ayout)&
p1 = new #anel()&
p> = new #anel()& 11creation o( panel
cardsadd(!card1%* p1)&
11 identi(ying panel p1 wit5 name !card1%
11and add to t5e deck o( cards
cardsadd(!card>%* p>)&
11 identi(ying panel p> wit5 name !card>%
11adding panel p> to t5e deck o( cards
There are A methods to place a card on top.
;ayout0bjectne:t (4ontainer parent) c;ayoutne:t (cards)
;ayout0bjectprevious (4ontainer parent) c;ayoutprevious (cards)
;ayout0bject(irst (4ontainer parent) c;ayout(irst (cards)
;ayout0bjectlast(4ontainer parent) c;ayoutlast (cards)
;ayout0bjects5ow(4ontainer parent* String nameWo( Wcard)
c;ayouts5ow (cards* !card1%)
parent is t5e container wit5 4ard;ayout
$&le) SourceGile F Card:ayoutTest.java
import javaawt2&
import javaawtevent2&
public class 4ard;ayout6est e:tends -rame
{ public static void main(String []args){
-rame ( = new 4ard;ayout6est()&
(resiSe(?>8* >88)&
(s5ow()&
'
public 4ard;ayout6est()
{ set6itle (T4ard;ayout6estT)&
tabs = new #anel()&
tabsadd(new .utton(TKKT))&
tabsadd(new .utton(TKT))&
tabsadd(new .utton(T0ptionsT))&
tabsadd(new .utton(TSettingsT))&
tabsadd(new .utton(T#re(erencesT))&
tabsadd(new .utton(TJT))&
tabsadd(new .utton(TJJT))&
add(T3ort5T* tabs)&
cards = new #anel()&
layout = new 4ard;ayout()&
%%
cardsset;ayout(layout)&
cardsadd(T0ptionsT* new SimpleHialog(T0ptionsT))&
cardsadd(TSettingsT* new SimpleHialog(TSettingsT))&
cardsadd(T#re(erencesT* new SimpleHialog(T#re(erencesT))&
add(T4enterT* cards)&
'
public boolean 5andle+vent(+vent evt)
{ i( (evtid == +ventP/3H0PWH+S6,0[) Systeme:it(8)&
return super5andle+vent(evt)&
'
public boolean action(+vent evt*0bject arg)
{ i( (evttarget instanceo( 4omponent __
((4omponent) evttarget)get#arent()eLuals(tabs))
{ i( (argeLuals(TKKT)) layout(irst(cards)&
else i( (argeLuals(TKT)) layoutprevious(cards)&
else i( (argeLuals(TJT)) layoutne:t(cards)&
else i( (argeLuals(TJJT)) layoutlast(cards)&
else layouts5ow(cards*(String)arg)&'
else return superaction(evt*arg)&
return true&
'
private #anel cards&
private #anel tabs&
private 4ard;ayout layout&
'
class SimpleHialog e:tends #anel
{ SimpleHialog(String name)
{ set;ayout(new .order;ayout())&
add(T4enterT* new ;abel(name F Tdialog goes 5ereT))&
#anel p = new #anel()&
padd(new .utton(T0YT))&
add(TSout5T* p)&
'
'
%+
D!a/(3 0(&e:
/ 1ialog box is a border test %indo% %ith a title bar. 1ialog boxes are used to get or
sho% information to the user. These %indo%s are displayed %hen data is re<uired to be
input or output and disposed %hen #!6 is complete. They can have components and have
to provide event handling for each component held.
1ialog boxes are of t%o types 2 (,+ Modal 1ialog box and (;+ Modeless 1ialog box. /
modal 1ialog box forces the user to close the 1ialog box before he %ants to interact %ith
any other component. #n a Modeless 1ialog box %e can interact %ith other objects as
%ell.
/8T provides a class called 1ialog. The user can inherit from this class to create his o%n
1ialog boxes and provide the re<uired function to the component present in it and to
itself. The default layout is =order:ayout.
StepsF ,. #nherit the 1ialog class.
;. Call the 1ialog class constructor in the inherited class. The arguments are
parent class$ and boolean. The boolean argument indicates %hether the
1ialog box is Modal or Modeless.
*. Set :ayout of 1ialog box
>. /dd controls to the 1ialog box
A. To display the 1ialog box create a ne% 1ialog object and invo'e the
sho% method.
$&le) SourceGile F 1ialogTest.java
public class Hialog6est e:tends -rame
{ public Hialog6est()
{ set6itle(!Hialog6est%)&
#anel p = new #anel()&
pset;ayout (new -low;ayout (-low;ayout;+-6))=
padd(new .utton(!)bout%))&
padd(new .utton(!4lose%))&
add(!3ort5%* p)&
'
public boolean action (+vent evt* 0bject arg)
{ i((argeLuals(!)bout%))
{ )boutHialog ab = new )boutHialog(t5is)&
abs5ow()&
'
else i( (argeLuals(!4lose%))
{ Systeme:it(8)&
'
else return superaction(evtarg)&
return true&
'
public boolean 5andle+vent(event evt)
+1
{ i( (evtid == +ventP/3H0PWH+S6,0[ __ evttarget ==t5is)
Systeme:it(8)&
return super5andle+vent(evt)&
'
public static void main(String args[ ])
{ -rame ( = new Hialog6est()&
(resiSe(?88* >88)&
(s5ow()&
'
'
class )boutHialog e:tends Hialog
{ public )boutHialog(-rame parent)
{ super(parent* !)bout Hialog6est%* true)&
#anel p1 = new #anel()&
p1add(new ;abel(!4ore"ava%))&
p1add(new ;abel(!.y \ary 4ornell and 4ay Oorstmann%))&
add(!4enter%* p1)&
#anel p> = new #anel()&
p>add(new .utton(!0Y%))&
add(!Sout5%* p>)&
resiSe(>>8* 1D8)&
'
public boolean action(+vent evt* 0bject arg)
{ i((argeLuals(!0Y%))
{ dispose()&
return true&
'
return (alse&
'
public boolean 5andle+vent(+vent evt)
{ i( (evtid= = +ventP/3H0PWH+S6,0[ __ evttarget == t5is)
Systeme:it(8)&
'
Data e&.,a"3!"3 *'(- a"6 t( D!a/(3 8(&#
The information in the 1ialog box cannot be obtained from its object because its scope is
lost as soon as it is closed. Specific interface is to be follo%ed to get data from 1ialog
box.
Steps in getting data "rom Dialog bo&)
,. 1eclare class involving the 1ialog box$ to implement Besultrocessor interface.
;. #mplement the method process,esult().
*. #n the method$ chec' if the source is an instance of the re<uired 1ialog class.
>. Then create an object to contain actual data and use the same to extract the data
from the 1ialog box.
This gives the values of the variables and hence usable.
+1
#n the action method after disposing the 1ialog call the process,esult() method as
belo%.
((,esult#rocessor) get#arent())#rocess,esult (t5is* new in(oWobject
(valueWone* valueWtwo)
$&le)
The program reads the dimensions for a rectangle using a 1ialog box. The program uses
the ColorBect class discussed earlier. The program is in t%o source files.
Compile ColorBect.java $ source files given belo% and run the 1ialogText class.
SourceGile F .al1ialog.java
import javaawt2&
import javaawtevent2&
inter(ace Ualue#rocessor{
public void process,esult(Hialog source* 0bject obj)&
'
class UalHialog e:tends Hialog {
private .utton ok=new .utton(T0kT)&
private .utton cancel=new .utton(T4ancelT)&
private 6e:t-ield Ualue]&
private 6e:t-ield Ualue[&
private 6e:t-ield UalueP&
private 6e:t-ield UalueO&
public UalHialog(Hialog6e:t parent* /nteger :i*/nteger yi) {
super(parent*TUaluesT*true)&
Ualue] = new 6e:t-ield(:itoString())&
Ualue[ = new 6e:t-ield(yitoString())&
UalueP = new 6e:t-ield(TPidt5T)&
UalueO = new 6e:t-ield(TOeig5tT)&
set;ayout(new \rid;ayout(D*>))&
add(new ;abel(TUalue]T))&add(Ualue])&
add(new ;abel(TUalue[T))&add(Ualue[)&
add(new ;abel(TUaluePT))&add(UalueP)&
add(new ;abel(TUalueOT))&add(UalueO)&
add(ok)&add(cancel)&
resiSe(>88*>88)&
'
public boolean 5andle+vent(+vent evt) {
i( (evtid == +ventP/3H0PWH+S6,0[) {
dispose()&
return true&
'
else return (super5andle+vent(evt))&
'
+2
public boolean action(+vent evt*0bject obj) {
i( (evttarget instanceo( .utton){
i( (objeLuals(T0kT)) {
int :val = /ntegerparse/nt(Ualue]get6e:t())&
int yval = /ntegerparse/nt(Ualue[get6e:t())&
int wval = /ntegerparse/nt(UaluePget6e:t())&
int 5val = /ntegerparse/nt(UalueOget6e:t())&
((Ualue#rocessor)get#arent())process,esult(t5is*
new 4olor,ect(:val*yval*wval*5val*4olorred))&
dispose()&
'
i( (objeLuals(T4ancelT))
dispose()&
return true&
'
return superaction(evt*obj)&
'
'
Source-ile Hailog6e:tjava
public class Hialog6e:t e:tends -rame implements Ualue#rocessor {
private ;abel lblHim = new ;abel(TT)&
private 4olor,ect crect &
public Hialog6e:t(String p6itle) {
super(p6itle)&
set;ayout(new .order;ayout())&
#anel butpan = new #anel()&
butpanset;ayout(new \rid;ayout(1*>))&
butpanadd(new .utton(T,ectangleT))&
butpanadd(new .utton(T+:itT))&
add(T3ort5T*lblHim)&
add(TSout5T*butpan)&
'
public boolean action(+vent evt* 0bject obj) {
i( (evttarget instanceo( .utton) {
i( (objeLuals(T,ectangleT)) {
/nteger :in = new /nteger(18)&
/nteger yin = new /nteger(18)&
UalHialog dv= new UalHialog(t5is*:in*yin)&
dvset,esiSable((alse)&
dvs5ow()&
'
i( (objeLuals(T+:itT))
Systeme:it(8)&
'
return superaction(evt*obj)&
'
public boolean 5andle+vent(+vent evt) {
i( (evtid == +ventP/3H0PWH+S6,0[) {
Systeme:it(8)&
return true&
'
else return (super5andle+vent(evt))&
'
+3
public void process,esult(Hialog source* 0bject result){
i( (source instanceo( UalHialog) {
crect = (4olor,ect)result&
lblHimset6e:t(crecttoString())&
repaint()&
'
'
public void paint(\rap5ics g){
gset-ont(new
-ont(TOelveticaT*-ont.0;HF-ont/6);/4*>8))&
i( (crect $= null)
crectdraw(g)&
'
public static void main(String args[]){
-rame (rm = new Hialog6e:t(THialogsT)&
(rmresiSe(D88*?D8)&
(rms5ow()&
'
'
6utut F This is the %indo% before 1ialog box is used.
This is the 1ialog box displayed
+4
This is the %indo% after the dialogue box has gone.
F!/eD!a/(3 8(&
Java provides Gile1ialog class to access file name in system for opening or saving.
Constructor F
+ile,ialo% -+rame parent, Strin% title, int mode.
Creates a -ileHialog object for loading or saving a file.
arametersF
parent the o%ner of the 1ialog
title the title of the 1ialog
mode the mode of the 1ialog$ one of :6/1 or S/.H
Methods of Gile1ialog classF
2 set-ilename-ilter (-ilename-ilter (ilter)&
+5
11sets t5e initial (ile mask (or t5e (ile dialog
2 setHirectory (String dir)&
11set t5e initial directory (or t5e (ile dialog
2 set-ile(String (ile)&
11sets t5e de(ault (ile c5oice (or t5e (ile dialog
2 String get-ile()&
11gets t5e (ilename t5at t5e user selected (or returns null i(
t5e
11 user didnBt select any (ile)
The follo%ing procedure may be follo%ed to use Gile1ialog class.
,. Ma'e a Gile1ialog object say d.
dset-ile3ame-ilter (!2t:t%)& !! to set initial filter to select only .txt files.
dsetHirectory(!%)& !! sets the current directory as the initial directory.
;. Then sho% the dialog box.
dset-ile ((ilename)& !!To select 5filename7 as initial selection
ds5ow()&
0nli'e the s5ow() call for a regular dialog box$ this call does not return until the
user has filled in the file dialog box. The selected file is returned %ith the
get-ile() method. #f the user cancels the dialog$ get-ile() returns null.
(ilename = dget-ile()&
HxampleF SourceGile F JavaGile.java
import javaio2&
import javaawt2&
import javaawtevent2&
import javautil2&
class "ava-ilesHia e:tends -ileHialog{
public "ava-ilesHia(-rame (*int type){
super((*(type==-ileHialog;0)HNTopenT=TS)U+T)FTH/);0\T*type)&
setSiSe(Q88*>D8)&
s5ow()&
'
public String get-ile()
{ return superget-ile()&'
'
public class "ava-ile e:tends -rame implements )ction;istener*
Pindow;istener
{
private 6e:t)rea -ile6:t&
private String j-ile3ame &
+6
private .utton open = new .utton(T0penT)&
private .utton save = new .utton(TSaveT)&
private .utton e:it = new .utton(T+:itT)&
public "ava-ile() {
-ile6:t = new 6e:t)rea(>8*Q8)&
set;ayout(new -low;ayout())&
add(open)&
add(save)&
add(e:it)&
add(TSout5T*-ile6:t)&
openadd)ction;istener(t5is)&
saveadd)ction;istener(t5is)&
e:itadd)ction;istener(t5is)&
addPindow;istener(t5is)&
setSiSe(1888*E88)&
setUisible(true)&
'
public String get-ile6e:t()
{ String.u((er sbu( = new String.u((er(D1>)&
String te:t( = new String()&
try{ int c5&
-ile,eader (r = new -ile,eader(j-ile3ame)&
w5ile ((c5=(rread())$=-1)
sbu(append((c5ar)c5)&
te:t( = sbu(toString()&
return(te:t()&
'
catc5(/0+:ception ioe){
Systemerrprintln(ioegetGessage())&
'
return(te:t()&
'
public void action#er(ormed()ction+vent e)
{
i( (egetSource() == open) {
"ava-ilesHia j( = new
"ava-ilesHia(t5is*-ileHialog;0)H)&
j-ile3ame = j(get-ile()&
-ile6:tset6e:t(get-ile6e:t())&
'
i( (egetSource() == e:it) {
setUisible((alse)&
dispose()&
Systeme:it(8)& '
'
public void window4losed(Pindow+vent e) { '
public void window4losing(Pindow+vent e) {
+$
setUisible((alse)&
dispose()&
Systeme:it(8)& '
public void windowHeiconi(ied(Pindow+vent e) { '
public void window/coni(ied(Pindow+vent e) { '
public void window0pened(Pindow+vent e) { '
public void window)ctivated(Pindow+vent e) { '
public void windowHeactivated(Pindow+vent e) { '
public static void main(String args[] ){
-rame ( = new "ava-ile()&
'
'
+%
4 E N U S
Menus allo% the user to perform direct or indirect actions. Menus can be built only for
frames.
/ menu contains a menubar$ on the top of 8indo% and contains menu items and submenu
items. 8hen user clic's on a menu item$ if it has a submenu item$ the submenu is
displayed else a method corresponding to the menu item is executed.
Java has a set of classes to support menus$ namely Menu=ar and Menu#tem. =oth are sub
classes of MenuComponent class.
Menu#tem class contains constructors and methods to handle menu items. / menu item
can be a command to execute or it can be another menu called a submenu.
Menu class contains menu items and are added to Menu =ars. The chec'Menu#tem class
is a menu item that toggles bet%een t%o states similar to a chec' box component.
Steps in adding a Menu)
,. Create a Menu=ar object
Genu.ar bar = new Genu.ar()&
;. Create a Menu object
Genu (ontmenu = new Genu ( A(ontB ) &
*. /dd Menu#tems to Menu
(ontmenuadd(new Genu/tem (!6imes,oman%))&
(ontmenuadd(new Genu/tem (!4ourier%))&
(ontmenuadd(new Genu/tem (!/talic%))&
>. /dd the menu to the Menu=ar
baradd ((ontGenu)&
A. set the menubar of the frame %ith setGenu.ar(bar)
setGenu.ar (bar)&
@. #f a submenu is to be added create a menu %ith menu items for the sub menu.
/dd the menu to the main menu exactly as a menu #tem is added.
Genu StyleGenu = new Genu (!Style%)&
StyleGenuadd (new Genu/tem (!/talic%))&
StyleGenuadd (new Genu/tem (!.old%))&
StyleGenuadd (new Genu/tem (!<nderline%))&
(ontGenuadd (StyleGenu)&
++
To add a separator bar$ add a Menu#tem %ith !-% hyphen as name or the method
addSeparator()&
6ne can get or set the state of a c5eckbo:Genu/tem either %ith method
setState() to set the state to true or false
getState() to get the current state of Menu#tem
$&le) SourceGile F MenuHxample.java
import javaawt2&
import javaawtevent2&
public class Genu+:ample e:tends -rame implements )ction;istener*
Pindow;istener
{
Genu.ar .ar = new Genu.ar()&
Genu GainGenu = new Genu(TGainT)&
Genu ZuitGenu = new Genu(TZuitT)&
Genu/tem .P/tem = new Genu/tem(T.PT)&
Genu/tem 4olor/tem = new Genu/tem(T4olorT)&
Genu/tem ,ed/tem = new Genu/tem(T,edT)&
Genu/tem .lue/tem = new Genu/tem(T.lueT)&
Genu/tem +:it/tem = new Genu/tem(T+:itT)&
public static void main(String args[]){
Genu+:ample t5e)pp = new Genu+:ample()&
'
public Genu+:ample(){
super(TG+3< +])G#;+T)&
setGenu.ar(.ar)&
.aradd(GainGenu)&
.aradd(ZuitGenu)&
GainGenuadd(.P/tem)&
GainGenuadd(4olor/tem)&
GainGenuaddSeparator()&
GainGenuadd(,ed/tem)&
GainGenuadd(.lue/tem)&
ZuitGenuadd(+:it/tem)&
4olor/temset+nabled((alse)&
.P/temadd)ction;istener(t5is)&
4olor/temadd)ction;istener(t5is)&
,ed/temadd)ction;istener(t5is)&
.lue/temadd)ction;istener(t5is)&
+:it/temadd)ction;istener(t5is)&
addPindow;istener(t5is)&
set.ackground(4olorblue)&
setSiSe(?>8*>E8)&
setUisible(true)&
'
111
public void action#er(ormed()ction+vent t5e+vent){
i( (t5e+ventgetSource() == +:it/tem)
Luit)pplication()&
i( (t5e+ventgetSource()== .P/tem)
{
set.ackground(4olorw5ite)&
.P/temset+nabled((alse)&
4olor/temset+nabled(true)&
,ed/temset+nabled(true)&
.lue/temset+nabled(true)&
'
i( (t5e+ventgetSource()== 4olor/tem)
{set.ackground(4olorw5ite)&
.P/temset+nabled(true)&
4olor/temset+nabled((alse)&
,ed/temset+nabled((alse)&
.lue/temset+nabled((alse)&
'
i( (t5e+ventgetSource()== ,ed/tem)
set.ackground(4olorred)&
i( (t5e+ventgetSource()== .lue/tem)
set.ackground(4olorblue)&
invalidate()&
validate()&
'
public void window4losed(Pindow+vent e) { '
public void window4losing(Pindow+vent e)
{ Luit)pplication()& '
public void windowHeiconi(ied(Pindow+vent e) { '
public void window/coni(ied(Pindow+vent e) { '
public void window0pened(Pindow+vent e) { '
public void window)ctivated(Pindow+vent e) { '
public void windowHeactivated(Pindow+vent e) { '
public void Luit)pplication()
{ setUisible((alse)&
dispose()&
Systeme:it(8)&
'
'
111
A ; ; L E T S
/pplets are compiled java programs that are run using the /pplet.ie%er or through any
bro%ser that supports. #t can display graphics$ sounds$ accept user input and manipulate
data just li'e any program. / separate 9TM: file should be created %ith details as name
of class file$ location of the class and the applets position on the 8eb page. /pplets
inherit the properties of the anel object and the /pplet class attributes.
App/!.at!(" V App/et
/pplications are self contained programs and execute in an independent environment. The
execution starts in the main method of one of the public classes defined in an application.
/n /pplet is a program$ %hich is meant for execution in bro%ser environment. /pplets
are the major capabilities of J/./ %hich ma'e it the 8eb language. Hach /pplet has to
define multiple entry points of the program(methods+ %hich are invo'ed in the bro%ser
environment in different contexts.
Security restrictions)
/pplets are generally loaded from a remote site and then executed locally. Bestrictions
are&
2 applets can never run any local executable program
2 applets cannot communicate %ith any host other than the server from %hich they
%ere do%n loaded
2 applets cannot read or %rite to the local computers file systems.
(dependent on the bro%ser+
2 applets cannot find any information about the local computer$ except for java
version used$ name and version of operating system$ characters used to separate
files& paths and lines.
Vie7ing Applet) To vie% an /pplet %e can use one of the methods belo%F
,. Applet #ie7er) This provided by Sun along %ith J1]. The /pplet.ie%er
ta'es the name of the 9TM: file containing the /pplet tag.
This %ill sho% the /pplet in the 9TM: file. #t %ill sho% only the /pplet tag
and not other text of the 9TM: file. #f the 9TM: file contains multiple /pplets
each /pplet %indo%s sho%n is a %indo%.
;. Any <eb 3ro7serF There are t%o %ays of opening. 6ne is to use the open
file option and give the 9TM: file name or by open location option giving the
112
file 0B: as belo%F
(ile=111+=1jtrg1OelloO6G; 2 using file 0B:.
Applet !-ML tags)
/pplet tag 2 K)##;+6 40H+ = !classname% P/H6O = widt5 in pi:els
O+/\O6 = 5eig5t in pi:elsJK1)##;+6J
40H+ 2 specifies name of class %ith .class extension.
P/H6O 2 specifies the %idth of the %indo% that holds the /pplet.
O+/\O6 2 specifies the height of the %indo% that holds the /pplet.
3)G+ 2specifies name of /pplet to be referred by other applets
);/\3 2specifies the alignment of the /ppletF
The value of the attribute can be one of F
;+-6 2 /pplet aligned to the left margin of the page
,/\O6 2 /pplet aligned to the right margin of the page
.0660G 2 =ottom of /pplet at the bottom of the text in current line
60# 2 Top of /pplet %ith top of the current line
G/HH;+ 2 Middle of the /pplet %ith the base line of the current line
.)S+;/3+ 2 =ottom of the /pplet %ith the base line of the current line
US#)4+ 2 specifies the number of pixels above and belo% the
OS#)4+ /pplet (US#)4++ and on each side of the /pplet(OS#)4++
40H+.)S+ 2 This optional attribute tells java that class files are found
belo% the directory %here current page is located.
$&leF #f an /pplet called Girst /pplet 2 class in directory named My/pplets$
and the My/pplets directory is belo% the current location.
K)##;+6 40H+ = !-irst)ppletclass% 40H+.)S+ = !Gy)pplets% P/H6O=188
O+/\O6=188J
/n 9TM: file for an /pplet %ith minimum Tags
KO6G;J
KO+)HJK6/6;+J )pplet title K16/6;+JK1O+)HJ
K.0H[J
- - - can write te:t also 5ere ---
K)##;+6 40H+J = !classname% P/H6O=widt5 in pi:els O+/\O6=5eig5t in
pi:elsJ
K1)##;+6J
K1.0H[J
113
K1O6G;J
$&le) The /pplet ta'es values from t%o text fields multiplies them displays the
result as a label. SourceGile F Calc.java
import javaapplet2&
import javaawt2&
import javaawtevent2&
public class 4alc e:tends )pplet implements )ction;istener {
6e:t-ield (irstHouble = new 6e:t-ield (18)&
6e:t-ield secondHouble=new 6e:t-ield (18)&
.utton mul.utton = new .utton (T2T)&
;abel t5e0utput =new ;abel (T99*99*99*99999T)&
public void init() {
add((irstHouble)&
add(mul.utton)&
add(secondHouble)&
add(t5e0utput)&
mul.uttonadd)ction;istener(t5is)&
'
public void action#er(ormed()ction+vent e) {
Houble (irst = Houblevalue0(((irstHoubleget6e:t())&
Houble second=Houblevalue0((secondHoubleget6e:t())&
double result=(irstdoubleUalue() 2 seconddoubleUalue()&
t5e0utputset6e:t(T = T F result)&
'
'
9TM:Gile F /ppl.html
KO6G;J
KO+)HJK6/6;+J Gultiplication o( Houbles K16/6;+JK1O+)HJ
K.0H[J
K)##;+6 40H+ = 4alcclass O+/\O6=1D8 P/H6O=188J K1)##;+6J
K1.0H[J
K1O6G;J
114
T,e /!*e .y./e (* a" App/et#
There are four methods in the /pplet class namely init(+$ start(+$ stop(+ and destroy(+ on
%hich the applets are built.
init() /ll initiali?ations for the /pplet are done in this method and %or's li'e a
constructor. This is called automatically by the system %hen java launches
the /pplet for the first time.
start() This method is called automatically after java calls the init(+ method. This
is also called %henever the user returns to the page containing /pplet after
having gone off to other pages.
stop() This method is automatically called %hen the user moves off the page on
%hich the /pplet sits. This method should not be called directly. #t is
basically used to stop a time consuming activity from slo%ing do%n the
system$ %hen user is not paying attention to the /pplet.
destroy() This method is called %henever the bro%ser shuts do%n normally..
$&le) /pplet demonstrating the life cycle of an /pplet.
SourceGile F :ifeTime.java
11/llustrates messages sent (rom t5e browser to t5e applet
import javaawt2&
import javaapplet2&
public class ;i(e6ime e:tends )pplet
{
11attributes
int init,cvd*start,cvd*stop,cvd*destroy,cvd*pain,cvd&
11Get5ods
115
public void init() {
add(new ;abel(TGessages recieved in an appletXs ;i(etimeT))&
init,cvdFF&
'
public void start(){ start,cvdFF&repaint()&'
public void stop() {stop,cvdFF& repaint()& '
public void destroy(){destroy,cvdFF&repaint()&'
public void paint(\rap5ics jacLues)
{
pain,cvdFF&
jacLuesdrawString(Tinit() =TFinit,cvd*18*E8)&
jacLuesdrawString(Tstart() =TFstart,cvd*18*DD)&
jacLuesdrawString(Tstop() =TFstop,cvd*18*@8)&
jacLuesdrawString(Tdestroy()=TFdestroy,cvd*18*QD)&
jacLuesdrawString(Tpaint() =TFpain,cvd*18*188)&
'
'
9TM:Gile F lifetime.html
KO6G;J
KO+)HJK6/6;+J)pplets ;i(e6ime K16/6;+JK1O+)HJ
K.0H[J
K)##;+6 40H+ = ;i(e6imeclass O+/\O6=1D8 P/H6O=>D8J K1)##;+6J
K1.0H[J
K1O6G;J
F
;a!"3 !"*('-at!(" t( App/et
Similar to passing values to a method a user can pass parameters to an /pplet also. To
pass values to /pplets along %ith the )##;+6 tag$ a #),)G tag is used immediately after
the K)##;+6J tag to %hich the parameters are to be passed.
GormatF K#),)G 3)G+=!parameterWname%U);<+=!parameterWvalue%J
The values parameterIname and parameterIvalue are case sensitive.
116
$&le) K)##;+6 40H+=!-igclass% P/H6O%=188 O+/\O6=?88J
K#),)G 3)G+=!color% U);<+=!blue%J
K)##;+6J
The values passed %ith /B/M tag can be accessed %ith get#arameter() method in the
/pplet.
.ormatF String get#arameter(parameterWname)
The method returns the value of the parameter %hose name is passed as a string. The
value returned is of String type. Method get#arameter() must be called %ith respective
name of the parameter for %hich the value is to be retrieved.
$&le) String colorname = get#arameter(!color%)
$&le) rogram to read a parameter$ for the font $ from the html file and display
text %ith the same font in the /pplet.
SourceGile F /pplet,.java
import javaapplet)pplet&
import javaawt2&
public class )pplet1 e:tends )pplet
{
public void update(\rap5ics g) {
paint(g)&
'
public void paint(\rap5ics g) {
String (ontname = get#arameter(T-036T)&
-ont (on = new -ont((ontname*-ont.0;H*1E)&
set-ont((on)&
set.ackground(4oloryellow)&
gdrawString((ontnameFT is t5e (ontT*D8*D8)&
'
'
9TM:Gile F //B/MS.9TM:
KO6G;J
KO+)HJK6/6;+J #assing values to t5e applet K16/6;+JK1O+)HJ
K.0H[J
K)##;+6 40H+ = )pplet1class O+/\O6=>88 P/H6O=E88J
K#),)G 3)G+=T-036T U);<+=TOelveticaTJ
K1)##;+6J
K1.0H[J
K1O6G;J
11$
Applet %onte&t /ppletContext is a class %hich represents the /pplet i.e the bro%ser in
%hich the /pplet is executed. 6n most bro%sers$ this information can be used to control
the bro%ser in %hich the /pplet is running. /lso one can get a reference to other applets
running in the =ro%ser. This is a po%erful feature because a reference to other applets
can be obtained and interaction bet%een /pplets can be achieved.
/n /ppletContext can be obtained %ith the get)pplet4onte:t() method of the /pplet
class.
.ormatF public )pplet4onte:t get)pplet4onte:t()&
$&le) )pplet4onte:t cont = get)pplet4onte:t()&
The )pplet4onte:t class has the follo%ing methods.
void s5owStatus (String mesg) This %ill print the String mesg on the status bar of
the 8eb bro%ser.
+numeration get)pplets() returns an Hnumeration of all the /pplets in current
context i.e on the same 8eb2page.
)pplet get)pplet(String name) returns the /pplet in the current context. Beturns
null if the /pplet of the given name is not
present.
void s5owHocument (<,; url) The method displays %eb page specified by 0B:.
void s5owHocument (<,; url*String target)
The method displays %eb page specified by
0B: in the frame specified by the target
string.
image get/mage (<,; url) returns an image
)udio4lip get)udio4lip (<,; url)
returns an /udioClip$ returns null if no image
11%
I"te'App/et C(--5"!.at!("
To communicate %ith an /pplet from another /pplet$ a reference to the /pplet is
re<uired. #t is obtained from the get/pplet(+ method of the /ppletContext %hich in turn
is obtained by the get/ppletContext(+ method of the /pplet running. The reference to the
methods and variables of the /pplet are obtained. #f needed user can send information to
the /pplet and hence can also execute the methods of the other /pplet.
$&le ) SourceGile F /pp,.java.
The first /pplet program %hich has the data re<uired by the second /pplet program /pp;
import javaapplet)pplet&
import javaawt2&
import javaawtevent2&
11 65e (irst applet program inter applet communication
public class )pp1 e:tends )pplet {
private String applet3ame = new String(TPelcome to S6<T)&
public void init(){
-ont (on = new -ont(TOelveticaT*-ont.0;H*1E)&
set-ont((on)&
'
public String get)pp3ame() {
return applet3ame&
'
public void update (\rap5ics g) {
paint (g)&
'
public void paint (\rap5ics g) {
set.ackground (4oloryellow)&
gdrawString (T)pplet oneT*D8*D8)&
'
'
SourceGile F /pp;.java F The second applet program ta'ing data from /pp,
import javaapplet)pplet&
import javaapplet2&
import javaawt2&
import javaawtevent2&
public class )pp> e:tends )pplet implements )ction;istener{
11+
private String (nt =new String()&
private .utton g-= new .utton(T\et GessageT)&
public void init()
{
g-add)ction;istener(t5is)&
add(g-)&
'
public void update(\rap5ics g) {
paint(g)&
'
public void action#er(ormed()ction+vent e){
i( (egetSource() == g-) {
)pplet4onte:t ac = get)pplet4onte:t()&
)pplet capp = acget)pplet(T)pp1T) &
(nt = (()pp1)capp)get)pp3ame()&
-ont (on = new -ont((nt*-ont.0;H*1E)&
set-ont((on)&
'
'
public void paint(\rap5ics g) {
set.ackground(4oloryellow)&
gdrawString(T65e message CTTF (nt F TCT is obtained (rom
)pp1T*D8*D8)&
'
'
9TM:Gile F /pp,.html. The html file to run the applet programs.
KO6G;J
KO+)HJK6/6;+J /nter )pplet 4ommunication K16/6;+JK1O+)HJ
K.0H[J
K$,unning applet )pp1 J
K)##;+6 3)G+=T)##1T 40H+ = )pp1class O+/\O6=ED8 P/H6O=D88J
K1)##;+6J
K$,unning applet )pp> J
K)##;+6 3)G+=T)##>T 40H+ = )pp>class O+/\O6=ED8 P/H6O=D88J
K1)##;+6J
K1.0H[J
K1O6G;J
111
111
E&.ept!(" Ha"6/!"3
$rrors
/n error is the failure of a function or process to successfully carry out its assigned tas'$
because of some directly controllable parameter or condition. rogrammers resorted to a
variety of %ays to handle errors$ li'e terminating the program$ returning a special value
from the function on detecting an error.
#t is the responsibility of the programmer to chec' for the return values of the functions
and ta'e appropriate action %hen a function fails.
$&ceptions
Hxceptions refer to abnormal conditions that occur during a programs execution$ li'e
division by ?ero$ arithmetic or array overflo%$ running out of memory etc. They can be
outright errors that cause the program to fail or conditions that can lead to errors. The
central mission of exception handling is to transfer control from %here the error occurred
to an error handler that can deal %ith the situation.
Hxceptions are raised (or thro%n+ as a result of either hard%are or soft%are events$
usually beyond the direct control of the program.
%lass hierarchy
-hro7able
Hxception Hrror
#nternal 6ut of 0n'no%n
Buntime #6 Hxception Hrror Memory Hrror
Hxception
/rithmetic 3ull ointer #ndex 6ut of
Hxception =ounds
112
The error class hierarchy represents internal errors and there is little that can be done
except notifying the user and trying to terminate the program gracefully.
Hxceptions are represented by objects$ %hich have properties similar to other Java objects.
Hxceptions are raised (or thro%n+ %henever an unusual condition arises in the course of
the execution of a program$ BuntimeHxception occurs because of programming error and
#nput 6utput exception occurs because a bad thing such as #!6 error etc.$ has happened.
$&ception-handling synta&
Hxception handling in a program is using t%o major bloc's 2 try bloc'$ and catch bloc'.
Java uses 'ey%ords namely try and catch for try and catch bloc's respectively. The
last catch bloc' is optionally follo%ed by a finally bloc'.
.ormat)
try{ 11block o( statements
'
catc5(e:ceptionWclassW1 e:ceptionWvariableW1) {
11e:ceptionW5andlerWprogramWbody
'
catc5 (e:ceptionWclassW> e:ceptionWvariableW>) {
11e:ceptionW5andlerWprogramWbody
'
(inally { 11e:itWprogramWbody
'
thro%
function that raises
exception
thro%
try =loc'
#nvo'e a function
that causes an exception
catch =loc' ,
Hxception catch =loc' ; no
catch =loc' * exceptoin
finally bloc'
executed regardless
of exception raised
or not
113
T'y 8/(.<
/n exception that occurs must be caught so as to handle it. This is done by enclosing the
statements that may thro% an exception in a try bloc'. 8hen an exception is thro%n$ it is
caught by a handler specified by a catch bloc' immediately follo%ing that try bloc'.
#t is not necessary to give try bloc's for each exception that may be thro%n. /ll of them
can be enclosed in a single try bloc' and provide catch bloc's for each type of the
exception.
/ catch bloc' defined by the 'ey%ord catch$ catches the exceptions thro%n and handles it.
Hach catch bloc' is also called an Hxception 9andler$ and the type of exception it can
handle is given as argument. Hach try bloc' can have a number of associated catch bloc's
and are tried in the order of appearance.
/fter the last catch bloc'$ an optional finally bloc' contains code that is al%ays executed
regardless of %hether or not an exception occurs. This is useful %hen cleanup operations
li'e closing files$ releasing resources etc.$ are to be performed.
$&ecution Se?uenceF
,. rogram follo%s normal flo% control and reaches the try bloc' and begins
executing.
;. #f no exception is thro%n during execution of the try bloc'$ all the catch bloc's
follo%ing the try bloc' are s'ipped. Control goes to the statement after the
last catch bloc'.
*. #f an exception is thro%n during execution of the try bloc' (either directly or
indirectly+$ an exception object is created.
>. The catch bloc's are scanned se<uentially for an exception type matching the
exception that %as thro%n.
A. #f a matching catch bloc' is found$ the code in the catch bloc' is executed and
the program resumes execution from the statement$ immediately after the last
catch bloc'.
@. #f no matching catch bloc' is found the exception is propagated to the next
higher enclosing bloc' of code. #f a matching catch is found there$ it is
executed and any remaining catch bloc's at that level are s'ipped. 6ther%ise$
the java run time system terminates the program.
114
C. #f a finally bloc' is provided it is executed even if no exception is thro%n.
8hen an exception is raised and a matching catch bloc' is found$ finally bloc'
is executed.
6nce an exception is thro%n$ the bloc' in %hich the exception is thro%n expires and
control cannot return to the thro% point.
Control goes to catch bloc' only if an exception is thro%n.
115
$&le F The program defines an array of t%o objects of int type but tries to access the
array %ith an index of -$ crossing the maximum index. The output is a message from the
exception object caught.
SourceGile F Hxception,.java
class +:ception1{
public static void main(String []args){
int k&
try{
Systemoutprintln(T/nner try blockT)&
int Sero = 8&
int[] c = new int[>]&11)rray o( two objects created
k = c[9]& 11 trying to access object 9
'
catc5 (/nde:0ut0(.ounds+:ception e) {
Systemoutprintln(e)&
'
'
'
0utput =
/nner try block
javalang)rray/nde:0ut0(.ounds+:ception= 9
#n the statement k=c[9] the array index is - %hich is more than the defined range of c
array i.e. ; . 9ence an exception called )rray/nde:0ut0(.ounds is thro%n. The
exception thro%n is caught in the catch bloc'. #n the catch bloc'$ message indicating that
the array index is out of range is displayed.
The same code if not caught in try catch bloc' as belo% a BunTimeHxception is thro%n
and the program stops.
SourceGile F Hxception;.java
class +:ception>{
public static void main(String []args){
int k&
Systemoutprintln(T/nner try blockT)&
int Sero = 8&
int[] c = new int[>]&
11)rray o( two objects o( int created* Oence ma:imum inde: is 1
k = c[9]&11 array inde: greater t5e ma:imium limit
'
'
116
6utput F
/nner try block
javalang)rray/nde:0ut0(.ounds+:ception= 9
at +:ception>main(+:ception>java=R)
-hro7ing $&ceptions ) Hxceptions are thro%n either by statements or methods. The
'ey%ord throw is used to raise an exception by a statement %ithin a method.
HxampleF #f a file length is say$ len),E;> bytes. 8hile trying to read this file in a
method$ if an error (say end of file+ occurs after reading *AE characters an
exception has to be thro%n.
%hile ( 2222222+
X if (ch ) ) 2,+ !!H6G encountered
X if (n Olen+
thro% ne% H6GHxception(+&
Y
2 2 2 2
Y
Steps in thro%ing an HxceptionF
2 find an appropriate exception class
2 ma'e an object of that class
2 thro% the exception object using 'ey%ord thro%
8henever a Java method has an exception thro%ing statement$ it has to be indicated to
the users of this method$ the type of exception it is going to raise by using thro%s clause.
Gormat of code to thro% an exception
returnWdatatype met5odWname (parameter-declarations) t5rows e:ception-
1* e:ception->* e:ception-?
{ met5odWcodeKblockJ '
/lternatively the method has to handle the exception.
11$
$&le ) To illustrate thro%ing an Hxception
Source-ile = +:cep4lassjava
public class +:cep4lass{
public static void main(String[] args){
try{
t5rowsGet5od()&
'
catc5(+:ception e){
Systemoutprintln( T+:ception 5andled in mainT)&
'
nott5rowsGet5od()&
'
public static void t5rowsGet5od() t5rows +:ception{
try{
Systemoutprintln( TGet5od t5rowsGet5odT)&
t5row new +:ception()&
'
catc5(+:ception e){
Systemerrprintln( T+:ception 5andled in met5od
t5rowsGet5odT)&
t5row e&
'
(inally {
Systemerrprintln( Tt5rowsGet5od=-inally is always
e:ecutedT)&
'
'
public static void nott5rowsGet5od(){
try {
Systemoutprintln( TGet5od nott5rowsGet5odT)&
'
catc5(+:ception e){
Systemerrprintln(etoString())&
'
(inally {
Systemerrprintln( Tnott5rowsGet5od=-inally is always
e:ecutedT)&
'
'
'
0utput=
Get5od t5rowsGet5od
+:ception 5andled in met5od t5rowsGet5od
t5rowsGet5od=-inally is always e:ecuted
+:ception 5andled in main
Get5od nott5rowsGet5od
nott5rowsGet5od=-inally is always e:ecuted
11%
11+
Ue' 6e*!"e6 E&.ept!(" #
Standard exceptions are used %ith the use of standard classing. 8hile for the customised
classes to have their o%n exceptions one can construct exception classes %hich may be
derived from the Hxception class. 8hen these user defined exceptions are used they are
to be thro%n explicitly at the positions re<uired$ %hich are in turn caught in try bloc's and
handled in the catch bloc's. Gor the catch bloc's to catch the exceptions the parameter in
the catch bloc' should be of the ne%ly defined exception type.
$&le +) )n e:ception class UserException is de(ined. /t is t5rown
in t5e met5od e:cpmet5od() and is caught in other method as
given belo%.
Source-ile = <ser4lassjava
class <ser+:ception e:tends +:ception {
public <ser+:ception(){
super(TUalue0ut0(,angeT)&
'
public <ser+:ception(String str){
super(TUalue0ut0(,ange = TFstr)&
'
'
public class <ser4lass{
public void e:cpmet5od(int val) t5rows <ser+:ception {
i( (val J E88)
t5row new <ser+:ception(TUalue TFval)&
else
{Systemoutprintln(TUalue T FvalFT is in ,angeT)&'
'
public static void main(String []args){
<ser4lass uc = new <ser4lass()&
try {
uce:cpmet5od(>88)&
uce:cpmet5od(R88)&
'
catc5 (<ser+:ception uen){
Systemoutprintln(uengetGessage())&
'
'
'
$&le : F Thro%ing exception. SourceGile F BeadString.java
import javaio2&
public class ,eadString{
public static void main(String []args)t5rows +0-+:ception* /0+:ception{
int c5=8&
String s=new String()&
c5=Systeminread()&
121
w5ile (true){
i( (c5 == -1) {
Systemoutprintln(sFT is t5e string givenT)&
t5row new +0-+:ception()&
'
else
s=sF(c5ar)c5&
c5=Systeminread()&
'
'
'
Methods in -hro7able class ) Methods most often used in the Throwa$le objects.
getGessage() returns the descriptive message related to the error
toString() returns the exception objects name and message.
$&le )
System.out.println(5#nner /rithmetic exception7 " eobj.getMessage(++&
The statement in any catch bloc' displays the descriptive message of the exception caught
i.e. eobj
printStac4-race56 outputs an error message %ith class name of the exception to the
standard error stream$ the descriptive String stored in the exception and a list of the
methods that had not completed execution %hen the exception %as thro%n. (i.e all the
methods currently re%inding on method call stac'+.
$&le @ ) user de(ined e:ception /nvalid ,adius +:ception is t5rown
w5enever t5e value o( radius is 8 or negative
Source-ile = 4irclejava
class /nvalid,adius+:ception e:tends +:ception {
public /nvalid,adius+:ception(){
t5is(T65e radius is not validT)&
'
public /nvalid,adius+:ception(String mesg){
super(T,adius is not valid T F mesg)&
'
'
public class 4ircle{
protected int radius&
public 4ircle(){ t5is(8)& '
public 4ircle(int pWradius) t5rows /nvalid,adius+:ception{
i( (pWradius K 8)
t5row new /nvalid,adius+:ception(T,adius= TFpWradius)&
else {
121
radius = pWradius&
Systemoutprintln(T4ircle 0k$ ,adius = TFradius)&
'
'
public static void main(String args[]) {
try {
4ircle cr = new 4ircle(E8)&
4ircle c( = new 4ircle(-19)&
'
catc5(/nvalid,adius+:ception ire){
Systemoutprintln(iregetGessage())&'
'
'
6utput F
4ircle 0k$ ,adius = E8
,adius = -19
%ommon $&ceptions
ClassNotFoundExceptionF This class extends Hxception. #t is thro%n if a class cannot
be found.
NoSuchMethodExceptionF Hxtends Hxception. Thro%n %hen a method could not be
found.
RuntimeExceptionF /n exception thro%n by the .irtual Machine. 0sers are not
forced to catch these exceptions.
ArithmeticExceptionF Hxtends Buntime Hxception. #t is thro%n %hen an
arithmetic exception li'e divide by ?ero occurs.
NullPointerExceptionF Hxtends Buntime Hxception. #t is thro%n any time a null
object is used to access a method.
ArrayStoreExceptionF Hxtends Buntime Hxception. Thro%n %hen an attempt is
made to store the %rong type in an array.
NegativeArraySieExceptionF extends Buntime Hxception. Thro%n if an attempt is
made to create an array %ith a negative si?e.
!llegalArgumentExceptionF Hxtends Buntime Hxception. #ndicates illegal argument
has occurred.
Num"erFormatExceptionF Hxtends #llegal/rgumentHxception. Thro%n if an invalid
number format occurs.
!ndex#ut#$%oundsExceptionF Hxtends Buntime Hxception. Thro%n if an #ndex is out
of bounds
Array!ndex#ut#$%ounds &Hxtends /nde:0ut0(.ounds '
String!ndex#ut#$%ounds
SecurityExceptionF Hxtends ,untime+:ception. #t is thro%n if there is a
violation of the security policy set by the
securityManager class.
122
C(--(" E''('
'irtualMachineErrorF Hxtends Hrror. #t signifies that .irtual machine has run out
of resources or it has an unrecoverable internal error.
Stac(#verFlo)ErrorF Hxtends UirtualGac5ine+rror #t signals that Java virtual
machines runtime stac' has overflo%ed.
#ut#$MemoryErrorF Hxtends UirtualGac5ine+rror. #t occurs %hen Java run time
can not satisfy memory re<uest.
123
I"p5t ) O5tp5t
I"t'(65.t!("
Stream F
/ stream is a se<uence of bytes or characters. 1ata moves into and out of a program
through stream. Streams act as source and destination of data. Streams are of t%o types 2
#nput and 6utput stream. #nput stream acts as source of data %hile output stream acts as
destination of data from a program. 8henever a java application or /pplet is executed$
three stream objects are automatically available. They are&
Systemin 2 standard input stream object ('eyboard+
Systemout 2 standard output stream object (screen+
Systemerr 2 standard error stream object (screen+
Gor input and output of data$ Java provides t%o types of abstract classes. 6ne type deals
%ith stream of bytes %hile the other %ith the stream of characters. Hach type has t%o
classes one for input and the other for output.
/nputStream 2 input is read from a stream of bytes.
0utputStream 2 output is %ritten to a stream of bytes.
,eader 2 input is read from a stream of characters.
Priter 2 output is %ritten to a stream of characters.
HIERARCHY OF READER =RITER CLASSES
*$AD$*
StringBeader ipeBeader GileBeader Char/rray
Beader
Gilter Beader
=uffered :ine3umber ushbac'
Beader Beader Beader
<*-$*
124
Gile 8riter Char /rray String Giltered iped
8riter 8riter 8riter 8riter
=uffered find ush bac'
%riter 8riter %riter
HIERARCHY OF STREA4 CLASSES
nput Stream
String=uffer =yte/rray Gile#nput Gilter#nput iped#nput Se<uence
#nputStream Stream Stream Stream #nputStream
=uffered#nput ushbac' :inenumber 1ata#nput
Stream #nputStream #nputStream Stream
#mplements
O(-P(- S-*$AM
1ata#nput
=yte/rray Gilter6utput Gile6utput iped6utput
6utputStream Stream Stream Stream #mplements
=uffered rintStream 1ata6utput Bandom/ccessGile
6utputStream Stream
1ata 6utput
#nputStream and Beader classes have the follo%ing methods to be used for input of data
from streamsF
int read() Beads and returns a byte from the input stream and %hen
the input is not available it returns 2,.
int read(byte dest[]) Beads and stores the bytes to an array given as a
parameter and returns number of bytes actually
read.
125
int read(byte dest[] * Bead and store bytes to a part of an array given by the
int start*int lengt5 ) starting index 5start7 and the length of the array to be filled
by 5length7 and returns number of bytes read.
void close() closes the stream$ releases system resources from the
object
int available() Beturns the no of bytes that can be read %ithout bloc'ing
i.e. the no of bytes in the buffer.
long skip(long nbytes) /ttempts to s'ip a specified number of bytes from the
data source. 9ence the next read operation reads the
nbytes", nth byte %here nbytes is the number of
bytes s'ipped.
0utputStream and Priter classes have the follo%ing methods for output to streamsF
void write(int b) F %rites the byte b to the output stream.
void write(byte b[]) F %rites an array of bytes bST to the output stream.
void write(byte b[]*int start* int lengt5) F %rites a part of an array bST starting
form index start upto a length of the array length to be read
for the output.
void (lus5() F %rites out any bytes in the buffer to the stream
void close() F closes the file and releases system resources from the object
The classes above allo% to read and %rite only individual bytes!char and array of
bytes!chars. They cannot read!%rite data in the streams in terms of basic data types
directly.
F!/e t'ea- :
/ file is valued as a se<uential stream of bytes. 8hen a file is opened an object is created
and a stream is associated %ith the object. The input or output is from or to a file i.e. the
source or destination is a file. Java library derives four classes from the above abstract
classes for the input !output to the files stream. They are as given belo%.
-ile/nputStream 2 Gor input from files as byte streams 2 derived from
/nputStream
-ile0utputStream 2 Gor output to files as byte streams 2 derived from
0utputStream
-ile,eader 2 Gor input from files as Character streams 2 derived from ,eader
-ilePriter 2 Gor output to files as Character streams2 derived from Priter
%reation o" "ile objects)
-ile/nputStream -ile/nputStream(String pat5) 6pen an #nputStream to file for
input as described by path
Hxample F -ile/nputStream (ileis = new
-ile/nputStream(!/tems%)&
126
The example creates an input file stream for the physical file
5#tems7.
-ile/nputStream -ile/nputStream(-ile (ile) 6pen an #nputStream to file for
input as described by file. / Gile is a class containing the details of a
file i.e. name$ si?e$ date of creation etc.
Hxample F
-ile/nputStream (ileis = new -ile/nputStream(/tem()&
The example creates an input file stream object for the Gile object
5#temf7 already defined.
Hxample F
-ile/nputStream (ileis =new -ile/nputStream(item(d)&
The example creates an input file stream object from for a
-ileHescriptor object itemfd already defined.
-ile0utputStream Gile6utputStream(String path+ 6pen an output stream for output to
file as described by path
Hxample F
-ile0utputStream (ileos = new
-ile0utputStream(!/tems%)&
The example creates an output file stream for the file 5#tems7
-ile0utputStream -ile0utputStream(-ile (ile) 6pen a file stream for 6utput of
data$ described by Gile object 5file7
Hxample F -ile0utputStream (ileos = new
-ile0utputStream(/tem()&
The example creates an output file stream for a class Gile object
5#temf7 already defined.
-ile,eader This class is an input stream for characters of a file.
-ile,eader(String pat5)6pen an input stream to a file in character mode as described
by path.
Hxample F -ile,eader (ilerd = new -ile,eader(!/tems%)&
The example creates an input stream for a file 5#tems7
-ile,eader(-ile (ile) 6pen an input stream to file in character mode as described
by Gile object 5file.7
Hxample F GileBeader filerd ) ne% GileBeader(#temf+&
The example creates an input file stream for a Gile class object
5#temf7 already defined.
-ile,eader(-ileHescriptor (d) 6pen an input stream to file in character mode as
described by -ileHescriptor object fd
Hxample F -ile,eader (ilerd = new -ile,eader(item(d)&
12$
The example creates an input file stream for an object of the
Gile1escriptor filerd already defined.
-ilePriter(String pat5) 6pen an output stream to file in character mode as described
by path
HxampleF -ilePriter (ilewt = new -ilePriter(!/tems%)&
The example creates an output file stream for the file 5#tems7
-ilePriter(-ile (ile)6pen an output stream to file in character mode as described by
Gile object 5file.7
Hxample F -ilePriter (ilewt = new -ilePriter(/tem()&
The example creates an output file stream from an object 5#temf7
of class Gile already defined.
-ilePriter(-ileHescriptor (d) 6pen an output stream to file in character mode as
described by Gile1escriptor object fd
Hxample F -ilePriter (ilewt = new -ilePriter(item(d)&
The example creates an output file stream for an object 5itemfd7
of class -ileHescriptor already defined.
$&le) Bead a file 5estream.java7 and display using GileBeader class.
SourceGile F stream.java
import javaio2&
import javautil2&
public class stream{
public static void main (String[] args) {
try {
int c5=8&
-ile,eader (br = new -ile,eader(TestreamjavaT)&
do {
c5 = (brread()&
i( (c5 $= -1)
Systemoutprint((c5ar)c5)&
'w5ile(c5 $= -1)&
(brclose()&
'
catc5(-ile3ot-ound+:ception (l)
{ Systemoutprintln(T-ile is not (oundT)& '
catc5(/0+:ception (lo)
{ Systemoutprintln(T/0+:ception=F(logetGessage())& '
'
'
12%
HxampleF Bead a file 5estream.java7 and display using Gile#nputStream class.
Source-ile = istreamjava
import javaio2&
import javautil2&
public class istream{
public static void main (String[] args) {
-ile i(ile = new -ile(!estreamjava!)&
try {
int c5=8&
-ile/nputStream (is = new -ile/nputStream(i(ile)&
do {
c5 = (isread()&
i( (c5 $= -1)
Systemoutprint((c5ar)c5)&
'w5ile(c5 $= -1)&
(isclose()&
'
catc5(-ile3ot-ound+:ception (l)
{
Systemoutprintln(T-ile is not (oundT)&
'
catc5(/0+:ception (lo)
{
Systemoutprintln(T/0+:ception = TF(logetGessage())&
'
'
'
F!/te' I"p5t>O5tp5tSt'ea-#
The filter stream provides additional functionality such as buffering$ monitoring line
numbers or aggregating data types into meaningful primitive2data2type units.
-ilter/nputStream - (ilters an /nputStream
-ilter0utputStream - (ilters an 0utputStream
05**e'e6St'ea-#
=uffering is used to improve #!6 performance. 1ata is stored temporarily in memory
called bytes. 8henever the buffer is full$ the re<uired input!output operation is performed.
/ subclass of class -ilter/nputStream 2 data is read and stored into a memory buffer.
rogram ta'es data from the buffer.
12+
/ subclass of class -ilter0utputStream 2 Hach output statement transfers data to
memory buffer. /ctual output to the output device is performed in one physical output
operation. / partially filled buffer can be forced out to the device at any time$ %ith an
explicit (lus5()
$&le) Bead from a file 5estream.java7 in to a buffer called 5line7. Contents of
the buffer are read and displayed on the screen.
SourceGile F bistream.java
import javaio2&
import javautil2&
public class bistream{
public static void main (String[] args) {
-ile (name = new -ile(TestreamjavaT)&
try {
int bu(siSe = RE&
int rbytes=8&
.u((ered/nputStream bir = new .u((ered/nputStream(
new -ile/nputStream((name))&
byte line[] = new byte[bu(siSe]&
do {
rbytes = birread(line* 8* bu(siSe)&
(or (int i=8&iKrbytes&iFF)
Systemoutprint((c5ar)line[i])&
'w5ile(rbytes J= RE)&
birclose()&
'
catc5(-ile3ot-ound+:ception (l) {
Systemoutprintln(T-ile T F(nameFT is not (oundT)&
'
catc5(/0+:ception (lo) {
Systemoutprintln(T/0+:ception = TF(logetGessage())&
'
catc5(+:ception (loe) {
Systemoutprintln(T+:ception = TF(loegetGessage())&
'
'
'
DataSt'ea- :
Most often the data used in applications is of type integer$ float$ long $string etc. and not
in the form of bytes. The stream classes or reader!%riter classes %hich are subclasses of
the input!output streams or reader!%riter classes respectively deal directly %ith the
input!output stream of bytes or characters. The input!output here is as a se<uence of
131
bytes or characters. 9ence it is re<uired that the input!output must be in the form of the
data types i.e.$ as an integer$ double $ a character or as a string. To achieve this Java has
the follo%ing classes.
DatanputStream F
Beads binary data from an #nputStream. There are reader!%riter classes for datastreams.
The constructor is defined as belo%F
The constructor for the class has an input stream as a parameter. The data is ta'en from
this #nputStream and then filtered to return the data in a formatted %ay i.e. as a standard
datatype.
Hata/nputStream(/nputStream is)
2 Creates a Hata/nputStream from an /nputStream is.
This class has methods to read the data in any primary data type in Java. The follo%ing are
the methods in 1ata#nputStream. Most of the methods are in the form of readOdatatypeP
%hich implies the method gets a value of type OdatatypeP from the stream.
boolean read.oolean() - reads and returns a boolean value (rom t5e
stream
byte read.yte() - reads and returns a byte value (rom t5e stream
int read<nsigned.yte() - reads and returns an <nsigned value (rom t5e
stream
s5ort readS5ort() - reads and returns a s5ort value (rom t5e
stream
int read<nsignedS5ort()-reads and returns an <nsigned s5ort value (rom
t5e stream
c5ar read45ar() - reads and returns a c5aracter value (rom t5e
stream
int read/nt() - reads and returns an integer value (rom t5e
stream
long read;ong() - reads and returns a long integer value (rom
t5e stream
(loat read(loat() - reads and returns a (loat value (rom t5e
stream
double readHouble() - reads and returns a double value (rom t5e
stream
String read<6-() - reads and returns a string value (rom t5e
stream
%part from the a$ove (ataInput"tream also has the following methods&
static String read<6-(Hata/nput di()
Beads an 0TG string from specified data input stream
void read-ully(byte[] dest )
/ttempts to fill the byte array dest %ith bytes from source
void read-ully(byte[] dest * int o((set* int legt5)
:i'e readGully above but only attempts to fill a part of the byte array.
131
void skip.ytes(int nbytes)
:i'e readGully above$ but discards bytes rather than storing in an array.
DataOutputStream F 8rite binary data to an 0utputStream.
The constructor creates a Hata0utputStream from an 0utputStream object 5dest7
Hata0utputStream(0utputStream dest)
#t has the follo%ing methods of the form void %rite(datatype datavalue+ %hich %rites the
datavalue of the type datatype to the destination stream.
void write.oolean(boolean b) - writes a boolean value into t5e stream
void write.yte(int i) - writes a byte value into t5e stream
void writeS5ort(int i) - writes a s5ort value into t5e stream
void write/nt(int i) - writes an integer value into t5e stream
void write;ong(long l) - writes a long integer value into stream
void write-loat((loat () - writes a (loat value into t5e stream
void writeHouble(double d) - writes a double value into t5e stream
void write45ars(String s) - writes a string value into t5e stream
void write.ytes(String s) - writes a string value into t5e stream
void write<6-(String s) - writes an <6- string value into t5e
stream
$&le ) rogram to %rite logical records containing names of cities and their codes
to a file called 5cities7 using the 1ata6utputStream class
132
SourceGile F dostream.java
import javaio2&
import javautil2&
public class dostream{
public static void main (String[] args) {
-ile (name = new -ile(TcitiesT)&
11create logical (ile (rom p5ysical (ile
try {
int codes[] = {1* >* ?* E* D* R* @* Q* 9* 18'&
String cities[] = {
! Hel5i%* ! 45ennai%* ! .angalore%*
! 4alcutta%* ! Oyderabad%* ! .5opal%*
! Secunderabad%* ! Gumbai%* ! #atna%*
! Uisak5apatnam% '
11create Hata0utputStrem (rom (ile 0utputStream
Hata0utputStream dos = new Hata0utputStream(
new -ile0utputStream((name))&
(or(int i=8&iK18&iFF) {
11write records to stream
doswrite/nt(codes[i]F1>8)&
doswrite<6-(cities[i])&
'
dosclose()&
'
catc5(/0+:ception (lo) {
Systemoutprintln(T/0+:ception = TF(lo)&
'
catc5(+:ception (loe) {
Systemoutprintln(T+:ception = TF(loe)&
'
'
'
6utput F The data in array is %ritten to the file 5cities7
$&le) rogram reads records from the file 5cities7 created above using
1ata#nputStream class.
SourceGile F distream.java
import javaio2&
import javautil2&
public class distream{
public static void main (String[] args) {
133
-ile (name = new -ile(TcitiesT)&
11create logical (ile (rom p5ysical (ile
try {
int code = 8&
String city = new String()&
11create data /nputStream (rom (ile /nputStrem
Hata/nputStream dis = new Hata/nputStream(new
-ile/nputStream((name))&
(or(int i=8&iK18&iFF)
{ 11,ead data (rom strem
code = disread/nt()&
city = disread<6-()&
Systemoutprintln(T4ity is TFcityFT 4ode isT Fcode)&
'
disclose()&
'
catc5(-ile3ot-ound+:ception (n(){
Systemoutprintln(T/0+:ception = TF(n()&
'
catc5(/0+:ception (lo) {
Systemoutprintln(T/0+:ception = TF(lo)&
'
catc5(+:ception (loe) {
Systemoutprintln(T+:ception = TF(loe)&
'
'
'
!"#!"=
4ity is Hel5i 4ode is 1>1
4ity is 45ennai 4ode is 1>>
4ity is .angalore 4ode is 1>?
4ity is 4alcutta 4ode is 1>E
4ity is Oyderabad 4ode is 1>D
4ity is .5opal 4ode is 1>R
4ity is Secunderabad 4ode is 1>@
4ity is Gumbai 4ode is 1>Q
4ity is #atna 4ode is 1>9
4ity is #atna 4ode is 1>9
4ity is Uisak5apatnam 4ode is 1?8
;'!"t t'ea- ./ae:
134
The rint Str e a m and rint8riter classes have methods that support printing text. The
rintStream is based on 6utputStream and rint8riter is based on the 8riter class. They
print data of any type in the form of text. T%o methods are available.
,+ void print(datatype datavariable)= The value given by argument 5datavalue7
of type 5datatype7 %ill be printed to the stream in text form.
;+ void println(datatype datavariable): The value given by argument 5datavalue7
of type 5datatype7 %ill be printed to the stream in text form$ follo%ed by a ne% line
character. So any subse<uent printing starts from a ne% line.
The datatype may be any one of the follo%ing F
char, int , lon%, float, double , boolean , char/0 , Strin% , bject,
/part from these another method$
void println() 2 %ithout arguments prints a ne% line character into the stream.
$&le) rogram to print integer and string data %ith variable names 5codes7 and
5names7 to a file called 5person7.
SourceGile F pstream.java
import javaio2&
import javautil2&
public class pstream{
public static void main (String[] args) {
-ile (name = new -ile(TpersonT)& 11create a logical (ile
try {
int codes[] = {18* >8* ?8* E8* D8'&
String names[] = { !Siva%* !45andra%*!Sek5ara%* !3ages5%*
!;aks5mi% '
11create a printStrem (rom -ile0utputStream
#rintPriter pw = new #rintPriter(
new -ile0utputStream((name))&
(or(int i=8&iKD&iFF){ 11print data to stream
pwprint(codes[i]F188)&
pwprint(names[i])&
'
pwclose()&
'
catc5(/0+:ception (lo) {
Systemoutprintln(T/0+:ception = TF(lo)&
'
catc5(+:ception (loe) {
Systemoutprintln(T+:ception = TF(loe)&
'
'
'
135
Output ) The data is %ritten in the file 5person7
Ra"6(-A..eF!/e :
This type of files are useful for direct!instant access application li'e airline reservations$
=an' systems etc. Hach re<uest li'e input!output re<uest may be directed to any part of
the file. / variety of techni<ues can be used to create random2access files$ the simplest is
to use fixed length records.
Java provides a class$ ,andom)ccess-ile to deal %ith such files. #t provides methods to
read and %rite to a file.
The class provides a filepointer variable. The filepointer al%ays indicates the position of
the next record that %ill be read or %ritten. The seek() method sets the file pointer to the
byte position given by argument. The argument to see' is a long integer bet%een ?ero and
the length of the file in bytes. The get-ile#ointer() method returns the current position
of the filepointer.
,andom)ccess-ile implements Hata/nput and Hata0utput interfaces. 9ence for #!6
same methods namely read/nt()* read<6-() as for Hata/nputStream and
write/nt()* write<6-() as for Hata0utputStream can be used.
HxampleF rogram to create a random access file$ %rite to the file and display the
contents of the file.
SourceGile F B/GStream.java
import javaio2&
import javautil2&
public class ,)-Stream{
private -ile ra(-ile&
private ,andom)ccess-ile ra(stream&
static int ma:,ecords=8&
public ,)-Stream(String (ilename) t5rows -ile3ot-ound+:ception*
/0+:ception
{ -ile c-ile =new -ile((ilename)&
ra(stream = new ,andom)ccess-ile(c-ile*TrwT)&
'
public void writeHata() t5rows /0+:ception
{
int codes[] = {18* >8* ?8* E8* D8'&
String names[] =
{TS5ankarT* TSivaT* T+swarT* T3arayanaT* T.ra5maT'&
(or(int i=8&iKD&iFF){
ra(streamseek((long)i2>E;)&
ra(streamwrite/nt(codes[i])&
ra(streamwrite<6-(names[i]FTCnT)&
136
'
ma:,ecords=E&
'
public void get,ecord)t(int p/d) t5rows /0+:ception
{
int code=8& String name = new String()&
int len=8&
ra(streamseek((long) p/d2>E;)&
code=ra(streamread/nt()& 11read integer (rom (ile
name=ra(streamread<6-()& 11read name (rom (ile
Systemoutprintln(codeFT M TFname)&
'
public void get,ecord-or/d(int p/d) t5rows /0+:ception
{
int code=8& String name = new String()&
int len=8*i=8&
do {
ra(streamseek((long)i2>E;)&
code=ra(streamread/nt()&
name=ra(streamread<6-()&
iFF&
' w5ile(iK=ma:,ecords __ code$=p/d)&
i( (i J ma:,ecords)
Systemoutprintln(T,ecord wit5 /d TFp/dFT not (oundT)&
else
Systemoutprintln(codeFT M TFname)&
'
public void append(String pWname*int pWid) t5rows /0+:ception
{
ma:,ecordsFF&
ra(streamseek((long)(ma:,ecords)2>E;)&
ra(streamwrite/nt(pWid)&
ra(streamwrite<6-(pWnameFTCnT)&
'
public void close()t5rows /0+:ception {
ra(streamclose()&
'
public static void main(String[] args) t5rows -ile3ot-ound+:ception*
/0+:ception
{
,)-Stream ra( = new ,)-Stream(new String(TempdatT))&
ra(writeHata()&
ra(get,ecord)t(1)&
ra(get,ecord)t(8)&
ra(append(T"yotiT*1D)&
ra(get,ecord)t(1)&
13$
ra(get,ecord)t(?)&
ra(get,ecord)t(D)&
ra(append(TYiranT*ED)&
ra(get,ecord-or/d(>8)&
ra(get,ecord-or/d(1D)&
ra(close()&
'
'
!"#!"=
>8 M Siva
18 M S5ankar
>8 M Siva
E8 M 3arayana
1D M "yoti
>8 M Siva
1D M "yoti
St'ea-T(<e"!:e' C/a#
Stream To'enising means brea'ing of the input text into to'ens. The to'enising provides
a %ay of analysing the text$ li'e source code of C$ C"" or Java. The to'ens are
recognised by different delimiter characters li'e space# $rac)ets# punctuation mar)s# ta$s#
new lines etc. There are > different types of to'ens$ namely num$er# words# end of line
and end of file.
Java provides a class called StreamTo'eni?er. The stream is built over an #nput stream.
The method ne:ttoken() gets the next to'en from the stream. The method returns an int
representing the type of to'en. The value of the to'en is stored in instance variables. #f
the to'en is a number$ the value is stored in n#al variable else if it is a %ord its value is
stored in s#al.
$&le) To read an input stream and to'enise it to display on screen.
SourceGile F streamto'ens.java
import javaio2&
import javautil2&
public class streamtokens
{
public static void main (String[ ] args)t5rows -ile3ot-ound+:ception*
/0+:ception
13%
{ -ile (name = new -ile (T),,6+S6")vaT)&
int bu(siSe = RE&
int rbytes = 8& 11 open a stream tokeniSer (or above (ile
Stream6okeniSer stj = new Stream6okeniSer(new -ile,eader ((name))&
int type&
11 get tokens one by one until end o( (ile
w5ile ((type=stjne:t6oken()) $= Stream6okeniSer66W+0-){
switc5(type) { 11 c5eck token type
case Stream6okeniSer66W3<G.+,= 11 i( number print nval
Systemoutprint(stjnval)&break&
case Stream6okeniSer66WP0,H= 11i( word print sval
Systemoutprint(stjsval)&break&
case Stream6okeniSer66W+0;= 11i( end o( line print TCnT
Systemoutprint(TCnT)&break&
'
'
'
'
The file arrtest.java before to'eni?ing
public class arrtest{
public static void main(String [] args){
long -ibanocci[]={Ql* DQ9l*R9l*@9Q@l'&
long 6ower0(Oanoi[][] = { {18*9*Q*@*R*D*E*?*>*1'*{'*{''&
11declare a two
Systemoutprint(-ibanocci[>])&
Systemoutprint(T;+3TF6ower0(Oanoilengt5)&
'
'
O(-P(-) The file arrtest.java after streamto'eni?ing.
publicclassarrtestpublicstaticvoidmainStringargslong-ibanocciQ8lDQ98l
R98l@9Q@8llong6ower0(Oanoi18898Q8@8R8D8E8?8>818Systemoutp
rint-ibanocci>8Systemoutprint6ower0(Oanoilengt5
-he LineNumberOutputStream and LineNumber*eader %lassesF
These classes maintain a counter of the lines read from the source. / line is a se<uence of
bytes terminated %ith a ACrB or ACnB character.
-he S e ?u e nc eOut put St r e a m cl a s s F
The Se<uence6utputStream class is a mechanism for combining t%o or more 6utput
streams. / se<uence 6utput stream reads from its first 6utput stream until that stream is
exhausted& #t then discards the +nd0(-ile+:ception (rom (irst stream and starts
reading from its second 6utput stream and so on until the last 6utput stream returns 2,.
13+
Stri ng3u" " er cl as s e s F
String.u((er/nputStream 2 Gor 6utput from Strings as byte streams
2 derived from 6utputStream
2Constructor creates a stream from String str
String.u((er/nputStream(String str)
String,eader 2 Gor 6utput from Strings as Character streams
2 derived from Beader
2Constructor creates a reader from String str
String,eader(String str)
StringPriter 2 Gor output to Strings as Character streams
2 derived from 8riter
2Constructors
StringPriter() creates a %riter
StringPriter(int siSe) creates a %riter of si?e 5si?e7
;!pe6 I"p5t>O5tp5t St'ea-#
ipes are synchroni?ed communication channels bet%een threads. / pipe is established
bet%een t%o threads.
Class areF
#iped0utputStream! 2 6ne thread sends data to another thread using
#ipedPriter #iped0utputStream1 #ipedPriter.
#iped/nputStream! 2 thread reads information from pipe using
#iped,eader #iped/nputStream1 #iped,eader.
141
45/t!t,'ea6!"3
Java is uni<ue among general purpose programming languages in that it ma'es
concurrency primitives available to the personal computer applications programmer. The
programmer specifies that applications contain threads of execution$ each thread
designating a portion of a program that may execute concurrently %ith other threads. This
capability is called multithreading.
$&le )
Java provides a lo% priority garbage collector thread$ %hich automatically reclaims
dynamically allocated memory that is no longer needed.
-hread %lass
%onstructors
public 65read() F constructs a thread %hose name is ^Thread^
concatenated %ith a digit li'e Thread,$
Thread;.
public 65read = constructs a thread %hose name is Thread3ame.
(String 65read3ame)F
public 65read = ) re(erence to an object o( implements
t5e
(Bunnable runnable6bject+ the class that implements the Bunnable interface.
public 65read(,unnable runnable0bject*String t5read3ame)
F Constructs thread %ith name thread3ame.
nter"aces
Bunnable #nterface F This is implemented %hen multithreading is
re<uired in a class derived from some other
class.
Creating Threads:
To implement multithreading three things are re<uired are to be identifiedF
The Code to be executed
The 1ata for that code to operate upon
/nd the .irtual C0 to run the code.
%P(F #n Java a virtual C0 is encapsulated in an instance of class Thread. C0
allotment (thread scheduling+ mechanism is automatic through this class.
%ode F Javas object oriented model re<uires that program code can only be %ritten as
member methods of class. 9ence the code re<uired by threads is %ritten in the methods of
the classes.
141
DataF Similarly the data can exist only as automatic(or local+ variables inside methods$
class members or objects.
9ence these rules re<uire that a thread must be in the form of a class instance.
Thread Methods F The method
start() F / threads execution is launched by calling this method.
run() F The code that has to be executed for a thread is placed in its run
method.
sleep() F This is a static method. This method is called %ith an argument
specifying ho% long the currently executing thread should sleep in
units of milliseconds. This allo%s other threads to execute.
suspend() F suspends temporarily thread execution.
resume() F resumes the execution of a suspended thread.
stop() F stops a thread by thro%ing a Thread death object.
-hread States
born
start
ready
<uantum dispatch
expiration (assign a
processor
notify or #!6 completion
notify/ll running
%ait sleep spend issue #!6 re<uest
%aiting sleeping suspended bloc'ed
sleep interval resume
stop complete
dead
/t any time$ a thread is said to be in one of above several states.
$&le )Three threads run %ith different data i.e. same program code used for different
142
objects.
SourceGile F rintTest.java
public class #rint6est{
public static void main(String args[]) {
#rint65read pt5r1* pt5r>* pt5r?&
pt5r1=new #rint65read(T1T)&
pt5r>=new #rint65read(T>T)&
pt5r?=new #rint65read(T?T)&
pt5r1start()&
pt5r>start()&
pt5r?start()&
'
'
class #rint65read e:tends 65read{
int sleep6ime&
public #rint65read(String id){
super(id)&
sleep6ime = (int)(Gat5random()2D888)&
Systemoutprintln(T3ame= TFget3ame()FT&sleep= TFsleep6ime)&
'
public void run(){
Systemoutprintln(T.e(ore Sleep = TFget3ame())&
try { sleep(sleep6ime)& '
catc5(/nterrupted+:ception e:c)
{ Systemerrprintln(T+:ception =TFe:ctoString())& '
Systemoutprintln(T)(ter Sleep = TFsuperget3ame())&
'
'
6utput F
3ameF ,&sleepF *@-;
3ameF ;&sleepF >,*>
3ameF *&sleepF ,C*E
=efore Sleep F ,
=efore Sleep F ;
=efore Sleep F *
/fter Sleep F *
/fter Sleep F ,
/fter Sleep F ;
C(6e a"6 6ata *(' T,'ea6
143
The Thread execution starts in method run() defined in the class (similar to main for
normal programs+. The data to be operated on by the thread are the data members of the
object passed to the thread.
To suit the re<uirement of the programmer any class can be used to provide a starting
point$ and the class can be a subclass of any single class (no multiple inheritance+. The
particular re<uirement is that the class must be declared to implement the interface
Bunnable i.e.$ it must have a non abstract method called public void run(). This is %hy
the class that provides the code for Thread is called Bunnable.
-hread F Hvery Thread in J/./ has a name.
#n the previous example the constructor of Thread %ithout name parameter %as used in
%hich case J/./ gives a uni<ue name. #t is possible to find out the name of the thread
%ith t5read1get3ame() on the Thread object t5read1
-hread priorities FHvery Java thread has a priority in the range 65readG/3W#,/0,/6[
(a constant of ,+ and 65readG)]W#,/0,/6[(a constant of ,E+. The default priority for a
thread is 65read30,GW#,/0,/6[(a constant of A+.
#n the case of 8indo%s -A and 8indo%s 3T$ each thread is given a limited amount of
time called time <uantum to execute on the processor. 8hen the ptime for the thread
expires the thread is made to %ait %hile all other threads of e<ual priority are given
chance in round robbin fashion. The original thread resumes execution. This process
continues till all the threads at that priority level complete execution. Then the thread %ith
lo%er priority starts executing.
/ssume a$b$c are e<ual priority threads $ and d a lo% priority thread.
Girst threads a$b and c execute in round robin fashion till completion$ then thread d %ill be
executed.
HxampleF *unnable class and -hread
SourceGile F MyBunnable.java
public class Gy,unnable implements ,unnable{
private String message&
public Gy,unnable(String to#rintloop){
message = to#rintloop&
'
public void run(){
(or (&&){
Systemoutprintln(message)&
144
'
'
'
3ow (or main met5od to e:ecute
Source-ile = 65readSamplejava
public class 65readSample{
public static void main(String args[]){
i( (argslengt5 J 8) {
Gy,unnable t5readobj =new Gy,unnable(args[8])&
65read t5read1 = new 65read(t5readobj)&
t5read1start()&
'
'
'
6utput F 8hen 5HC#:7 is the command line argument given
HC#:
HC#:
HC#:
HC#:
HC#:
HC#:
HC#:
HC#:
HC#:
HC#:
HC#:
HC#:
HC#:
HC#:
HC#:
HC#:
HC#:
HC#:
HC#:
Obser#ations on the pre#ious sample code)
The threadobj is a runnable instance. /nd it has its o%n data that is message (String+. So
the run method operates on the message member variable of the instance %hich is passed
to it.
Multiple threads to operate on the same objects data can be created by giving code li'e
145
65read t5read> = new 65read(t5readobj)&
65read t5read? = new 65read(t5readobj)&
data 5"rom same object6 and code are shared here
Multiple threads$ each to operate on different data can be created li'e thisF
Gy,unnable t5readobj> = new Gy,unnable(!rames5%)&
Gy,unnable t5readobj? = new Gy,unnable(!sures5%)&
65read t5read> = new 65read(t5readobj>)&
t5read>start()&
65read t5read? = new 65read(t5readobj?)&
t5read?start()&
The start() method ma'es the thread begin execution. =efore thread is not yet running.
The same run() method(code+ is shared here
$&le ) /nimation using multithreadingF
SourceGile F /nimateHxample.java
import javaapplet2&
import javaawt2&
public class )nimate+:ample e:tends )pplet implements ,unnable {
65read t5e65read&
String t5eString = T.0/3\$$$T&
int :=>8*y=>8*d:=1*dy=1&
(inal static int S6+# = D&
(inal static int G/3 =8&
int ma:]=8*ma:[=8&
int string6op*string.ottom*stringPidt5&
public void start(){
t5e65read = new 65read(t5is)&
t5e65readstart()&
'
public void stop()
{i( (t5e65read $= null)
t5e65readstop()&
t5e65read = null&
'
public void run()
{
w5ile (true)
{
:F=d:2S6+#&
i( (:KG/3 MM :FstringPidt5 Jma:]) d:2=-1&
i( (:KG/3) :=G/3&
i( (:FstringPidt5Jma:])
146
:=ma:] - stringPidt5&
yF=dy 2 S6+#&
i( (y-string6op K G/3 MM y F string.ottom J= ma:[)
dy2=-1&
i( (y-string6op KG/3) y=G/3 F string6op&
i( (yFstring.ottom Jma:[) y= ma:[ - string.ottom&
repaint()&
try{65readsleep(?8)&'
catc5(/nterrupted+:ception interrupted){'
'
'
public void paint(\rap5ics g)
{ma:]= getSiSe()widt5&
ma:[ = getSiSe()5eig5t&
gdrawString(t5eString*:*y)&
'
public void init()
{ set-ont(new -ont(T6imes,omanT*-ont.0;HF-ont/6);/4*>E))&
set.ackground(4oloryellow)&
set-oreground(4olorred)&
\rap5ics g= get\rap5ics()&
-ontGetrics (m = get-ontGetrics(gget-ont())&
stringPidt5 = (mstringPidt5(t5eString)&
string6op = (mget)scent()&
string.ottom = (mgetHescent()&
'
'
More thread Methods )
wait() 8hen a running thread calls %ait$ the thread enters a %aiting state %here it
%aits in a <ueue associated %ith the particular object on %hich %ait(+ %as
called.
noti(y() the first thread in the %ait <ueue for a particular object becomes ready on a
call to notify(+ method $ issued by another thread associated %ith that
object.
noti(yall() Hvery thread in the %ait <ueue for a given object becomes ready.
yield() a call to this method gives other threads a chance to execute. yield() is
appropriate for non2timesliced system.
/ threads priority can be adjusted %ith the set#riority() method %hich ta'es an int
argument. Similarly get#riority() method returns the threads priority.
-hread Synchroni&ation
14$
Thread synchroni?ation is synchroni?ing access to shared resources. Java uses monitors to
perform synchroni?ation. Hvery object %ith synchroni?ed method is a monitor. The
monitor allo%s only one thread at a time to execute a synchroni?ed method. This is
accomplished by loc'ing the object %hen the synchroni?ed method is invo'ed and all other
threads attempting to invo'e synchroni?ed methods must %ait. 8hen a thread executing
synchroni?ed method completes the object can notify a %aiting thread to become ready so
that it can attempt to obtain the loc' on the monitor object again and execute.
$&le F Thread code is different. Same data is shared bet%een multiple threads.
SourceGileFSharedCell.
public class S5ared4ell
{
public static void main (String args[])
{
Oold/nteger 5 = new Oold/nteger()&
#roduce/nteger p = new #roduce/nteger(5)&
4onsume/nteger c = new 4onsume/nteger(5)&
pstart()&
cstart()&
'
'
class #roduce/nteger e:tends 65read
{
private Oold/nteger pOold&
public #roduce/nteger(Oold/nteger 5)
{ pOold = 5& '
public void run(){
(or (int count = 8& count K 18&countFF){
pOoldsetS5ared/nt(count)&
Systemoutprint(T#roducer T)&
try {
sleep(?88)&
'
catc5(/nterrupted+:ception e:c){
Systemerrprintln(T+:ception =TFe:ctoString())&
'
'
t5isstop()&
'
'
class 4onsume/nteger e:tends 65read {
private Oold/nteger cOold&
14%
public 4onsume/nteger(Oold/nteger 5)
{ cOold = 5& '
public void run(){
int val = cOoldgetS5ared/nt()&
w5ile(val$=9){
try {
sleep(?88)&
'
catc5(/nterrupted+:ception e:c){
Systemerrprintln(T+:ception =TFe:ctoString())&
'
val=cOoldgetS5ared/nt()&
Systemoutprint(T4onsumer T )&
'
t5isstop()&
'
'
class Oold/nteger
{
private int s5ared/nt&
private boolean writeable = true&
public sync5roniSed void setS5ared/nt(int val)
{
w5ile($writeable){
try{
wait()&
'
catc5(/nterrupted+:ception e:c){
Systemerrprintln(T+:ception =TFe:ctoString())&
'
'
Systemoutprintln(TsetS5ared/nt() = setting value to TFval)&
s5ared/nt = val&
writeable = (alse&
noti(y()&
'
public sync5roniSed int getS5ared/nt() {
w5ile(writeable){
try{
wait()&
'
catc5(/nterrupted+:ception e:c){
Systemerrprintln(T+:ception =TFe:ctoString())&
'
'
Systemoutprintln(TgetS5ared/nt()=getting value o( TFs5ared/nt)&
writeable = true&
noti(y()&
return s5ared/nt&
'
'
14+
OutPut)
setS5ared/nt() = setting value to 8
#roducer getS5ared/nt() = getting value o( 8
setS5ared/nt() = setting value to 1
#roducer getS5ared/nt() = getting value o( 1
4onsumer setS5ared/nt() = setting value to >
#roducer getS5ared/nt() = getting value o( >
4onsumer setS5ared/nt() = setting value to ?
#roducer getS5ared/nt() = getting value o( ?
4onsumer setS5ared/nt() = setting value to E
#roducer getS5ared/nt() = getting value o( E
4onsumer setS5ared/nt() = setting value to D
#roducer getS5ared/nt() = getting value o( D
4onsumer setS5ared/nt() = setting value to R
#roducer getS5ared/nt() = getting value o( R
4onsumer setS5ared/nt() = setting value to @
#roducer getS5ared/nt() = getting value o( @
4onsumer setS5ared/nt() = setting value to Q
#roducer getS5ared/nt() = getting value o( Q
4onsumer setS5ared/nt() = setting value to 9
#roducer getS5ared/nt() = getting value o( 9
4onsumer
"ae#on threads :
/ daemon thread is a thread that runs in the bac'ground for the benefit of other threads.
The garbage collector is a daemon thread. / thread is designated as a daemon thread$
using the method call setHaemon(true). /n argument of false means that the thread is
not a daemon thread. 8hen only daemon threads remain in a program$ Java exits.
151
NET=OR?ING
I"t'(65.t!("
3et%or'ing is interconnection of independent systems to share resources. Java net%or'
programming is based on TC!#(Transmission Control rotocol!#nternet rotocol+. #t
uses the internal services provided by TC!# and does the data transfer as per the
program.
Java offers soc'et2based communication. This type of communication enables applications
to vie% transfer of the data as$ as though it is bet%een files. / program can read from or
%rite to a soc'et as simply as reading from or %riting to a file. Java provides t%o type of
soc'ets F stream soc'ets and datagram soc'ets.
8ith stream soc'et a process establishes a connection to other processes. 8hile the
connection is valid$ data flo%s bet%een the processes in one continuous stream. This is
called as a connection2oriented service. This uses TC!# protocol.
8ith datagram soc'ets$ data is transmitted as pac'ets of data. The protocol used %ith
datagram soc'ets is a 0ser 1atagram rotocol(01+. #n this type of communication data
pac'ets %ith address are put on the net%or'. 8hen a host comes across the data pac'et$ it
sees if it belongs to it. #f so$ then it accepts the data and responds as re<uired else the
pac'et is sent again to a host %hich is nearer to the destination host %ritten in the data
pac'et. This is a connectionless service and does not guarantee %hether pac'ets are
delivered properly or not .
/part from the soc'et services Java also uses other protocols provided by #nternet service.
They are used through 0B:s. / 0B: is an address of a document on the #nternet.
3et%or'ing services are mostly of client2server type. / client re<uests that some action
be performed and the server performs the action returning the result to the client. / server
al%ays %aits for the re<uests from the clients. 8hen a client first attempts to establish a
connection to the server$ the server can accept or deny the connection. #f the connection
is accepted then the client and server communicate through soc'ets as if they %ere doing
file #!6. 8hen the purpose of connection is served either the client or server may close
the connection. #f anyone closes the connection the connection is closed on both sides.
Javas net%or'ing capabilities are centralised in the java.net pac'age.
151
St'ea-S(.<et C(--5"!.at!("
(Connection 6riented Communication+
Java provides in its net pac'age classes for Soc'ets$ ServerSoc'et %ith appropriate
methods for communication. The server program creates a ServerSoc'et$ registers an
available port number from %hich the transfer is to be done. The server needs to be
registered %ith a statement.
ServerSocket s = new ServerSocket( port* Lueue;engt5)&
The <ueue:ength specifies the number of clients that can %ait for a connection and
processed by the server. #f the <ueue is full client connection is refused. 6nce the
ServerSoc'et is established$ the server %aits for an attempt by a client to connect. 8hen a
client attempts to connect to the server on this port$ the server accepts the re<uest and
establishes the connection %ith a Soc'et. This is done by ServerSoc'et method accept(+
as belo%F
Socket connection = saccept()&
and returns a Soc'et object %hen a connection is established. 6nce the connection is
established %ith a Soc'et$ 6utputStream is created to send data and an #nputStream is
created to receive data. To create an 6utputStream the server calls the method
get0utputStream() on the Soc'et and to create an #nputStream the server calls the
method get/nputStream() on the Soc'et . #n order to have #!6 in terms of characters$ or
filtered #nput!6utput as buffered stream$ or data stream$ the #nputStream or
6utputStream can be chained to the re<uired stream and the #nput!6utput can be done.
That may done as belo%.
.u((ered,eader / = new .u((ered,eader(
new /nputStream,eader(
sget/nputStream()))&
.u((eredPriter o = new .u((eredPriter(
new 0utputStreamPriter(
sget0utputStream()))&
0sing the #nput!6utput streams created as above data for the client can be sent by %riting
it to the =uffered8riter 5o7 and data to the server can be received by reading from the
=ufferedBeader 5#7.
$&le) 4lient reLuesting and getting date and time data (rom server
65e program sends a reLuest (or data on t5e port 1? to t5e 5ost 6o
connect to t5e server program t5e client program must know t5e servers
/# address or Homain name address and give it at t5e command line
152
Source-ile = Hay4lientjava
import javanet2&
import javaio2&
import javautil2&
public class Hay4lient{
String 5ost& 115ost name
Socket soc& 11socket (or data trans(er
public static void main(String args[]) t5rows /0+:ception{
Hay4lient dc= new Hay4lient(args[8])& 114reate a client
dcgetHate()& 11call (or date service
'
public Hay4lient(String p5ost) t5rows /0+:ception{
11constructor to create a client
t5is5ost = p5ost&
'
public void getHate() t5rows /0+:ception{
11met5od to get date (rom server
soc = new Socket(5ost* 1?)& 11create a socket
.u((ered,eader br = new .u((ered,eader(
new /nputStream,eader(
socget/nputStream()))&
Systemoutprintln(brread;ine())&
11,ead a line o( data (rom above reader and print
brclose()&
socclose()& 11close t5e connection
'
'
$&le) 65e Server program sends t5e date and time o( t5e day to t5e
reLuested client 65e server will wait (or a reLuest on t5e port 1? and
sends t5e date and time data to t5e client on reLuest
Source-ile = HayServerjava
import javanet2&
import javaio2&
import javautil2&
public class HayServer{
private ServerSocket ss& 11variable to 5old server socket
public static void main(String args[]) t5rows /0+:ception{
HayServer ds= new HayServer()& 11create server
(or(&&) dsserve()& 11wait (or reLuest in(initely
11and serve t5em
'
153
public HayServer() t5rows /0+:ception{
ss = new ServerSocket(1?*D)&
'
public void serve() t5rows /0+:ception{
Socket s= null& 11declare socket
s = ssaccept()& 11c5eck (or a reLuest on socket
.u((eredPriter out = new .u((eredPriter(
new 0utputStreamPriter(sget0utputStream()))&
outwrite(THay_6ime=TF(new Hate())toString()FTCnT)&
11write date to above stream
outclose()& 11close connection
sclose()&
'
'
Data3'a-S(.<et .(--5"!.at!(">UD;
(Connectionless communication+
01 is a (ser Datagram Protocol. #n this type of communication no connection bet%een
the client and the server is established. =ut similar to a post letter$ data is pac'ed %ith the
source and destination addresses and put in the net%or'. The nodes in the net%or'$
transfer the data to the re<uired client. #f the node is the client itself the data is ta'en. The
client is not guaranteed %ith the proper transfer of the data or the transfer itself and there
is no ac'no%ledgement %hich indicates the status of the data transfer i.e. success or
failure.
The client and server programs have to agree upon methods to ma'e an evaluation of the
data transferred. #f the data is lost or not in re<uired format the data has to be just
transferred again. Since data is sent in the form of pac'ets %hich are not guaranteed to be
in the order sent$ it is the responsibility of the application to 'no% %hich pac'et belongs to
%hat data item and ensure that the data is not corrupt in the transfer.
Java provides in its net pac'age classes DatagramSoc4et and DatagramPac4et %ith
appropriate methods for a connectionless communication. =oth have to create
DatagramSoc4ets and DatagramPac4et. 1ifference is that the clients message is a
re<uest for data and servers message is the re<uired data. The server program first creates
a DatagramSoc4et. Then the server %ill prepare data in the form of DatagramPac4et.
The DatagramPac4et contains the destination address and the port number on %hich the
client can receive data and send data. The DatagramPac4ets are sent on the net%or' by
154
the server using the method send() of the DatagramSoc4et. The client re<uesting the
data also creates a DatagramSoc4et upon the port no$ %here the server is sending data
and %aits for the DatagramPac4ets to arrive. 8hen a DatagramPac4et arrives at the
clients port the client receives the data %ith all other information. #f the port is reserved
for a particular service then it might be understood. Hlse it is the responsibility of the client
to understand %hat data it is. The server starts operation %ith the creation of the
DatagramSoc4et %ith a statement.
HatagramSocket ds = new HatagramSocket()&
Then the server determines the address of the client it has to send data. /nd prepares the
DatagramPac4ets as belo%.
.yte [] bu(&
String data=new String(!Pelcome to server%)&
bu( = dataget.ytes()&
address = /net)ddressget.y3ame(name)&
portno = 1??8&
Hatagram#acket dp= new Hatagram#acket(bu(*bu(lengt5()*address*
portno)&
The data pac'et prepared is sent by the method send() of the DatagramSoc4et as
dssend(dp)&
dp is the parameter. The client on the other side also creates a DatagramSoc4et on the
port number %here data is expected and an empty Hatagram#acket to hold the incoming
data as belo%.
HatagramSocket dc = new HatagramSocket(portno)&
.yte [] bu( = new byte[RE]&
Hatagram#acket dp= new Hatagram#acket(bu(* bu(lengt5())&
#t %aits for the data to come in %ith the method receive()
(or(&&)
dcreceive(dp)&
/s soon as data arrives it is stored into the Hatagram#acket dp The Hatagram#acket
contains data %hich is obtained by the getHata() method of the Hatagram#acket
dpgetHata()&
155
$&le ) Server program sending date and time o( t5e day in t5e (orm
o( data packets to t5e reLuested client
Source-ile = <H#HaySeverjava
import javanet2&
import javaio2&
import javautil2&
public class <H#HayServer{
HatagramSocket ds&
Hatagram#acket dp&
/net)ddress addr&
static (inal int H)[6/G+W#0,6 = 1?1?& 11constant (or port 3o
public static void main(String args[]) t5rows +:ception{
<H#HayServer uds&
i( (argslengt5 J8 )
uds= new <H#HayServer(args[8])& 11 create server
else
uds= new <H#HayServer()&
(or(&&)
udsserve()&11wait (or data packets and i( one arrives
'
public <H#HayServer() t5rows +:ception{11constructor to create
11server
addr = /net)ddressget.y3ame(T1>@881T)& 11create address
ds = new HatagramSocket()&11create socket (or data
11trans(er
'
public <H#HayServer(String target) t5rows +:ception{
11constructor to create server
addr = /net)ddressget.y3ame(target)&
11create address
ds = new HatagramSocket()& 11create socket (or data
11trans(er
'
public void serve() t5rows +:ception{ 11met5od to send data
byte [] bu(&
65readsleep(1888)&
String data=(new Hate())toString()&11 get system date
bu( = dataget.ytes()& 11store date as bytes in bu((er
dp=new Hatagram#acket(bu(*bu(lengt5*addr*
H)[6/G+W#0,6)&
11prepare a data packet wit5 date
156
dssend(dp)& 11send t5e data packet
'
'
$&le ) 65e client program receives t5e date and time o( t5e day 65e
program receives date as a packet o( data
Source-ile = <H#Hay4lientjava
import javanet2&
public class <H#Hay4lient{
HatagramSocket ds&
Hatagram#acket dp&
/net)ddress addr&
public static (inal int H)[6/G+W#0,6 = 1?1?&11constant (or port 3o
public static void main(String args[]) t5rows +:ception{
<H#Hay4lient udc= new <H#Hay4lient()& 11create a client
udcget#ackets()& 11take t5e data packets arriving
'
public <H#Hay4lient(String target)t5rows +:ception{11 create client
ds = new HatagramSocket(H)[6/G+W#0,6)& 11create socket (or data
'
public <H#Hay4lient() t5rows +:ception{11 create client
ds = new HatagramSocket(H)[6/G+W#0,6)&11 socket (or data
11trans(er
'
public void get#ackets() t5rows +:ception{11 to receive data
String s&
byte []bu( = new byte[RE]&
dp = new Hatagram#acket(bu(* bu(lengt5)& 11create empty
11data
packet
dsreceive(dp)&
s = new String(dpgetHata())& 11convert data to string
Systemoutprintln(THate and 6ime o( t5e day = TFs)&
'
'
URL FOR DATA TRANSFER
The java.net pac'age provides t%o classes for %or'ing %ith 0B:s. They are 0B: and
0B:Connection classes. These classes facilitate to read data referred by the 0B:$ in the
form of a stream. /n instance of the 0B: class can be created using a text string that
represents the 0B: as given belo%.
<,; aurl = new <,; (!5ttp=11wwwsuncom1%)&
15$
6nce the 0B: is created the openStream(+ method provides the mechanism for reading
the data that the 0B: describes allo%ing the input to be handled by any of the standard
#nputStream classes$ including the chaining of other types of input streams or readers$
such as the 1ata#nputStream or #nputStreamBeader classes.
15%
$&le ) The program %ill connect to the 0B: httpF!!%%%.yahoo.com! and get t5e
data (rom it 65is will work i( t5e internet connection is available
,eplace wit5 your local web server available
Source -ile = <,;4onnection,eaderjava
import javanet2&
import javaio2&
public class <,;4onnection,eader {
public static void main(String[] args) t5rows +:ception {
<,; ya5oo = new <,;(T5ttp=11wwwya5oocom1T)&
<,;4onnection ya5oo4onnection = ya5ooopen4onnection()&
.u((ered,eader in = new .u((ered,eader(
new /nputStream,eader(
ya5oo4onnectionget/nputStream()))&
String input;ine&
w5ile ((input;ine = inread;ine()) $= null)
Systemoutprintln(input;ine)&
inclose()&
'
'
Ut!/!t!e
Java provides different utility classes for various purposes. /ll these classes are available in
the javautil pac'age.
Ziven belo% are some important utility classes.
Date, Hashtable, Properties, Random, Stack, StringTokenizer, Vector
Date) Hate class represent date and time 65ere are several
constructors (or Hate objects
%onstructors )
Hate() = produces the current date and time.
Hate(int year* int mont5* ind dayo(mont5)
Hate(int year* int mont5* ind dayo(mont5*int 5ours* int mins)
Hate(int year* int mont5* ind dayo(mont5*int 5ours* int mins*int secs)
Hate(long milliseconds) = no o( milliseconds (rom "anuary 1* 19@8
midnig5t
Hate(String strdate) = 4onverts t5e string representation o( date
into a Hate object
15+
Methods
boolean a(ter(Hate pdate) - returns true if the current date is after pdate.
boolean be(ore(Hate pdate) - returns true if the current date is before pdate.
boolena eLauls(Hate pdate) - returns true if the current date same as pdate.
int getHay()
int getGont5()
int get[ear()
void setHay(int dayno)
void setGont5(int mont5no)
void set[ear(int year)
$&le ) <sage o( Hate class Source-ile = datetestjava
import javaio2&
import javautil2&
public class datetest{
public static void main(String args[])
{
Hate today = new Hate()&
Systemoutprintln(T6odayCXs date is TFtodaytoString())&
Systemoutprintln(T4urrent time is TFtodayget6ime())&
Hate aday = new Hate(199Q*18*9)&
Hate bday = new Hate(199Q*11*18)&
Hate cday = new Hate(199Q*9*>?)&
Hate tday = new Hate(199Q*9*>?*1>*>8)&
Systemoutprintln(T) day is TFadaytoString())&
Systemoutprintln(T. day is TFbdaytoString())&
Systemoutprintln(T4 day is TFcdaytoString())&
Systemoutprintln(T6 day wit5 time is TFtdaytoString())&
i( (adaybe(ore(bday))
Systemoutprintln(T a is be(ore bT)&
i( (cdaya(ter(bday))
Systemoutprintln(T c is a(ter bT)&
Systemoutprintln(T6ime o( aday is TFadayget6ime())&
Systemoutprintln(T6ime o( tday is TFtdayget6ime())&
Hate today1 = new Hate()&
i( (today1eLuals(today))
Systemoutprintln(T today is same as today1T)&
'
6utput F
6odayXs date is 65u Sep 1@ 1>=1@=1Q \G6F8D=?8 199Q
4urrent time is 98R81EQ?Q>88
) day is Ped 3ov 89 88=88=88 \G6F8D=?8 ?Q9Q
. day is Sat Hec 18 88=88=88 \G6F8D=?8 ?Q9Q
4 day is Sun 0ct >? 88=88=88 \G6F8D=?8 ?Q9Q
161
6 day wit5 time is Sun 0ct >? 1>=>8=88 \G6F8D=?8 ?Q9Q
a is be(ore b
6ime o( aday is R8QRQ@Q8>88888
6ime o( tday is R8QR@?DDQ88888
Ha,ta8/e =
/ 9ashtable instance can be used to store arbitrary objects %hich are indexed by another
arbitrary object. The 9ashtable uses hashing techni<ue to ma'e an index from the 'ey
object given. The elements are added to hash table %ith its 'ey object and the object itself.
%onstructors)
9ashtable (+
9ashtable (int si?e+
Methods =
boolean contains(0bject value)
returns if the object is present in the 9ashtable
0bject get(0bject key)
returns the object identified by the 'ey object
0bject put(0bject key* 0bject value)
adds an object value %ith its 'ey object 'ey
0bject remove(0bject key)
removes the object identified by the 'ey object
Hxample F Creation of 9ashtable %ith String objects. SourceGile F hashtabletest.java
import javautil2&
public class 5as5tabletest{
public static void main(String args[])
{
Oas5table vg =new Oas5table()&
String /tems[]={T0nionT*T#otatoT*T6omatoT*T.rinjalT*T.eansT'&
/nteger #rices[]={new /nteger(1>)*
new /nteger(?E)*
new /nteger(D?)*
new /nteger(>?)*
new /nteger(>Q)'&
i( (vgis+mpty())
Systemoutprintln(TOas5table is empty$ )dd elementsT)&
else
Systemoutprintln(T4urrent siSe o( Oas5table TFvgsiSe())&
(or(int i=8& iKD&iFF)
vgput(/tems[i]*#rices[i])&
161
i( (vgis+mpty())
Systemoutprintln(TOas5table is emptyT)&
else
Systemoutprintln(T4urrent siSe o( Oas5table TFvgsiSe())&
(or (int j=8&jKD&jFF)
Systemoutprintln((/nteger)vgget(/tems[j]))&
vgremove(T0nionT)&
vgremove(T#otatoT)&
Systemoutprintln(T4urrent siSe o( Oas5table TFvgsiSe())&
(or ( int j=8&jKD&jFF)
Systemoutprintln((/nteger)vgget(/tems[j]))&
i( (vgcontains(new String(T0nionT)))
Systemoutprintln(T#rice o( 0nion is TF(/nteger)
vgget(T0nionT))&
else
Systemoutprintln(T0nion is not presentT)&
'
'
Output )
Oas5table is empty$ )dd elements
4urrent siSe o( Oas5table D
1>
?E
D?
>?
>Q
4urrent siSe o( Oas5table ?
null
null
D?
>?
>Q
0nion is not present
Properties = /t is used to maintain lists o( values as in a Oas5table*
t5e key is a String and t5e value is also a String /t is a
subclass o( Oas5table
%onstructors) #roperties()
Methods )
String get#roperty(String key) = returns the string identified by 'ey string
void load (/nputSream is) = inputs a property list from an #nputStream is
void save(0utputStream os* = the properties list is saved to the
162
String desc) 6utputStream os %ith the description given as
desc
$&le = 65e program creates a property list and tries to retrieve
objects using key Source-ile = propertiestestjava
import javautil2&
public class propertiestest{
public static void main(String args[])
{
#roperties vg =new #roperties()&
String 3ames[]={T-ontT*T-ile#at5T*T4ode.aseT*T4ountryT*TUersionT'&
String
Ualues[]={T4ourierT*T1windows1systemT*T1)ppletsT*T/ndiaT*TE8T'&
i( (vgis+mpty())
Systemoutprintln(T#roperties is empty$ )dd elementsT)&
else
Systemoutprintln(T4urrent siSe o( #roperties TFvgsiSe())&
(or(int i=8& iKD&iFF)
vgput(3ames[i]*Ualues[i])&
i( (vgis+mpty())
Systemoutprintln(T#roperties is emptyT)&
else
Systemoutprintln(T4urrent siSe o( #roperties TFvgsiSe())&
(or (int j=8&jKD&jFF)
Systemoutprintln((String)vgget#roperty(3ames[j]))&
vgremove(T0nionT)&
vgremove(T#otatoT)&
Systemoutprintln(T4urrent siSe o( #roperties TFvgsiSe())&
(or ( int j=8&jKD&jFF)
Systemoutprintln((String)vgget#roperty(3ames[j]))&
i( (vgcontains(new String(T0nionT)))
Systemoutprintln(T#rice o( 0nion is !F (String) vgget#roperty
(T0nionT))&
else
Systemoutprintln(T0nion is not presentT)&
'
'
Output
163
#roperties is empty$ )dd elements
4urrent siSe o( #roperties D
4ourier
1windows1system
1)pplets
/ndia
E8
4urrent siSe o( #roperties D
4ourier
1windows1system
1)pplets
/ndia
E8
0nion is not present
*andom ) 65e ,andom class is a generator o( pseudorandom numbers
%onstructor =
,andom()
Methods)
double ne:tHouble()* (loat ne:t-loat()* int ne:t/nt()* long ne:t;ong()
65ese met5ods generate random numbers o( t5e corresponding type
$&le ) 65e program produces a random integer value * double value *
a (loat value
and a long value
Source-ile = randomtestjava
import java.util.R&
public class randomtest{
public static void main(String []args){
,andom rand = new ,andom()&
double dval &
int ival&
(loat (val&
long lval&
dval = randne:tHouble()&
ival = randne:t/nt()&
(val = randne:t-loat()&
lval = randne:t;ong()&
Systemoutprintln(THouble = TFdval)&
Systemoutprintln(T/ntegee= TFival)&
Systemoutprintln(T-loat = TF(val)&
Systemoutprintln(T;ong = TFlval)&
'
'
164
Output
Houble = 8@E1Q@Q9>D898>@DD
/ntegee= -1RE>>EQ8RQ
-loat = 888>9QQQ1D?
;ong = R181RQ18?8EE1>188QD
165
Stac4 ) ) Stack contains a list o( values wit5 operations like pus5*
pop* 65e pus5 operation adds elements to t5e list w5ile t5e pop
removes an element (rom t5e list )dding or removing o( elements in t5e
list can be done at one end only 0nly t5e top element in t5e list can
be removed /( ?rd element (rom top is to be removed t5en (irst two
must be removed* similar to adding rings onto a pole
Stac4 is a subclass o( Uector /t 5as a constructor Stack()
Methods = boolean empty()* 0bject pop()* 0bject pus5(0bject element)
$&le = Source-ile = stacktestjava
import javaio2&
import javautil2&
public class stacktest{
public static void main(String args[]){
String s[] = new String[18]&
Stack strStack = new Stack()&
s[8]=TabcT& s[1]=Tde(T&
s[>]=Tg5iT& s[?]=TjklT&
s[E]=TmnoT& s[D]=TpLrT&
s[R]=TstuT&
strStackpus5(s[8])&
Systemoutprintln(s[8]FT pus5edT)&
strStackpus5(s[1])&
Systemoutprintln(s[1]FT pus5edT)&
strStackpus5(s[>])&
Systemoutprintln(s[>]FT pus5edT)&
strStackpus5(s[?])&
Systemoutprintln(s[?]FT pus5edT)&
String st = (String)strStackpop()&
Systemoutprintln(stFT poppedT)&
st = (String)strStackpop()&
Systemoutprintln(stFT poppedT)&
st = (String)strStackpop()&
Systemoutprintln(stFT poppedT)&
strStackpus5(s[E])&
Systemoutprintln(s[E]FT pus5edT)&
st = (String)strStackpop()&
Systemoutprintln(stFT poppedT)&
'
'
166
Output =
abc pus5ed
de( pus5ed
g5i pus5ed
jkl pus5ed
jkl popped
g5i popped
de( popped
mno pus5ed
mno popped
String-o4eniAer = 65e met5ods o( t5e String6okeniSer object are used to
parse a given
string into di((erent tokens
%onstructors )
String6okeniSer(String str)
Methods = int count6okens()* boolean 5asGore6okens()* String ne:t6oken()
SourceGile F stringto'enstest.java
$&le)
import javautil2&
public class stringtokenstest{
public static void main(String []args)
{
String tokens = new String(Tt5e line is a set o( wordsT)&
String6okeniSer st = new String6okeniSer(tokens)&
Systemoutprintln(TCTTFtokensFTCTTFT is broken into T)&
w5ile (st5asGore+lements())
Systemoutprintln(stne:t6oken())&
'
'
Output )
Tt5e line is a set o( wordsT is broken into
t5e
line
is
a
set
o(
words
16$
Vector )
/ vector operates li'e an incrementable array. /n array can have only one type of objects
%hile a .ector object can have 6bjects %hich belong to different classes.
%onstructors )
Uector()
Uector(int siSe) = 4reate vector wit5 a intial capacity
Uector(int siSe* int ince) = Create vector %ith a intial capacity and increment
si?e if the current vector is full
Methods )
(inal void add+lement(0bject element)
adds an element to the vector
(inal int capacity()
returns the current capacity of the vector$.
(inal boolean contains(0bject element)
return true if the vector has the element object
(inal element)t(int inde:)
returns the object at an index
(inal void insert+lement)t(0bejct element* int inde:)
#nserts an object at index
(inal void remove+lement(0bject element)
removes the element object form vector
(inal void remove+lement)t(int inde:)
removes the element at an index given
$&le ) Source-ile = vectortestjava
import javautil2&
public class vectortest{
public static void main(String args[])
{
Uector vc =new Uector(D*D)&
String /tems[]={T0nionT*T#otatoT*T6omatoT*T.rinjalT*T.eansT'&
i( (vcis+mpty())
Systemoutprintln(TUector is empty$ )dd elementsT)&
else
Systemoutprintln(T4urrent siSe o( vector TFvcsiSe())&
(or(int i=8& iKD&iFF)
vcadd+lement(/tems[i])&
16%
i( (vcis+mpty())
Systemoutprintln(TUector is emptyT)&
else
Systemoutprintln(T4urrent siSe o( vector TFvcsiSe())&
(or (int j=E&jJ=8&j--)
Systemoutprintln((String)vcelement)t(j))&
vcremove+lement(T0nionT)&
vcremove+lement(T#otatoT)&
vctrim6oSiSe()&
Systemoutprintln(T4urrent siSe o( vector TFvcsiSe())&
(or ( int j=>&jJ=8&j--)
Systemoutprintln((String)vcelement)t(j))&
vcinsert+lement)t(new String(T#epperT)*>)&
Systemoutprintln(T4urrent siSe o( vector TFvcsiSe())&
(or ( int j=vcsiSe()-1&jJ=8&j--)
Systemoutprintln((String)vcelement)t(j))&
Systemoutprintln(T+lement at 1 is TFvcelement)t(1))&
vcremove+lement)t(1)&
Systemoutprintln(T4urrent siSe o( vector TFvcsiSe())&
(or ( int j=vcsiSe()-1&jJ=8&j--)
Systemoutprintln((String)vcelement)t(j))&
'
'
Output )
Uector is empty$ )dd elements
4urrent siSe o( vector D
.eans
.rinjal
6omato
#otato
0nion
4urrent siSe o( vector ?
.eans
.rinjal
6omato
4urrent siSe o( vector E
.eans
#epper
.rinjal
6omato
+lement at 1 is .rinjal
4urrent siSe o( vector ?
.eans
#epper
6omato
16+
JAVA DATA0ASE CONNECTIVITY
I"t'(65.t!("#
DatabaseF
/ database is a tool used to collect and manipulate data. #t is %ell suited to the storage
and retrieval of data.
.rontend ApplicationF
8hile the database system is %ell suited to the storage of data$ some sort of frontend
application is needed inorder to see and access the data stored.
Probelms 7ith de#eloping "rontend applicationsF
R The computers in most companies are of heterogeneous nature.
Gor exampleF /rt and mar'eting departments 2 use Macintosh systems
Hngineers 2 use highend 0nix%or's stations
Sales people 2 use Cs
R So$ to expose the data stored in the database$ the developers of frontend applications
must consider all of the various permutations of systems on %hich$ they %ish to
deploy the frontend application.
Database clientBser#er methodology
R Belational data storage began in ,-CE %ith the %or' of 1r. H.G. Codd$ %ho proposed a
set of ,; rules for identifying relationships bet%een pieces of data.
R 1ata in a relational database Management System are stored as ro%s of distinct
information in tables.
R The Structured \uery :anguage(S\:+ is an /3S# Standard$ %hich is used to <uery
(retrieve+$ store and change the data.
R The early development of B1=MS applications utili?ed an integrated model of user
interface code$ application code and database libraries
R This single binary model ran only on a local machine$ typically a mainframe.
1$1
Disad#antages o" the integrated model
,. #n an integrated model$ the applications %ere simple but inefficient and do not
%or' over :/3S.
;. The application and user interface code %ere tightly coupled to the database
libraries.
*. Gurther$ the monolithic approach did not allo% multiple instances of the
application to communicate %ith each other leading to contention bet%een
instances of application.
-he Monolithic Single -ier Database Design
/pplication
1atabase
:ibraries
Storage
-7o-tier Database Design
R T%o2tier models appeared %ith the advent of server technology.
R Communication 2 protocol development and extensive use of local and %ide area
net%or's allo%ed the database developer to create an application frontend that
accessed data through a connection (soc'et+ to the bac'2end server.
-!$ -<O--$* DA-A3AS$ D$S9N
/pplication S\:
(client+ re<uest
1atabase
Client2Side Soc'et Server
libraries 1ata
reply
Storage
The diagram above illustrates a t%o2tier database design$ %here the client soft%are is
connected to the database through a soc'et connection.
In the two*tier data$ase design&
1$1
R Client programs (applying a user interface+ send S\: re<uests to the database
server.
R Server returns the appropriate results$ and the client formats the data.
R Clients use a vendor provided library %hose functions manage the communication
bet%een client and server.
R Most of these libraries are %ritten in C2:anguage.
Limitations o" the t7o-tier model
1espite the success of client!server technology$ t%o2tier database models suffer from a
number of limitations.
R They are limited by the vendor provided library.
R S%itching from one database vendor to other re<uires a re%rite of significant
amount of code to the client application.
R .ersion control is an issue.
R 8hen the vendor updates client side libraries the applications that utili?e the
database must be recompiled and redistributed.
R =ase library only deals %ith fetches and updates on single ro%s or columns of
data. This can be enhanced on the server2side by creating a stored procedure2
%hich is a macro program that lives on the database. =ut the complexity of the
system increases.
R The intelligence associated %ith using and manipulating the data is implemented
in the client application.
R The above fact creates large client2side runtimes. This drives the cost of each
client seatup.
-hree--ier Database Design
R Today$ a great deal of interest is in multitier design$ in %hich there does not have
to be just * tiers$ but conceptually this is the next step.
R #n a multitier design$ the client communicates$ %ith an intermediate server that
provides a layer of abstraction from the B1=MS.
OD3% 5Open Database %onnecti#ity6
1$2
Microsofts 61=C (6pen 1atabase Connectivity+ /# is %idely used as the middle%are
in a three tier database design %hich acts as an interface for accessing relational databases.
#t is a C interface %hich offers the ability to connect to almost all databases on almost on
all platforms.
A -!*$$--$* DA-A3AS$ D$S9N
/pplication S\: re<uest Middle%are
(client+ =usiness rules
(61=C+ 1atabase
Client2Side 1ata reply Client2side Server
libraries Change libraries
notification
:ocal storage
replication
R The intermediate layer can handle multiple client re<uests and manage the
connection to one or more database servers.
The middle tierF
2 is multithreaded to manage multiple client connections simultaneously.
2 can accept connections from clients on a variety of vendor2neutral protocols
(from 9TT to TC!#+$ then marshal the re<uests to the appropriate vendor2
specific database servers$ and return the replies to the appropriate clients.
1$3
2 can be programmed %ith a set of 5business rules7 that manage the manipulation
of the data. =usiness rules could restrict access to certain portions of
data or ensure that data is formatted before
being inserted or updated.
2 prevents the client from becoming too heavy by centrali?ing process intensive
tas's and abstracting data representation to a higher level.
2 isolates the client application from the database system and frees a company to
s%itch database systems %ithout having to re%or' the business rules.
2 can asynchronously provide the client %ith a status of a current datatable or ro%.
HxampleF / client application had just completed a <uery of a particular table.
Then$ if a subse<uent action by another distinct client changed the data$
the first client could receive notification from an intelligent middle2tier
program.
-he Ja#a Database connecti#ity and its Ad#antages
J1=C is a Java /# for executing S\: statements.
#t consists of a set of classes and interfaces %ritten in the Java programming language
that are implemented by a driver %hich ma'es it easy to send S\: statements to
virtually any relational database.
So$ there is no need of %riting one program to access a Sybase database$ another
program to access an 6racle database$ another program to access an #nformix
database$ and so on.
/ single program %ritten using the J1=C /# can send S\: statements to the
appropriate database.
The J1=C /# supports both t%o2tier and three2tier models for database access.
1$4
JD0C ) OD0C
R J1=C is not a derivative of Microsofts open 1atabase Connectivity.
R J1=C is %ritten entirely in Java and 61=C is a C interface.
R =oth J1=C and 61=C are based on the S\: Command :evel #nterface (C:#+.
R Java soft provides a J1=C261=C bridge that translates J1=C to 61=C.
JD3% -<O--$* DA-A3AS$ D$S9N
6racle
database
/pplication
J1=C
6racle Sybase
driver driver
Sybase
database
#n the above t%o2tier model$ a Java applet or application tal's directly to the database.
There is a J1=C driver that communicates %ith a particular database management system.
The driver ta'es care of the translation of standard J1=C calls into the specific calls
re<uired by the database it supports. The application is %ritten once and moved to the
various drivers. The application remains the same. The drivers change.
JD3% -!*$$--$* DA-A3AS$ D$S9N
/pplication Middle%are .endor /
(61=C+ database
J1=C rotocol server
handler
1=MS2independent 1=MS clientside .endor =
protocol driver libraries database
server
#n the three tier2model$ commands are sent to a 5middle tier7 of services$ %hich then send
S\: statements to the database. The database processes the S\: statements and sends
the results bac' to the middle tier$ %hich then sends them to the user. 1rivers may be
used to develop the middle tier of a multitier database design$ also 'no%n as middle%are.
1$5
R J1=C extends %hat can be done in Java.
,+ Gor example$ %ith Java and the J1=C /#$ it is possible to publish a %eb
page containing an applet that uses information obtained from a
remote database.
;+ /nother example is$ an enterprise can use J1=C to connect all its
employees$ even if they are using a conglomeration of 8indo%s$
Machintosh and 03#4 machines to one or more internal
databases via an internet.
*+ Management #nformation Systems managers li'e the combination of Java
and J1=C because it ma'es disseminating information easy and
economical.
R 8ith the help of J1=C$ businesses can continue to use their installed databases
and access information easily even if it is stored on different database
management systems.
R 1evelopment time for ne% applications is short.
R #nstallation and version control are greatly simplified. / programmer can %rite
an application or an update once$ put it on the server and everybody has access to
the latest version.
R Gor businesses selling information services$ Java and J1=C offer a better %ay of
getting out information updates to external customers.
<hat does JD3% doC
Simply put$ J1=C ma'es it possible to do * thingsF
,. Hstablish a connection %ith a database
;. Send S\: statements
*. rocess the results.
T,e A;I C(-p("e"t
There are ; distinct layers %ithin the J1=C /#F
,. The /pplication :ayer$ %hich database application developers %ill use.
;. The 1river :ayer %hich driver vendors implement.
JD3% AP %OMPON$N-S 5-he %lass !ierarchy6
1river 1river Manager
1$6
layer
1river
/pplication Connection
layer
reparedStatement Statement CallableStatement
BesultSet BesultSet BesultSet
R The application developer uses the standard /# interfaces to guarantee J1=C
compliance.
R The driver developer is responsible for developing code that interfaces to the
database and supports the J1=C application level calls.
R The four interfaces are the 1river$ Connection$ Statement and BesultSet and the
class that bridges the application and driver layers is the 1river Manager class.
R The Connection$ Statement and BesultSet interfaces are implemented by the
driver vendor but these interfaces represent methods$ %hich the application
developer %ill treat as real object classes and use them to create statements and
retrieve results.
T,e D'!7e' Laye'
The 1river class is an interface implemented by the driver vendor.
The 1river Manager class %hich is above the 1river and /pplication layers is
responsible for loading and unloading drivers and ma'ing connections through
drivers.
The 1river Manager also provides features for logging and database login
timeouts.
T,e D'!7e' I"te'*a.e
o Hvery J1=C application has atleast one J1=C driver implementation.
1$$
o The 1river interface allo%s the 1riverManager and J1=C /pplication
layers to exist independently of the particular database used.
o / J1=C driver is an implementation of the 1river interface class.
o 1rivers use a string to locate and access databases. The syntax of this
string is similar to a 0B: string. The purpose of a J1=C 0B: string is to
separate the application developer from the driver developer.
o The 0B: syntax used by the 8ord8ide8eb supports a standard syntax
that satisfies these goals. J1=C 0B:s have the follo%ing syntaxF
JD0C URL y"ta& a"6 t'5.t5'e
"H.4 = KsubprotocolJ= KsubnameJ
%here OsubprotocolP defines the type of driver
and OsubnameP provides the dataSource name
Gor exampleF jdbc=odbc=in(o
9ere the database driver is an odbc driver and the subname is a local database
called info. This driver is designed to 'no% ho% to use the subname %hen ma'ing
connection to the database.
1$%
T,e D'!7e' 4a"a3e' C/a
The 1riverManager class is really a utility class used to manage J1=C drivers. The class
provides methods to obtainF
,. / connection through a driver
;. Begister and deregister drivers
*. Setup logging and set login timeouts for database access
/ll the above methods in the 1riverManager class are static and may be referenced
through the follo%ing class nameF
SignatureF public class java.s<l.1riverManager.
,. public static sync5roniSed connection get4onnection (String url*
properties in(o) t5rows SZ;+:ception
This method (and the other get4onnection() methods+ attempts to return a
reference to an object implemented from the connection interface. This method
s%eeps through a vector of stored 1river classses$ passing the 0B: string and
properties object info to each in turn. The first 1river class that returns a
connection is used.info is a reference to a properties container object of tag!value
pairs typically username!pass%ord. This method allo%s several attempts to ma'e
an authori?ed connection for each driver in the vector.
;. public static sync5roniSed connection get4onnection (String url)
t5rows SZ;+:ception
This method calls get4onnection (url* in(o) above %ith an empty properties
object (info+.
*. public static sync5roniSed connection get4onnection (String url*
String user* String password) t5rows SZ;+:ception
This method creates a properties object (info+ stores the user and pass%ord strings
into it$ and then calls get4onnection (url* in(o) above.
1rivers are registered %ith the 1riverManager class either at initiali?ation of the
1riverManager class or %hen an instance of the driver is created.
1$+
8hen the 1riverManager class is loaded$ a section of static code (in the class+ is
run$ and the class names of drivers listed in a Java property named jdbc.drivers are
loaded.
Hach driver name is a class file name (including the pac'age declaration+ that the
1riverManager %ill attempt to read through the current C:/SS /T9 . The
1riverManager uses the follo%ing call to locate$ load and lin' the named class.
4lass(or3ame(driver)&
$&le) 4lass(or 3ame(!sunjdbcodbc"dbc0dbcHriver%)
The primary use of the 1riverManager is to get a connection object reference
through the get4onnection methodF
$&le) 4onnection conn=null&
conn=HriverGanagerget4onnection (url* user* pwd)&
The method gets through the list of registered drivers and passes the 0B: string
and parameters to each driver in turn through the drivers connect(+ method. #f the
driver supports the subprotocol and subname information a connection object
reference is returned.
T,e App/!.at!(" Laye'
The application layer encompasses * interfaces that are implemented by the 1river:ayer$
but are used by the application developer.
/n interface in Java provides a means of using a general name to indicate a specific
object. The general name defines methods that must be implemented by the specific object
classes.
So$ for the application developer$ the specific 1river class implementation is irrelevant.
Just coding to the standard J1=C /#S %ill be sufficient. This is only %hen the driver is
J1=C compliant. This means that the database is atleast /3S# S\:2; Hntry level.
The * main interfaces in the /pplication layer are&
,. Connection$
;. Statement and
*. BesultSet
,. / connection object is obtained from the driver implementation through the
1riverManager.getConnection(+method call &
conn)1riverManager.getConnection(url$usr$pass%ord+
1%1
;. 6nce a Connection object is returned the application developer may create a
Statement object to issue against the database.
*. The result of a Statement is a BesultSet object$ %hich contains the results of a
particular statement(if any+.
%onnection 3asics
The connection inerface represents a session %ith the database connection provided by the
1rivers. Typical database connections include the ability to control changes made to the
actual data stored through transactions.
-ransaction
/ transaction is a set of operations that are completed in order.
%ommit
/ commit action ma'es the operations store (or change+ data in the database.
*ollbac4
/ rollbac' action undoes the previous transaction before it has been committed.
6n creation$ J1=C connections are in autocommit mode$ there is no rollbac' possible. So
after getting a connection object from the driver$ the developer should consider setting
auto commit to false %ith the set/utoCommit (boolean b+ method.
8hen auto2commit is disabled$ the connection %ill support both Connection.commit(+ and
Connection.rollbac'(+ method calls.
The level of support for transaction isolation depends on the underlying support for
transactions in the database.
Some of the methods in the connection interface definition used fre<uently areF
Signature F public interface Connection
,. Statement createStatement() t5rows SZ;+:ception
1%1
The connection object implementation %ill return an instance of an
implementation of a statement object. The Statement object is then used to issue
<ueries.
;. #reparedStatement prepareStatement(String sLl) t5rows
SZ;+:ception
The connection object implementation %ill return an instance of a
reparedStatement object that is configured %ith the S<l string passed. The driver
may then send the statement to the database$ if the database(driver+ handles
precompiled statements. 6ther%ise the drivers may %ait until the
reparedStatement is executed by an execute method. /n exception may be
thro%n if the driver and database do not implement precompiled statements.
*. 4allableStatement prepare4all(String SZ;) t5rows SZ;+:ception
The connection object implementation %ill return an instance of a
CallableStatement. CallableStatements are optimi?ed for handling stored
procedures. The driver implementation may send the s<l string immediately %hen
prepareCall(+ is complete or may %ait until an execute method occurs.
>. a+ void commit() t5rows SZ;+:cetpion 2 Ma'es all changes made since the
beginning of the current transaction(either the opening of the connection or since
the last commit(+ or rollbac'(N+ +.
b+ void rollback() t5rows SZ;+:ception 2 3ullifies all changes made since
the beginning of the current transaction.
The primary use of the connection interface is to create a statement
4onnection msLlconn=null&
Statement stmt=null&
msLlconn=HriverGanagerget4onnection(url* user* passwd)&
stmt = msLlconncreateStatement()&
This statement may be used to send S\: statements that return a single result set
in a BesultSet object reference. Statements that need to be called a number of
times %ith slight variations may be executed more efficiently using a
reparedStatement. The connection interface is also used to create a
CallableStatement %hose purpose is to execute stored procedures.
State-e"t 0ASICS
/ statement is the vehicle for sending S\: <ueries to the database and retrieve a
set of results. Statements can be S\: updates1 inserts1 delets or ?ueries (via
Select+. The statement interface provides a number of methods designed to ma'e
the job of %riting <ueries to the database easier. 8hen sending S\: statements to
1%2
the database$ %e can use the appropriate S\: types li'e ./BC9/B %hich
corresponds to a J/./ String$ T#3.#3T %hich corresponds to a J/./ byte$
1/TH %hich corresponds to a J/./ 1ate etc.
Signature F public interface Statement
,. ,esultSet e:ecuteZuery (String sLl) t5rows SZ;+:ception 2 Hxecutes a
single S\: <uery and returns the results in an object of type BesultSet.
;. int e:ecute<pdate(string sLl) t5rows SZ;+:ecption 2 Hxecutes a single
S\: <uery that does not return a set of results but a count of ro%s affected.
*. boolean e:ecute(String sLl) t5rows SZ;+:ception - / general S\:
statement that may return multiple resultsets and!or update counts. This method is
used to execute stored procedure that return out and #nout parameters. The
get,esultSet()* get<pdate4ount()* and getGore,esults() methods are
used to retrieve the data returned.
36THF -ypes o" parameters in Stored Procedures
n parameters F arameters that are passed into an operation
Out parametersF arameters passed by reference. They are expected to
return a result of the reference type.
nout ParametersF 6ut parameters that contain an initial value and may
change as a result of the operation.
J1=C supports all * parameters types
>. ,esultSet get,esultSet() t5rows SZ;+:ception 2 Beturns the current data
as the result of a statement execution as a BesultSet object.
#f there are no results to be read or if the result is an update count$ this method
returns null. 6nce read$ the results are cleared.
A. int get<pdate4ount() t5rows SZ;+:ception 2 Beturns the status of an
0pdate$ #nsert or 1elete <uery or a stored procedure. The value returned is the
number of ro%s affected. 2, is returned if there is no updatecount or if the data
returned is a resultset. 6nce read$ the update count is cleared.
@. boolean getGore,esults() t5rows SZ;+:ception 2 Moves to the next result
in a set of multiple results!update counts. This method returns true if the next
result is a BesultSet object. This method %ill also close any previous BesultSet
read.
1%3
Statements may or may not return a BesultSet object$ depending on the Statement
method used.
$&le)
The e:ecute<pdate() method is used to execute S\: statements that do not
expect a result (except a ro% count status+
int row4ount&
row4ount= Stmte:ecute<pdate(!H+;+6+ -,0G customer
PO+,+ customer /H = AG4\18>?B !)&
The 1elete <uery only delets a ro% from the customer table. #t does not return
any resultSet. So$ e:ecute<pdate() just returns the ro% count status in the
customer table after deletion of the ro% %ith customer#1 MCZ,E;*.
S\: statements that return a single set of results can use the e:ecuteZuery( )
method. The method returns a single BesultSet object. The object represents the
ro% information returned as a result of the <uery.
$&le)
,esultSet results&
results = stmte:ecuteZuery(!S+;+46 2-,0G S604Y%)&
65e statement !S+;+46 2-,0G S604Y% returns a single result set
object So e:ecuteZuery() met5od is used
$DAMPL$ ) s?lE,ja#a
11) simple java application t5at illustrates t5e use o( HriverGanager*
11Hriver *4onnection and Statement
1165is application is used to create t5e customer table in t5e database
import javanet2&
import javasLl2&
import javaio2&
public class sLlD
{4onnection conn&
11main
public static void main(String arg[])
{11look (or url*username and password
i( (arglengt5K?)
{Systemoutprintln(T+])G#;+ <S)\+T)&
Systemoutprintln(Tjava sLlD KurlJKusrJKpasswdJT)&
1265e url is !jdbc=odbc=in(o% w5ere in(o is t5e datasource name
)(ter t5e ur t5e user name and userBs password are to be
provided21
Systeme:it(1)&
1%4
'
11create an instance o( t5e class
sLlD sL=new sLlD()&
11initialiSe t5e connection
sLinitdb(arg[8]*arg[1]*arg[>])&
116est t5e connection by creating a customer table
sLtestdb()&
'
public void initdb(String url*String user*String passwd)
{11call used by HriverGanager to locate*load*and link t5e named class
try
{4lass(or3ame(Tsunjdbcodbc"dbc0dbcHriverT)&11"dbc0dbcbridge
'
catc5 (javalang4lass3ot-ound+:ception e)
{Systemoutprintln(THriver GessageT)&
Systemoutprintln(egetGessage())&
Systeme:it(1)&
'
try
{conn = HriverGanagerget4onnection(url*user*passwd)&11create a
connection
'
catc5 (SZ;+:ception e)
{Systemoutprintln(THatebase 4onnection (ailedT)&
Systemoutprintln(egetGessage())&
Systeme:it(1)&
'
'
public void testdb()
{
try{
11create t5e select statement
Statement stmt = conncreateStatement()&
11create a table named customer
stmte:ecute<pdate(T4,+)6+ 6).;+ customer(customerid U),4O),(18)*
lastname U),4O),(18)*(irstname U),4O),(18)*p5onenumber
U),4O),(Q)*streetaddress U),4O),(>8)*Sipcode U),4O),(Q))T)&
'catc5 (SZ;+:ception e)
{Systemoutprintln(egetGessage())&
Systeme:it(1)&
'
'
'
The above example creates a table customer in the datasource named info.
S\: statements that execute stored procedures (or trigger a stored procedure+ may return
more than one set of results. The e:ecute() method is used to return either a single
resultset or multiple resultsets. The method returns a boolean flag that is used to
determine %hether there are more resultsets. =ecause a resultset could either contain data
1%5
or the count of an operation that returns a ro% count$ the get,esultSet()$
getGore,esults()$ and get<pdate4ount() methods are used.
$&le)
12 )ssume SZ; string is an SZ; string w5ic5 returns multiple
resultsets 65e e:ecute() met5od returns true i( a ,esultSet is
returned
Statement stmt& ,esultSet results&
int count&
i( (stmte:ecute(SZ; string))
{ results = stmtget,esultSet()&
' 12 get t5e ,esultSet into results 21
else 12since stmte:ecute(SZ; string) returned (alse an
updatecount
was returned 21
{ count = stmtget<pdate4ount()&
12get t5e noo( rows a((ected into t5e variable
count21
'
11process t5e (irst results 5ere
12 3ow loop until t5ere are no more results or update counts 21
do { 11/s t5e ne:t result a ,esultSetN
i( (stmtgetGore,esults())
{ results = stmtget,esultSet()& '
else { count = stmtget<pdate4ount()&
'
11 process ne:t results 5ere
' w5ile ((results $=null) __ (count $ = -1))&
1%6
;'epa'e6 State-e"t
The #reparedStatement interface extends the statement interface. 8hen there is a S\:
statement that re<uires repitition %ith minor variations$ the reparedStatement provides
an efficient mechanism for passing a precompiled S\: statement that uses parameters.
SignatureF public inter(ace #reparedStatement e:tends Statement
#reparedStatement parameters are used to pass data into a S\: statement$ so they are
considered #n parameters and are filled in by using set6ype methods.
The set6ype methods fill the value of parameters (mar'ed by <uestion mar's+ in a
reparedStatement. These parameters are indexed from , to n.
$&le)
int reduction = 18&
4onnection msLlconn=HriverGanagerget4onnection(url*usr*passwd)&
#reparedStatement ps = msglconnprepareStatement
(!<#H)6+ 4atalog S+6 #rice=N PO+,+ /tem/H = N%)
11Ho t5e updates in a loop
(or (int i=8& iKreduced itemslengt5()& /FF)
{
12 65e set6ype met5ods set t5e value o( t5e parameters noted in t5e
SZ; statement wit5 Luestion marks(N) 65ey are inde:ed starting (rom 1
to n 21
psset-loat(1* (#rice;ist[i] 2 (((loat) (188 - reduction)1188)))&
pssetString(>* reduced/tems[ i ])&
i( (pse:ecute<pdate() ==8)
{t5row new SZ;+:ception(!3o /tem/H=%Freduced/tems[i])&
'
'
arameters hold their current values until either a ne% set6ype method is called or the
method clear#arameters ( ) is called for the #reparedStatement object.
#n addition to the execute methods inherited from the Statement* #reparedStatement
declares the follo%ing set6ype methods. Hach method ta'es ; arguments.
,. / parameter index and
;. The primitive or class type.
1%$
$DAMPL$) %ustomer,ja#a
11customer record class t5is class is used to store and access
customer data (rom t5e 11database
import javasLl2&
import javanet2&
public class 4ustomer{
private 4onnection conn&12conn is a 4onnection object21
private #reparedStatement insert3ew4ustomer&
private #reparedStatement delete4ustomer&
private #reparedStatement get4ustomer&
private #reparedStatement update4ustomer&
12 insert3ew4ustomer*delete4ustomer*get4ustomer
and update4ustomer are preparedStatements21
11customer constructor=store a localcopy o( t5e connection
11object4reate statements (or use later
public 4ustomer(4onnection c){
conn=c&
try {
insert3ew4ustomer = connprepareStatement
(T/3S+,6 /360 4ustomer U);<+S(N*N*N*N*N*N)T)&
12inserts into t5e customer table t5e values (or all columns o( t5e
table and t5e values to be inserted are represented by t5e Luestion
marks(N)21
delete4ustomer = connprepareStatement
(TH+;+6+ -,0G 4ustomer w5ere ;ast3ame=NT)&
12deletes a customer wit5 t5e given last name (rom t5e customer
table21
update4ustomer = connprepareStatement
(T<#H)6+ 4ustomer S+6 Street)ddress =N PO+,+ ;ast3ame =NT)&
12updates t5e street address o( a customer wit5 t5e given last
name21
get4ustomer = connprepareStatement
(TS+;+46 2 -,0G 4ustomer w5ere ;ast3ame=NT)&
12selects all t5e details o( t5e customer wit5 t5e given last name21
'catc5 (SZ;+:ception e)
{Systemoutprintln(T<nable to create prepared or callable
statementsT)&
'
'
11Get5od (or creating a new customer record
public void insert3ew4ustomer(String id*String lname*String
(name*String pnum*String addr* String Sip) t5rows insert-ailed+:ception
*SZ;+:ception
{
insert3ew4ustomersetString(1*id)& 11set6ype met5ods are used to
insert3ew4ustomersetString(>*lname)&11set t5e values o( t5e /3
parameters
1%%
insert3ew4ustomersetString(?*(name)&11o( t5e preparedStatement
w5ic5
insert3ew4ustomersetString(E*pnum)&11are represented by Luestion
marks
insert3ew4ustomersetString(D*addr)&
insert3ew4ustomersetString(R*Sip)&
11e:ecute t5e statement
i( (insert3ew4ustomere:ecute<pdate() $= 1)
1265e e:ecute<pdate met5od did not insert t5e row o( new values21
t5row new insert-ailed+:ception
(Tcould not e:ecute insertT)&
'
11\et a single customer record wit5 t5is lastname
public void get4ustomer(String lname) t5rows SZ;+:ception
{
get4ustomersetString(1*lname)&
,esultSet rs= get4ustomere:ecuteZuery() &
1265e preparedStatement get4ustomer is e:ecuted wit5 t5e e:ecuteZuery()
met5od w5ic5 returns t5e results in a ,esultSet object21
Systemoutprint(rsgetString(1)FT T)&
Systemoutprint(rsgetString(>)FT T)&
Systemoutprint(rsgetString(?)FT T)&
Systemoutprint(rsgetString(E)FT T)&
Systemoutprint(rsgetString(D)FT T)&
Systemoutprintln(rsgetString(R))&
Systemoutprintln()&
'
11met5od (or deleting a customer record wit5 t5e given lastname
public void delete4ustomer(String name)
t5rows SZ;+:ception
{
delete4ustomersetString(1*name)&
delete4ustomere:ecute<pdate()&
'
11met5od to update t5e streetaddress o( t5e customer wit5 t5e given
11lastname
public void update4ustomer(String add*String name) t5rows SZ;+:ception
{
update4ustomersetString(1*add)&
update4ustomersetString(>*name)&
update4ustomere:ecute<pdate()&
'
11met5od to delete all customer records
public void deleteall4ustomers()t5rows SZ;+:ception
{
1%+
Statement stmt=conncreateStatement()&
12) statement object is created 21
try {
stmte:ecute<pdate(TH+;+6+ -,0G 4<S60G+,T)&
' catc5(SZ;+:ception e)
{Systemoutprintln(egetGessage())&
Systeme:it(1)&
'
'
11met5od to update t5e customerid o( all customer records
public void updateall4ustomers() t5rows SZ;+:ception
{ Statement stmt = conncreateStatement()&
try
{stmte:ecute<pdate(T<#H)6+ 4ustomer S+6
4ustomer/H=403U+,6(U),4O),*8)F403U+,6(U),4O),*8)F403U+,6(U),4O),*8)F4us
tomer/HT)&
'
catc5(SZ;+:ception e)
{Systemoutprintln(egetGessage())&
Systeme:it(1)&
'
'
11met5od to select all records in t5e customer table
public void selectall4ustomers() t5rows SZ;+:ception
{ Statement stmt = conncreateStatement()&
try
{,esultSet rs=stmte:ecuteZuery(TS+;+46 2 -,0G 4ustomerT)&
w5ile(rsne:t())
{Systemoutprint(rsgetString(1)FT T)&
Systemoutprint(rsgetString(>)FT T)&
Systemoutprint(rsgetString(?)FT T)&
Systemoutprint(rsgetString(E)FT T)&
Systemoutprint(rsgetString(D)FT T)&
Systemoutprintln(rsgetString(R))&
'
'catc5(SZ;+:ception e)
{Systemoutprintln(egetGessage())&
Systeme:it(1)&
'
'
class insert-ailed+:ception e:tends SZ;+:ception {
public insert-ailed+:ception (String reason)
{super(reason)& '
public insert-ailed+:ception ()
{ super ()& '
'
'
1+1
3o%$a simple java application to test the above Customer class is %ritten.
The program belo% is menu driven %hich calls the appropriate method in the Customer
class depending upon the users choice.
1+1
$DAMPL$F SFLG,ja#a
11) simple java application t5at tests t5e customer class
import javasLl2&
import javanet2&
import javaio2&
public class SZ;E{
4onnection conn&
public static void main(String arg[])
{i( (arglengt5K?)
{Systemoutprintln(T+:ample use=T)&
Systemoutprintln(Tjava SZ;E KurlJ KusernameJ KpasswordJT)&
Systeme:it(1)&
'
SZ;E sL = new SZ;E ()&
sLinitdb(arg[8]*arg[1]*arg[>])&
sLtestdb()&
'
public void initdb(String url*String user*String passwd) {
try{
4lass(or3ame(Tsunjdbcodbc"dbc0dbcHriverT)&
'
catc5(javalang4lass3ot-ound+:ception e)
{Systemoutprintln(THriver GessageT)&
'
try {
conn = HriverGanagerget4onnection(url*user*passwd)&
'
catc5 (SZ;+:ception e) {
Systemoutprintln(THatabase 4onnection (ailed=T)&
Systemoutprintln(egetGessage())&
Systeme:it(1)&
'
'
11simple met5od to test t5e customer class met5ods
public void testdb()
{
int c5oice&
11create an instance o( customer class
4ustomer cust = new 4ustomer(conn)&
do
{ Systemoutprintln(T2222222222222222222222G+3<22222222222222222222
222T)&
Systemoutprintln(T1 /3S+,6 03+ 4<S60G+,T)&
Systemoutprintln(T> H+;+6+ 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ameT)&
Systemoutprintln(T? <#H)6+ 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ameT)&
Systemoutprintln(TE S+;+46 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ameT)&
Systemoutprintln(TD H+;+6+ );; 4<S60G+,ST)&
1+2
Systemoutprintln(TR <#H)6+ );; 4<S60G+,S 60 4O)3\+ );; 6O+/, /HS
60T)&
Systemoutprintln(T \+6 )<\G+36+H .+-0,+ P/6O 888T)&
Systemoutprintln(T@ S+;+46 );; 4<S60G+,ST)&
Systemoutprintln(TQ Z</6T)&
Systemoutprintln(T2222222222222222222+3H22222222222222222222222222
2T)&
Systemoutprintln(T+36+, [0<, 4O0/4+ (11>1?1E1D1R1@1Q)T)&
c5oice=read/nt()&
switc5(c5oice)
{
case 1=
Systemoutprintln(T+36+, /H 0- 6O+ 3+P 4<S60G+,T)&
String id1 = readString()&
Systemoutprintln(T+36+, ;ast3ame 0- 6O+ 3+P 4<S60G+, T)&
String id> = readString()&
Systemoutprintln(T+36+, -irst3ame 0- 3+P 4<S60G+, T)&
String id? = readString()&
Systemoutprintln(T+36+, #5one3umber 0- 3+P 4<S60G+, T)&
String idE = readString()&
Systemoutprintln(T+36+, Streetaddress 0- 3+P 4<S60G+, T)&
String idD = readString()&
Systemoutprintln(T+36+, ^ipcode 0- 3+P 4<S60G+, T)&
String idR =readString()&
11now insert a new customer
try{custinsert3ew4ustomer(id1*id>*id?*idE*idD*idR)&
'
catc5(SZ;+:ception e)
{Systemoutprintln(T/nsert -ailed=T)&
Systemoutprintln(egetGessage())& Systeme:it(1)&
'
break&
case >=String dname&
Systemoutprintln(T;ast3ame 0- 6O+ 4<S60G+, 60 .+ H+;+6+HT)&
dname=readString()&
11now delete a customer wit5 t5e given lastname
try
{custdelete4ustomer(dname)&
'catc5 (SZ;+:ception e)
{
Systemoutprintln(egetGessage())&
Systeme:it(1)&
'
break&
case ?=
Systemoutprintln(T+36+, 6O+ lastname 0- 6O+ 4<S60G+,T)&
Systemoutprintln(TPO0S+ )HH,+SS /S 60 .+ <#H)6+HT)&
String name=readString()&
Systemoutprintln(T+36+, 6O+ 3+P )HH,+SST)&
String add=readString()&
1+3
11now update t5e streetaddress o( t5e customer wit5 t5e given
lastname 11 to t5e given new streetaddress
try{
custupdate4ustomer(add*name)&
'catc5(SZ;+:ception e)
{Systemoutprintln(egetGessage())&
Systeme:it(1)&
'
break&
case E=
Systemoutprintln(T+36+, 6O+ ;ast3ame 0- 6O+ 4<S60G+, PO0S+
H+6)/;ST)&
Systemoutprintln(T),+ 60 .+ #,/36+HT)&
String lname =readString()&
Systemoutprintln(Tt5e details o( t5e 4ustomer areT)&
11now get t5e details o( t5e customer wit5 t5e given lastname
try{
custget4ustomer(lname)&
'catc5 (SZ;+:ception e)
{Systemoutprintln(T,ead (ailedT)&
Systemoutprintln(egetGessage())&
Systeme:it(1)&
'
break&
case D=11now*delete all customer records
try
{custdeleteall4ustomers()&'
catc5(SZ;+:ception e)
{Systemoutprintln(egetGessage())&
Systeme:it(1)&
'
break&
case R=11now*update customerid o( all customer records in t5e customer
11table
try{custupdateall4ustomers()&
'catc5(SZ;+:ception e)
{Systemoutprintln(egetGessage())&
Systeme:it(1)&
'
break&
case @=11now select all customer records in t5e table
try
{custselectall4ustomers()&
'catc5(SZ;+:ception e)
{Systemoutprintln(egetGessage())&
Systeme:it(1)&
'
break&
1+4
case Q=
break &
de(ault = break&
'
'w5ile (c5oice $=Q)&
'
public static int read/nt()
{String s&
int c5oice=8&
s = readString()&
try
{c5oice = /ntegervalue0((strim())intUalue()&
' catc5 (3umber-ormat+:ception e)
{Systemoutprintln(T#;+)S+ +36+, )3 /36+\+, U);<+T)&
'
return c5oice&
'
public static String readString()
{int c5&
boolean done = (alse&
String r=TT&
w5ile($done)
{
try
{c5=Systeminread()&
i((c5K8MM(c5ar)c5==XCnX)
done=true&
else r=rF(c5ar)c5&
'
catc5(javaio/0+:ception e)
{done = true& '
'
return r&
'
'
O(-P(-
116O/S /S 6O+ 0<6#<6 PO+3 6O+ SZ;E )##;/4)6/03 /S +]+4<6+H
22222222222222222222222G+3<22222222222222222222222222
1 /3S+,6 03+ 4<S60G+,
> H+;+6+ 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
? <#H)6+ 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
E S+;+46 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
D H+;+6+ );; 4<S60G+,S
R <#H)6+ );; 4<S60G+,S 60 4O)3\+ );; 6O+/, /HS 60
\+6 )<\G+36+H .+-0,+ P/6O 888
@ S+;+46 );; 4<S60G+,S
1+5
Q Z</6
22222222222222222222222+3H222222222222222222222222222222
+36+, [0<, 4O0/4+ (11>1?1E1D1R1@1Q)
1
+36+, /H 0- 3+P 4<S60G+,
1
+36+, ;ast3ame 0- 3+P 4<S60G+,
./;;
+36+, -irst3ame 0- 3+P 4<S60G+,
"03+S
+36+, #5one3umber 0- 6O+ 4<S60G+, 60 .+ /3S+,6+H
@R88?Q?
+36+, Streetaddress 0- 6O+ 4<S60G+, 60 .+ /3S+,6+H
4),0;/3)
+36+, ^ipcode 0- 6O+ 4<S60G+, 60 .+ /3S+,6+H
D?881@
22222222222222222222222G+3<22222222222222222222222222
1 /3S+,6 03+ 4<S60G+,
> H+;+6+ 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
? <#H)6+ 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
E S+;+46 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
D H+;+6+ );; 4<S60G+,S
R <#H)6+ );; 4<S60G+,S 60 4O)3\+ );; 6O+/, /HS 60
\+6 )<\G+36+H .+-0,+ P/6O 888
@ S+;+46 );; 4<S60G+,S
Q Z</6
22222222222222222222222+3H222222222222222222222222222222
+36+, [0<, 4O0/4+ (11>1?1E1D1R1@1Q)
@
1 ./;; "03+S @R88?Q? 4),0;/3) D?881@
22222222222222222222222G+3<22222222222222222222222222
1 /3S+,6 03+ 4<S60G+,
> H+;+6+ 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
? <#H)6+ 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
E S+;+46 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
D H+;+6+ );; 4<S60G+,S
R <#H)6+ );; 4<S60G+,S 60 4O)3\+ );; 6O+/, /HS 60
\+6 )<\G+36+H .+-0,+ P/6O 888
@ S+;+46 );; 4<S60G+,S
Q Z</6
22222222222222222222222+3H222222222222222222222222222222
+36+, [0<, 4O0/4+ (11>1?1E1D1R1@1Q)
?
+36+, 6O+ lastname 0- 6O+ 4<S60G+,
PO0S+ )HH,+SS /S 60 .+ <#H)6+H
./;;
+36+, 6O+ 3+P )HH,+SS
40;<G./)
1+6
22222222222222222222222G+3<22222222222222222222222222
1 /3S+,6 03+ 4<S60G+,
> H+;+6+ 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
? <#H)6+ 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
E S+;+46 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
D H+;+6+ );; 4<S60G+,S
R <#H)6+ );; 4<S60G+,S 60 4O)3\+ );; 6O+/, /HS 60
\+6 )<\G+36+H .+-0,+ P/6O 888
@ S+;+46 );; 4<S60G+,S
Q Z</6
22222222222222222222222+3H222222222222222222222222222222
+36+, [0<, 4O0/4+ (11>1?1E1D1R1@1Q)
@
1 ./;; "03+S @R88?Q? 40;<G./) D?881@
22222222222222222222222G+3<22222222222222222222222222
1 /3S+,6 03+ 4<S60G+,
> H+;+6+ 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
? <#H)6+ 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
E S+;+46 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
D H+;+6+ );; 4<S60G+,S
R <#H)6+ );; 4<S60G+,S 60 4O)3\+ );; 6O+/, /HS 60
\+6 )<\G+36+H .+-0,+ P/6O 888
@ S+;+46 );; 4<S60G+,S
Q Z</6
22222222222222222222222+3H222222222222222222222222222222
+36+, [0<, 4O0/4+ (11>1?1E1D1R1@1Q)
1
+36+, /H 0- 6O+ 4<S60G+, 60 .+ /3S+,6+H
>
+36+, ;ast3ame 0- 6O+ 4<S60G+, 60 .+ /3S+,6+H
")G
+36+, -irst3ame 0- 6O+ 4<S60G+, 60 .+ /3S+,6+H
SP/-6
+36+, #5one3umber 0- 6O+ 4<S60G+, 60 .+ /3S+,6+H
@8D1?9>
+36+, Streetaddress 0- 6O+ 4<S60G+, 60 .+ /3S+,6+H
6+])S
+36+, ^ipcode 0- 6O+ 4<S60G+, 60 .+ /3S+,6+H
D888E8
22222222222222222222222G+3<22222222222222222222222222
1 /3S+,6 03+ 4<S60G+,
> H+;+6+ 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
? <#H)6+ 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
E S+;+46 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
D H+;+6+ );; 4<S60G+,S
1+$
R <#H)6+ );; 4<S60G+,S 60 4O)3\+ );; 6O+/, /HS 60
\+6 )<\G+36+H .+-0,+ P/6O 888
@ S+;+46 );; 4<S60G+,S
Q Z</6
22222222222222222222222+3H222222222222222222222222222222
+36+, [0<, 4O0/4+ (11>1?1E1D1R1@1Q)
@
1 ./;; "03+S @R88?Q? 40;<G./) D?881@
> ")G SP/-6 @8D1?9> 6+])S D888E8
22222222222222222222222G+3<22222222222222222222222222
1 /3S+,6 03+ 4<S60G+,
> H+;+6+ 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
? <#H)6+ 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
E S+;+46 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
;. H+;+6+ );; 4<S60G+,S
R <#H)6+ );; 4<S60G+,S 60 4O)3\+ );; 6O+/, /HS 60
\+6 )<\G+36+H .+-0,+ P/6O 888
@ S+;+46 );; 4<S60G+,S
Q Z</6
22222222222222222222222+3H222222222222222222222222222222
+36+, [0<, 4O0/4+ (11>1?1E1D1R1@1Q)
>
+36+, 6O+ ;ast3ame 0- 6O+ 4<S60G+, 60 .+ H+;+6+H
./;;
22222222222222222222222G+3<22222222222222222222222222
1 /3S+,6 03+ 4<S60G+,
> H+;+6+ 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
? <#H)6+ 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
E S+;+46 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
D H+;+6+ );; 4<S60G+,S
R <#H)6+ );; 4<S60G+,S 60 4O)3\+ );; 6O+/, /HS 60
\+6 )<\G+36+H .+-0,+ P/6O 888
@ S+;+46 );; 4<S60G+,S
Q Z</6
22222222222222222222222+3H222222222222222222222222222222
+36+, [0<, 4O0/4+ (11>1?1E1D1R1@1Q)
@
> ")G SP/-6 @8D1?9> 6+])S D888E8
22222222222222222222222G+3<22222222222222222222222222
1 /3S+,6 03+ 4<S60G+,
> H+;+6+ 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
? <#H)6+ 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
E S+;+46 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
D H+;+6+ );; 4<S60G+,S
R <#H)6+ );; 4<S60G+,S 60 4O)3\+ );; 6O+/, /HS 60
\+6 )<\G+36+H .+-0,+ P/6O 888
1+%
@ S+;+46 );; 4<S60G+,S
Q Z</6
22222222222222222222222+3H222222222222222222222222222222
+36+, [0<, 4O0/4+ (11>1?1E1D1R1@1Q)
E
+36+, 6O+ ;ast3ame 0- 6O+ 4<S60G+, PO0S+ H+6)/;S
),+ 60 .+ #,/36+H
")G
t5e details o( t5e 4ustomer are
> ")G SP/-6 @8D1?9> 6+])S D888E8
22222222222222222222222G+3<22222222222222222222222222
1 /3S+,6 03+ 4<S60G+,
> H+;+6+ 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
? <#H)6+ 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
E S+;+46 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
D H+;+6+ );; 4<S60G+,S
R <#H)6+ );; 4<S60G+,S 60 4O)3\+ );; 6O+/, /HS 60
\+6 )<\G+36+H .+-0,+ P/6O 888
@ S+;+46 );; 4<S60G+,S
Q Z</6
22222222222222222222222+3H222222222222222222222222222222
+36+, [0<, 4O0/4+ (11>1?1E1D1R1@1Q)
R
22222222222222222222222G+3<22222222222222222222222222
1 /3S+,6 03+ 4<S60G+,
> H+;+6+ 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
? <#H)6+ 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
*. S+;+46 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
D H+;+6+ );; 4<S60G+,S
R <#H)6+ );; 4<S60G+,S 60 4O)3\+ );; 6O+/, /HS 60
\+6 )<\G+36+H .+-0,+ P/6O 888
@ S+;+46 );; 4<S60G+,S
Q Z</6
22222222222222222222222+3H222222222222222222222222222222
+36+, [0<, 4O0/4+ (11>1?1E1D1R1@1Q)
@
888> ")G SP/-6 @8D1?9> 6+])S D888E8
22222222222222222222222G+3<22222222222222222222222222
1 /3S+,6 03+ 4<S60G+,
> H+;+6+ 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
? <#H)6+ 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
E S+;+46 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
D H+;+6+ );; 4<S60G+,S
R <#H)6+ );; 4<S60G+,S 60 4O)3\+ );; 6O+/, /HS 60
\+6 )<\G+36+H .+-0,+ P/6O 888
@ S+;+46 );; 4<S60G+,S
Q Z</6
22222222222222222222222+3H222222222222222222222222222222
1++
+36+, [0<, 4O0/4+ (11>1?1E1D1R1@1Q)
D
22222222222222222222222G+3<22222222222222222222222222
1 /3S+,6 03+ 4<S60G+,
> H+;+6+ 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
? <#H)6+ 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
E S+;+46 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
D H+;+6+ );; 4<S60G+,S
R <#H)6+ );; 4<S60G+,S 60 4O)3\+ );; 6O+/, /HS 60
\+6 )<\G+36+H .+-0,+ P/6O 888
@ S+;+46 );; 4<S60G+,S
Q Z</6
22222222222222222222222+3H222222222222222222222222222222
+36+, [0<, 4O0/4+ (11>1?1E1D1R1@1Q)
@
22222222222222222222222G+3<22222222222222222222222222
1 /3S+,6 03+ 4<S60G+,
> H+;+6+ 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
? <#H)6+ 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
E S+;+46 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
D H+;+6+ );; 4<S60G+,S
R <#H)6+ );; 4<S60G+,S 60 4O)3\+ );; 6O+/, /HS 60
\+6 )<\G+36+H .+-0,+ P/6O 888
@ S+;+46 );; 4<S60G+,S
Q Z</6
22222222222222222222222+3H222222222222222222222222222222
+36+, [0<, 4O0/4+ (11>1?1E1D1R1@1Q)
Q
#n addition to passing parameters to prepared statements $J1=C defines an escape syntax
to pass #3 parameters to the S\: string that is passed to the Statement objects %hile exec
2uting the Statement object %ith one of the execute methods.
!!first$inorde to insert a cusomer$into the customer table$S\:>.java
!!is executed a customer is inserted.
!!This is the output %hen s<l>.java is executed.
22222222222222222222222G+3<22222222222222222222222222
1 /3S+,6 03+ 4<S60G+,
> H+;+6+ 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
? <#H)6+ 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
E S+;+46 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
D H+;+6+ );; 4<S60G+,S
R <#H)6+ );; 4<S60G+,S 60 4O)3\+ );; 6O+/, /HS 60
\+6 )<\G+36+H .+-0,+ P/6O 888
@ S+;+46 );; 4<S60G+,S
Q Z</6
22222222222222222222222+3H222222222222222222222222222222
211
+36+, [0<, 4O0/4+ (11>1?1E1D1R1@1Q)
1
+36+, /H 0- 6O+ 4<S60G+, 60 .+ /3S+,6+H
1
+36+, ;ast3ame 0- 6O+ 4<S60G+, 60 .+ /3S+,6+H
./;;
+36+, -irst3ame 0- 6O+ 4<S60G+, 60 .+ /3S+,6+H
"03+S
+36+, #5one3umber 0- 6O+ 4<S60G+, 60 .+ /3S+,6+H
@R88?Q?
+36+, Streetaddress 0- 6O+ 4<S60G+, 60 .+ /3S+,6+H
4),0;/3)
+36+, ^ipcode 0- 6O+ 4<S60G+, 60 .+ /3S+,6+H
D88 81?
22222222222222222222222G+3<22222222222222222222222222
1 /3S+,6 03+ 4<S60G+,
> H+;+6+ 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
? <#H)6+ 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
E S+;+46 4<S60G+,S P/6O 6O+ \/U+3 ;ast3ame
D H+;+6+ );; 4<S60G+,S
R <#H)6+ );; 4<S60G+,S 60 4O)3\+ );; 6O+/, /HS 60
\+6 )<\G+36+H .+-0,+ P/6O 888
@ S+;+46 );; 4<S60G+,S
Q Z</6
22222222222222222222222+3H222222222222222222222222222222
+36+, [0<, 4O0/4+ (11>1?1E1D1R1@1Q)
Q
The follo%ing example passes the lastname of a customer %hose details are %anted$ to
the S\: string in the execute0pdate method of a statement object using an escape
syntax.
$DAMPL$ ) s?l++,ja#a
11) simple application to test t5e escape synta: used to pass
11parameters to statement objects
import javasLl2&
import javanet2&
import javaio2&
public class sLl11
{
4onnection conn&
public static void main(String arg[])
{ i( ((arglengt5)K?)
{Systemoutprintln(T+])G#;+ <S)\+T)&
Systemoutprintln(Tjava sLl11 KurlJKuserJKpasswdJT)&
Systeme:it(1)&
'
211
sLl11 sL = new sLl11()&
sLinitdb(arg[8]*arg[1]*arg[>])&
sLtestdb()&
'
public void initdb(String url*String user* String passwd)
{ try
{4lass(or3ame(Tsunjdbcodbc"dbc0dbcHriverT)&
'
catc5 (4lass3ot-ound+:ception e)
{Systemoutprintln(TH,/U+, G+SS)\+T)&
Systemoutprintln(egetGessage())&
Systeme:it(1)&
'
try
{conn =HriverGanagerget4onnection(url*user*passwd)&
'
catc5 (SZ;+:ception e)
{ Systemoutprintln(T4033+46/03 -)/;+HT)&
Systemoutprintln(egetGessage())&
Systeme:it(1)&
'
'
public void testdb()
{ Systemoutprintln (T+36+, 6O+ ;)S63)G+ 0- 6O+ 4<S60G+, PO0S+
H+6)/;S ),+ P)36+HT)&
String s=readString()&
try
{ 11create a statement
Statement stmt = conncreateStatement()&
11get t5e details o( t5e customer wit5 t5e given lastname
,esultSet rs= stmte:ecuteZuery(Tselect 2 (rom customer w5ere
lastname=TFTCXTFsFTCXT)&11lastname is passed to t5e SZ; string using an
escape synta:
w5ile(rsne:t())
{ Systemoutprint(rsgetString(1)FT T)&
Systemoutprint(rsgetString(>)FT T)&
Systemoutprint(rsgetString(?)FT T)&
Systemoutprint(rsgetString(E)FT T)&
Systemoutprint(rsgetString(D)FT T)&
Systemoutprint(rsgetString(R))&
'
'
catc5(SZ;+:ception e)
{Systemoutprintln(egetGessage())&
Systeme:it(1)&
'
'
public static String readString()
{ int c5&
boolean done =(alse&
String r=TT&
w5ile($done)
212
{try
{c5=Systeminread()&
i((c5K8MM(c5ar)c5==XCnX)
done=true&
else r=rF(c5ar)c5&
'
catc5(javaio/0+:ception e)
{done=true&
'
'
return r&
'
'
O(-P(-
+36+, 6O+ ;)S63)G+ 0- 6O+ 4<S60G+, PO0S+ H+6)/;S ),+ P)36+H
NP(-
./;;
O(-P(-
1 ./;; "03+S @R88?Q? 4),0;/3) D88 81?
213
set-ype methods the Database
Method Signature Ja#a-ype SFL-ype "rom
void set.yte (int inde:*byte b) byte 6/3[/36
void setS5ort(int inde:* s5ort :) s5ort SG);;/36
void set/nt (int inde:* int /) int /36+\+,
void set;ong (int inde:* long l) long ./\/36
void set-loat (int inde:* (loat
()
(loat -;0)6
void setHouble (int inde:* double
d)
double H0<.;+
void set.igHecimal (int inde:*
.igHecimal :)
javamat5.igHecimal 3<G+,/4
void setString (int inde:* String
s)
javalongString U),4O), or
;03\U),4O),
void set.ytes (int inde:* byte
:[])
byte array U),./3),[ or
;03\U), ./3),[
void setHate (int inde:* Hate d) javasLlHate H)6+
void set6ime (int inde:* 6ime t) javasLl6ime 6/G+
void set6imestamp (int inde:*
6imeStampWts)
javasLl6imeStamp 6/G+S6)G#
void set3ull (int inde:* int
sLl6ype)
javasLl6ypes lists SZ; types
by number and
3<;;
/nteger 8(Sero)
void Set.oolean(int inde:*
boolean b)
boolean ./6
%allableStatement
SignatureF public inter(ace 4allableStatement e:tends #reparedStatement
The CallableStatement interface is used to execute S\: stored procedures.
CallableStatement inherits from the reparedStatement interface$ so all of the execute and
setType methods are available.
Stored procedures have a varying syntax among database vendors$ so J1=C defines
standard %ay for all B1=MSS to call stored procedures.
The J1=C uses an escape syntax allo%ing parameters to be passed as #n parameters and
6ut parameters. The syntax also allo%s a result to be returned$ and if this syntax is used$
the parameter must be registered as an 6ut parameter.
214
$&le)
9ere is an example of a CallableStatement returning an 6ut parameter.
4allableStatement cs=connprepare4all (! {call getZuote (N* N) ' ! )&
cssetString (1* Stock3ame)&
12 javasLl6ypes de(ines SZ; data types t5at are returned as out
parameters 21
csregister0ut #arameter (>* javasLltypes-;0)6)&
cse:ecute<pdate()&
(loat Luote=csget-loat(>)
The stored procedure named get\uote returns the <uote of an item in the stoc'.
CallableStatement defines a set of getType methods that convert the S\: types returned
from the database to Javatypes. These methods match the setType methods declared by
reparedStatement.
The getType methods access data in each column as the result of a <uery. Hach column
can be accessed by either its position in the ro%$ numbered from , to n columns$ or by its
name$ li'e cust#1 (%hich is a column name in a table called customer+.
The example belo% create a stored procedure using a statementobject.
$DAMPL$) s?l+0,ja#a
11) simple java applicatin w5ic5 creates a stored procedure called \06S
1165e stored procedure takes t5e lastname o( a customer as input and
11gives 5is address as output
import javaio2&
import javasLl2&
import javanet2&
public class sLl18
{4onnection conn&
public static void main(String arg[])
{ i( ((arglengt5)K?)
{Systemoutprintln(T+])G#;+ <S)\+T)&
Systemoutprintln(Tjava sLl18 KurlJKuserJKpasswdJT)&
Systeme:it(1)&
'
sLl18 sL = new sLl18()&
sLinitdb(arg[8]*arg[1]*arg[>])&
sLtestdb()&
'
public void initdb(String url*String user* String passwd)
{ try
215
{4lass(or3ame(Tsunjdbcodbc"dbc0dbcHriverT)&
'
catc5 (4lass3ot-ound+:ception e)
{Systemoutprintln(TH,/U+, G+SS)\+T)&
Systemoutprintln(egetGessage())&
Systeme:it(1)&
'
try
{conn =HriverGanagerget4onnection(url*user*passwd)&
'
catc5 (SZ;+:ception e)
{ Systemoutprintln(T4033+46/03 -)/;+HT)&
Systemoutprintln(egetGessage())&
Systeme:it(1)&
'
'
public void testdb()
{
try
{11create a statement
Statement stmt = conncreateStatement()&
11create t5e stored procedure \06S
stmte:ecute<pdate(T4,+)6+ #,04+H<,+ \06S Vplname U),4O),(18)*Vppno
U),4O),(Q) output as select Vppno=p5onenumber -,0G 4<S60G+, PO+,+
;ast3ame=Vplname T)&
'
catc5(SZ;+:ception e)
{Systemoutprintln(egetGessage())&
Systeme:it(1)&
'
'
'
The example belo% calls the stored procedure created in the above program using
a callable statement.
$DAMPL$ ) s?lH,ja#a
11) simple java application w5ic5 calls a stored procedure called
11\+6S w5ic5 gives t5e p5onenumber o( a customer as out parameter
11wit5 t5e given lastname as in parameter
import javasLl2&
import javanet2&
import javaio2&
public class sLl@
{4onnection conn&
public static void main(String arg[])
{ i( ((arglengt5)K?)
{Systemoutprintln(T+])G#;+ <S)\+T)&
Systemoutprintln(Tjavas sLl@ KurlJKuserJKpasswdJT)&
Systeme:it(1)&
216
'
sLl@ sL = new sLl@()&
sLinitdb(arg[8]*arg[1]*arg[>])&
sLtestdb()&
'
public void initdb(String url*String user* String passwd)
{ try
{4lass(or3ame(Tsunjdbcodbc"dbc0dbcHriverT)&
'
catc5 (4lass3ot-ound+:ception e)
{Systemoutprintln(TH,/U+, G+SS)\+T)&
Systemoutprintln(egetGessage())&
Systeme:it(1)&
'
try
{conn =HriverGanagerget4onnection(url*user*passwd)&
'
catc5 (SZ;+:ception e)
{ Systemoutprintln(T4033+46/03 -)/;+HT)&
Systemoutprintln(egetGessage())&
Systeme:it(1)&
'
'
public void testdb()
{ Systemoutprintln(T+36+, 6O+ ;)S63)G+ 0- 6O+ 4<S60G+, PO0S+
#O03+3<G.+, /S P)36+HT)&
String s=readString()&
try
{ 11create t5e callable statement cs w5ic5 calls t5e storedprocedure
\06S
4allableStatement cs = connprepare4all(T{call \06S(N*N)'T)&
cssetString(1*s)&
csregister0ut#arameter(>*javasLl6ypesU),4O),)&
11e:ecute t5e callable statement
cse:ecute<pdate()&
Systemoutprintln(csgetString(>))&
'
catc5(SZ;+:ception e)
{Systemoutprintln(egetGessage())&
Systeme:it(1)&
'
'
public static String readString()
{ int c5&
boolean done =(alse&
String r=TT&
w5ile($done)
{try
{c5=Systeminread()&
i((c5K8MM(c5ar)c5==XCnX)
done=true&
else r=rF(c5ar)c5&
'
21$
catc5(javaio/0+:ception e)
{done=true&
'
'
return r&
'
'
0<6#<6
+36+, 6O+ ;)S63)G+ 0- 6O+ 4<S60G+, PO0S+ #O03+3<G.+, /S P)36+H
/3#<6
./;;
0<6#<6
@R88?Q?
get-ype methods
Method Signature Ja#a-ype SFL-ype "rom the
Database
boolean get.oolean(int inde:) boolean ./6
byte get.yte (int inde:) byte 6/3[/36
s5ort getS5ort(int inde: ) s5ort SG);;/36
int get/nt (int inde:) int /36+\+,
long get;ong (int inde: ) long ./\/36
(loat get-loat (int inde: ) (loat -;0)6
double getHouble (int inde: ) double H0<.;+
.igHecimal get.igHecimal (int
inde:* int scale)
javamat5.igHecimal 3<G+,/4
String getString (int inde: ) String 4O),*U),4O), or
;03\U),4O),
byte[] get.ytes (int inde: ) byte array ./3),[ or
U), ./3),[
Hate getHate (int inde: ) javasLlHate H)6+
6ime get6ime (int inde:) javasLl6ime 6/G+
6imeStamp get6imeStamp (int
inde:)
javasLl6imeStamp 6/G+S6)G#
#t is the responsibility of the J1=C driver to convert the data passed from the database as
S\: data types into java values.
*esult Set 3AS%S
SignatureF public inter(ace ,esultSet
The ,esultSet interface defines methods for accessing tables of data generated as the
result of executing a Statement. BesultSet column3ames may be accessed in any order
they are indexed and may be selected by either the name or the number (numbered from ,
to n+ of the column.
21%
,esultSet maintains the position of the current ro%$ starting %ith the first ro% of data
returned.
The ne:t() method moves to the next ro% of data.
Some of the fre<uently used methods in the ,esultSet interface areF
,. boolean ne:t() t5rows SZ;+:ception
ositions the BesultSet to the next ro%& BesultSet ro% position is intially the first
ro% of the resultset.
;. ,esultSetGetaHata getGetaHata() t5rows SZ;+:ception
Beturns an object that contains a description of the current result setF the number
of columns$ the type of each column$ and properties of the results.
*. void close() t5rows SZ;+:ception
3ormally a BesultSet is closed %hen another Statement is executed$ but it may be
desirable to release the resources earlier.
/s above in the CallableStatement$ the resulting data can be read through getType
methods.
$&le)
11pass a Luery to t5e statement object
,esultSet rs = stmte:ecuteZuery (!S+;+46 2-,0G Stock PO+,+
Luantity=8%)
11\et t5e results as t5eir "ava types
12 3ote t5at columns are inde:ed by an integer starting wit5 1 or by
t5e name o( column* as in !/tem/H% 21
Sytemoutprintln(!Stock replenis5ment list%)&
w5ile (rsne:t() )
{ systemoutprintln(!/tem/H= !FrsgetString(!/tem/H%))&
systemoutprintln(!3e:t s5ip date= % F rsgetHate(>))&
systemoutprintln(! !)&
'
Re5/tSet4etaData
J1=C provides interfaces to (,+ read data from a BesultSet object (;+ and also$ to allo%
the developer to determine %hat type of data %as returned.
21+
The BesultSetMeta1ata interface is similar to the 1atabaseMeta1ata interface in concept$
but is specific to current BesultSet BesultSetMeta1ata is useful in dynamically
determining the Meta1ata of a BesultSet returned from a stored procedure.
S$NDN9 AND *$%$VN9 LA*9$ DA-A %!(N'S
S\: :63Z./B=#3/B_ and :63Z./BC9/B data types can be of arbitary si?e. The
get=ytes(+ and getString(+ methods can read these types up to the limits imposed by the
driver. The limits can be read through the Statement getMaxGieldSi?e(+ method. Gor
larger bloc's of data$ the J1=C allo%s developers to use java.io. #nput streams to return
the data in chun's.
Streams must be read immediately follo%ing the <uery execution. Since they are
automatically closed at the next get of a BesultSet.
Sending large bloc's of data is also possible using java.io.6utputStream as parameters.
8hen a statement is executed the J1=C driver ma'es repeated calls to read and transmit
the data in the streams.
211