Java Notes
Java Notes
UNIT - 1
INTRODUCTION TO JAVA: Java and Java applications; Java Development Kit (JDK); Java is
interpreted, Byte Code, JVM; Object-oriented programming; Simple Java programs. Data types
and other tokens: Boolean variables, int, long, char, operators, arrays, white spaces, literals,
assigning values; Creating and destroying objects; Access specifiers. Operators and Expressions:
Arithmetic Operators, Bitwise operators, Relational operators, The Assignment Operator, The?
Operator; Operator Precedence; Logical expression; Type casting; Strings Control Statements:
Selection statements, iteration statements, Jump Statements.
6 Hours
UNIT - 2
CLASSES, INHERITANCE, EXCEPTIONS, APPLETS: Classes: Classes in Java; Declaring
a class; Class name; Super classes; Constructors; Creating instances of class; Inner classes.
Inheritance: Simple, multiple, and multilevel inheritance; Overriding, overloading. Exception
handling: Exception handling in Java. The Applet Class: Two types of Applets; Applet basics;
Applet Architecture; An Applet skeleton; Simple Applet display methods; Requesting repainting;
Using the Status Window; The HTML APPLET tag; Passing parameters to Applets;
getDocumentbase() and getCodebase(); ApletContext and showDocument(); The AudioClip
Interface; The AppletStub Interface; Output to the Console.
6 Hours
UNIT - 3
MULTI THREADED PROGRAMMING, EVENT HANDLING: Multi Threaded
Programming: What are threads? How to make the classes threadable; Extending threads;
Implementing runnable; Synchronization; Changing state of the thread; Bounded buffer
problems, read-write problem, producer-consumer problems. Event Handling: Two event
handling mechanisms; The delegation event model; Event classes; Sources of events; Event
listener interfaces; Using the delegation event model; Adapter classes; Inner classes.
7 Hours
UNIT - 4
SWINGS: Swings: The origins of Swing; Two key Swing features; Components and Containers;
The Swing Packages; A simple Swing Application; Create a Swing Applet; Jlabel and
PART - B
UNIT - 5
JAVA 2 ENTERPRISE EDITION OVERVIEW, DATABASE ACCESS: Overview of J2EE
and J2SE. The Concept of JDBC; JDBC Driver Types; JDBC Packages; A Brief Overview of the
JDBC process; Database Connection; Associating the JDBC/ODBC Bridge with the Database;
Statement Objects; ResultSet; Transaction Processing; Metadata, Data types; Exceptions.
6 Hours
UNIT - 6
SERVLETS: Background; The Life Cycle of a Servlet; Using Tomcat for Servlet Development;
A simple Servlet; The Servlet API; The Javax.servlet Package; Reading Servlet Parameter; The
Javax.servlet.http package; Handling HTTP Requests and Responses; Using Cookies; Session
Tracking.
7 Hours
UNIT - 7
JSP, RMI: Java Server Pages (JSP): JSP, JSP Tags, Tomcat, Request String, User Sessions,
Cookies, Session Objects. Java Remote Method Invocation: Remote Method Invocation concept;
Server side, Client side.
6 Hours
UNIT - 8
ENTERPRISE JAVA BEANS: Enterprise java Beans; Deployment Descriptors; Session Java
Bean, Entity Java Bean; Message-Driven Bean; The JAR File.
7 Hours
TEXT BOOKS:
1. Java - The Complete Reference Herbert Schildt, 7th Edition, Tata McGraw Hill,
2007.
2. J2EE - The Complete Reference Jim Keogh, Tata McGraw Hill, 2007.
REFERENCE BOOKS:
1. Introduction to JAVA Programming Y. Daniel Liang, 6th Edition, Pearson
Education, 2007.
2. The J2EE Tutorial Stephanie Bodoff et al, 2nd Edition, Pearson Education, 2004.
UNIT Page
No. Table of Contents No.
Java and Java applications; Java Development Kit (JDK); Java is interpreted,
1
Byte Code.
Data types and other tokens: Boolean variables, int, long, char, operators, arrays,
3
white spaces, literals,
The Applet Class: Two types of Applets; Applet basics; Applet Architecture; An
20
Applet skeleton; Simple Applet display method
Requesting repainting; Using the Status Window; The HTML APPLET tag;
22
Passing parameters to Applets; getDocumentbase() and getCodebase()
Multi Threaded Programming: What are threads? How to make the classes
29
threadable;
4 SWINGS 42-49
50
Overview of J2EE and J2SE.
The Concept of JDBC; JDBC Driver Types; JDBC Packages 50
6 SERVLETS 54-60
Background 54
The Life Cycle of a Servlet; Using Tomcat for Servlet Development; A simple
54
Servlet
Using Cookies 58
Session Tracking. 59
Server side 65
Client side. 65
KSIMC 65
Deployment Descriptors 67
UNIT-1
INTRODUCTION TO JAVA
Java and Java applications; Java Development Kit (JDK); Java is interpreted, Byte Code, JVM;
Objectoriented programming; Simple Java programs.
arrays, white spaces, literals, assigning values; Creating and destroying objects; Access specifiers.
Bitwise operators, Relational operators, The Assignment Operator, The? Operator; Operator
Precedence; Logical expression; Type casting; Strings Control Statements: Selection statements,
iteration statements, Jump Statements.
x Java language was designed to be small, simple, and portable across platforms and
operating systems, both at the source and at the binary level (more about this later).
x Java also provides for portable programming with applets. Applets appear in a Web
page much in the same way as images do, but unlike images, applets are dynamic and
interactive.
x Applets can be used to create animations, figures, or areas that can respond to input
from the reader, games, or other interactive effects on the same Web pages among the
text and graphics.
x Platform independence is one of the most significant advantages that Java has over other
programming languages, particularly for systems that need to work on many different
platforms.
x Bytecodes are a set of instructions that look a lot like machine code, but are not specific to
any one processor
x Platform-independence doesn't stop at the source level, however. Java binary files are also
platform-independent and can run on multiple platforms without the need to recompile the
source. Java binary files are actually in a form called bytecodes.
x Many of Java's object-oriented concepts are inherited from C++, the language on which it
is based, but it borrows many concepts from other object-oriented languages as well.
x Java includes a set of class libraries that provide basic data types, system input and output
capabilities, and other utility functions.
x T h e s e b a s i c c l a s s e s a r e p a r t o f t h e J a v a d e ve l o p m e n t k i t , w h i c h a l s o h a s c l a s s e s t o
s u p p o r t n e t w o r k i n g, c o m m o n I n t e r n e t p r o t o c o l s , a n d u s e r i n t e r f a c e t o o l k i t f u n c t i o n s .
x B e c a u s e t h e s e c l a s s l i b r a r i e s a r e w r i t t e n i n J a va , t h e y a r e p o r t a b l e a c r o s s p l a t f o r m s a s
a ll Ja va a ppl ic a tio ns a re .
c la s s He l loW o r ld {
p u b l i c s t a t i c vo i d m a i n ( S t r i n g a r gs [ ] ) {
S y s t e m . o u t . p r i n t l n (" H e l l o W o r l d ! " ) ;
}
}
T hi s p ro gra m ha s tw o ma i n pa rts :
x T h e b o d y o f t h e p r o g r a m ( h e r e , j u s t t h e o n e l i n e ) i s c o n t a i n e d i n a m e t h o d (f u n c t i o n )
c a l l e d m a i n ( ) . I n J a va a p p l i c a t i o n s , a s i n a C o r C + + p r o g r a m , m a i n ( ) i s t h e f i r s t m e t h o d
( f u nc ti on ) tha t i s ru n whe n the p ro gr a m is e xe c u te d.
x I n S u n ' s J D K, t h e J a va c o m p i l e r i s c a l l e d j a va c .
javac HelloWorld.java
j a va H e l l o W o r l d
If the program was typed and compiled correctly, the output will be :
x V a r i a b l e s a r e l o c a t i o n s i n m e m o r y i n w h i c h va l u e s c a n b e s t o r e d . T h e y h a ve a n a m e ,
a t y p e , a n d a va l u e .
x Ja va ha s th re e ki nd s of va ria ble s : in sta nc e va r ia b le s, c la ss va r ia ble s, a n d loc a l
va ria ble s.
x I n s t a n c e va r i a b l e s , a r e u s e d t o d e f i n e a t t r i b u t e s o r t h e s t a t e f o r a p a r t i c u l a r o b j e c t.
C l a s s va r i a b l e s a r e s i m i l a r t o i n s t a n c e va r i a b l e s , e x c e p t t h e i r va l u e s a p p l y t o a l l t h a t
c l a s s ' s i n s t a n c e s ( a n d t o t h e c l a s s i t s e l f ) r a t h e r t h a n h a v i n g d i f f e r e n t va l u e s f o r e a c h
o bj ect.
x L o c a l va r i a b l e s a r e d e c l a r e d a n d u s e d i n s i d e m e t h o d d e f i n i t i o n s ,
for example, for index counters in loops, as temporary variables, or to hold values t hat
yo u ne e d on l y in si de the me th od de f i nit io n itse lf
V a ri a b l e d e c l a ra t i o n s c o n s i s t o f a t y p e a n d a v a ri a b l e n a m e :
E xa m ple s :
int myAge;
String myName;
boolean isTired;
b yte 8 bi ts 12 8 to 1 27
s ho r t 16 bi ts 32, 7 68 to 32, 7 67
1. 2.2 Floating-point
T h i s i s u s e d f o r n u m b e r s w i t h a d e c i m a l p a rt . J a v a f l o a t i n g - p o i n t n u m b e r s a re c o m p l i a n t
w it h IE EE 7 54 (a n in te r na ti ona l sta nda r d f o r de f ini n g f loa t in g-p oi nt num be rs a nd
a rit hme t ic ).
T h e r e a re t w o f l o a t i n g -p o i n t t y p e s : f l o a t (3 2 b i t s , s i n g l e -p re c i s i o n ) a n d d o u b l e ( 6 4 b i t s ,
d o uble - pre c i si on ).
1. 2.3 Char
T h e c h a r t y p e i s u s e d f o r i n d i v i d u a l c h a ra c t e r s . B e c a u s e J a v a u s e s t h e U n i c o d e c h a ra c t e r
se t, the c ha r t ype ha s 16 bi ts of p re c isi on, un si gne d.
1. 2.4 Boolean
T h e b o o l e a n t y p e c a n h a ve o n e o f t w o v a l u e s , t r u e o r f a l s e . N o t e t h a t u n l i k e i n o t h e r C -
l i k e l a n g u a g e s , b o o l e a n i s n o t a n u m b e r, n o r c a n i t b e t re a t e d a s o n e . A l l t e s t s o f B o o l e a n
va ria ble s s ho ul d te st f o r t rue o r f a lse .
1. 2.5 Literals
Li t e ra l s a re u s e d t o i n d i c a t e s i m p l e v a l u e s i n y o u r J a v a p ro g r a m s .
N u m b e r Li t e r a l s
x T h e r e a r e s e ve r a l i n t e ge r l i t e r a l s . 4 , f o r e x a m p l e , i s a d e c i m a l i n t e ge r l i t e r a l o f t y p e
i nt
x A d e c i m a l i n t e ge r l i t e r a l l a r ge r t h a n a n i n t i s a u t o m a t i c a l l y o f t y p e l o n g.
x F l oa ti n g- poi nt lite ra ls us ua ll y ha ve t wo pa r ts: the inte ge r pa rt a n d t he de c ima l pa r t
f o r exam ple, 5. 677 77 7.
B o o l e a n Li t e r a l s
B o o l e a n l i t e ra l s c o n s i s t o f t h e k e y w o r d s t r u e a n d f a l s e . T h e s e k e y w o r d s c a n b e u s e d
a n y w h e r e n e e d e d a t e s t o r a s t h e o n l y p o s s i b l e v a l u e s f o r b o o l e a n va r i a b l e s .
1 . 2 . 6 C ha r a c te r L i te r a l s
O p e ra t o rs i n J a v a i n c l u d e a ri t h m e t i c , v a ri o u s f o r m s o f a s s i g n m e n t , i n c r e m e n t a n d
de c re me nt, a nd lo gic a l o pe ra ti on s.
J a v a h a s f i ve o p e r a t o r s f o r b a s i c a r i t h m e t i c
Operator Ex am
Meaning ple
+ A d dit io n 3+4
S u bt ra c t io n 5
* M ul tip licati on 57* 5
/ D i vi s i o n 14 / 7
% Modul us 20 % 7
c l as s Ari t hm et i c Te s t {
Expression Meaning
x += y x=x+y
x = y x = x y
x *= y x=x*y
x = x / y x /= y
x + + i n c r e m e n t s t h e va l u e o f x b y 1 j u s t a s i f yo u h a d u s e d t h e e x p r e s s i o n x = x + 1 .
Si m i l a rl y x -- d e c re m e n t s t h e va l u e o f x b y 1 .
Ex e rc i se : wri t e t h e d if fe re nce b e t we e n :
y = x++;
y = ++x;
Comparison operators.
== Equal x == 3
!= N o t equal x
< Le ss t ha n !x=<
> G re a te r t ha n 3
3x>
<= Le ss tha n or e q ua l x 3
to <=
>= Grea ter tha n o r e qua l t o x3 >= 3 Logical
Operators
x E x p r e s s i o n s t h a t r e s u l t i n b o o l e a n va l u e s ( f o r e x a m p l e , t h e c o m p a r i s o n o p e r a t o r s ) c a n
be c o mbi ne d b y usi n g lo gic a l o pe ra to rs t ha t re p re se nt t he lo gic a l c omb ina t io ns
x A N D, OR, X OR, a nd logi c a l N OT.
x F o r A ND c o mb ina ti o ns, use e it he r t he & o r &&. T he e xp re s sio n w ill be t rue onl y if
b ot h e xp re s si ons a re a lso t r ue
x F o r O R e x p r e s s i o n s , u s e e i t h e r | o r | |. O R e x p r e s s i o n s r e s u l t i n t r u e i f e i t h e r o r b o t h o f
t he ope ra n ds is a l so t rue
x I n a d dit io n, the re is the X OR o pe ra t o r ^, w hic h re tu r ns t rue o nl y if i ts o pe ra nd s a re
d i f f e re n t ( o n e t r u e a n d o n e f a l s e , o r v i c e v e rs a ) a n d f a l s e o t h e r wi s e ( e v e n i f b o t h a re
t r ue ).
x I n ge n e r a l , o n l y t h e & & a n d | | a r e c o m m o n l y u s e d a s a c t u a l l o g i c a l c o m b i n a t i o n s . & , |,
a n d ^ a re mo re c omm onl y use d f or b it wise lo gic a l o pe ra t io ns.
x F o r N O T , u s e t h e ! o p e r a t o r w i t h a s i n gl e e x p r e s s i o n a r g u m e n t . T h e va l u e o f t h e N O T
e x p r e s s i o n i s t h e n e ga t i o n o f t h e e x p r e s s i o n ; i f x i s t r u e , ! x i s f a l s e .
Bitwise Operators
Operator Meaning
& Bi t wise A N D
| Bi t wise O R
^ Bi t wise X OR
<< Le f t shif t
>> Ri gh t shif t
~ Bi t wise c om ple me nt
x |= y O R a ssi gn me nt (x + x | y)
O p e ra t o r p re c e d e n c e d e t e rm i n e s t h e o r d e r i n w h i c h e x p r e s s i o n s a re e v a l u a t e d . T h i s , i n
s ome c a se s, c a n de te rm ine the o ve ra ll va lue o f the e xp re s si on. F or e xa mp le , ta ke the
f o llo wi n g e x p re ss io n:
y=6+4/2
D e p e n d i n g o n w h e t h e r t h e 6 + 4 e x p re s s i o n o r t h e 4 / 2 e x p re s s i o n i s e v a l u a t e d f i r s t , t h e
v a l u e o f y c a n e n d u p b e i n g 5 o r 8 . I n g e n e r a l , i n c r e m e n t a n d d e c r e m e n t a r e e va l u a t e d
b e f o r e a r i t h m e t i c , a r i t h m e t i c e x p r e s s i o n s a r e e va l u a t e d b e f o r e c o m p a r i s o n s , a n d
c o m p a r i s o n s a r e e va l u a t e d b e f o r e l o g i c a l e x p r e s s i o n s . A s s i g n m e n t e x p r e s s i o n s a r e
e va l u a t e d l a s t .
1.4 Arrays
A r r a y s i n J a v a a re a c t u a l o b j e c t s t h a t c a n b e p a s s e d a r o u n d a n d t re a t e d j u s t l i k e o t h e r
o bj ects.
A r r a y s a r e a w a y t o s t o r e a l i s t o f i t e m s . E a c h s l o t o f t h e a r r a y h o l d s a n i n d i vi d u a l
e le me nt, a nd yo u c a n pl a c e e le me n ts in t o o r c h a n ge the c o nte nt s o r th o se sl ot s a s yo u
ne e d to.
T h re e ste p s to c re a te a n a r ra y:
1. D e c l a r e a va r i a b l e t o h o l d t h e a r r a y.
2. C r e a t e a n e w a r r a y o b j e c t a n d a s s i g n i t t o t h e a r r a y va r i a b l e .
E . g.
St ri n g[ ] n a m e s ;
names = new String[10];
n a me s [ 1 ] = n1 ;
n a m e s [ 2] = n2;
...
Java does not support multidimensional arrays. However, you can declare and create an
a r r a y o f a r r a y s ( a n d t h o s e a r r a y s c a n c o n t a i n a r r a ys , a n d s o o n , f o r h o w e v e r m a n y
d i m e n s i o n s yo u n e e d ) , a n d a c c e s s t h e m a s y o u w o u l d C - s t y l e m u l t i d i m e n s i o n a l a r r a y s :
i n t c o o r d s [ ] [ ] = n e w i nt [ 1 2 ] [ 1 2 ] ;
c oord s[ 0] [ 0] = 1; c oords[ 0] [ 1] = 2;
1. 5.1 if Conditionals
A n o p t i o n a l e l s e k e y w o r d p r o vi d e s t h e s t a t e m e n t t o e x e c u t e i f t h e t e s t i s f a l s e :
if ( x < y)
A n a l t e r n a t i v e t o u s i n g t h e i f a n d e l s e k e y w o rd s i n a c o n d i t i o n a l s t a t e m e n t i s t o u s e t h e
c o nd iti ona l o pe ra to r, some t ime s c a lle d the te r na r y o pe ra to r.
T h e t e s t i s a n e x p re s s i o n t h a t re t u r n s t r u e o r f a l s e , j u s t l i k e t h e t e s t i n t h e i f s t a t e m e n t . If
t h e t e s t i s t r u e , t h e c o n d i t i o n a l o p e r a t o r r e t u r n s t h e va l u e o f t r u e r e s u l t ; i f i t ' s f a l s e , i t
r e t u r n s t h e v a l u e o f f a l s e r e s u l t . Fo r e x a m p l e , t h e f o l l o w i n g c o n d i t i o n a l t e s t s t h e v a l u e s o f
x and y, returns the smaller of t he two, and as sign s t hat val ue to the va ria ble smal ler:
i n t s m a l l e r = x < y ? x : y;
T h e c o n d i t i o n a l o p e r a t o r h a s a ve r y l o w p r e c e d e n c e ; t h a t i s , i t ' s u s u a l l y e v a l u a t e d o n l y
after all its subexpressions are evaluated. The only operators lower in precedence are the
a s si gnme nt o pe ra t o rs. .
T h i s i s t h e s w i t c h o r c a s e s t a t e m e n t ; i n J a va i t ' s s w i t c h a n d b e h a ve s a s i t d o e s i n C :
switch (test) { c a se
va l ue One :
resultOne;
break;
c a se va l ue Two:
resultTwo;
break;
c a se va l u e T h re e :
resultThree;
break; . . .
In the switch statement, the test (a primitive type of byte, char, short, or int) is compared
w i t h e a c h o f t h e c a s e v a l u e s i n t u rn . If a m a t c h i s f o u n d , t h e s t a t e m e n t , o r s t a t e m e n t s a f t e r
t h e t e s t i s e x e c u t e d . If n o m a t c h i s f o u n d , t h e d e f a u l t s t a t e m e n t i s e x e c u t e d . Th e d e f a u l t i s
o pt io na l, s o if t he re is n' t a ma tc h i n a n y of the c a se s a nd de f a ult d oe sn 't e x ist, the s witc h
s t a t e m e n t c o m p l e t e s w i t h o u t d o i n g a n y t h i n g.
T h e f o r l o o p i n J a va l o o k s r o u g h l y l i k e t h i s :
f o r ( i n i ti a l i z a t i o n ; te s t ; i n c re me n t ) { s t a t e m e n t s ;
x I n i t i a l i z a t i o n i s a n e x p r e s s i o n t h a t i n i t i a l i z e s t h e s t a r t o f t h e l o o p . I f yo u h a ve a l o op
i n d e x , t h i s e x p re s s i o n m i g h t d e c l a re a n d i n i t i a l i ze i t , f o r e x a m p l e , i n t i = 0 . V a ri a b l e s t h a t
y o u d e c l a re i n t h i s p a r t o f t h e f o r l o o p a re l o c a l t o t h e l o o p i t s e l f ; t h e y c e a s e e x i s t i n g a f t e r
t h e l o o p i s f i n i s h e d e x e c u t i n g. T e s t i s t h e t e s t t h a t o c c u r s a f t e r e a c h p a s s o f t h e l o o p .
T h e t e s t m u s t b e a b o o l e a n e x p r e s s i o n o r f u n c t i o n t h a t r e t u r n s a b o o l e a n va l u e , f o r
e x a m p l e , i < 1 0 . If t h e t e s t i s t r u e , t h e l o o p e x e c u t e s . O n c e t h e t e s t i s f a l s e , t h e l o o p
s to ps e xe c u tin g
I n c r e m e n t i s a n y e x p r e s s i o n o r f u n c t i o n c a l l . C o m m o n l y, t h e i n c r e m e n t i s u s e d t o
c ha n ge t he va l ue of t he l o o p in de x to b r i n g t he s t a te of t he lo o p c lo se r t o r e t u r ni n g f a l s e
a n d c o m p l e t i n g.
F i n a l l y , t h e re a re w h i l e a n d d o l o o p s . wh i l e a n d d o l o o p s , l i k e f o r l o o p s , e n a b l e a b l o c k o f
Ja va c o de t o be e xe c ute d re pe a te d l y un til a spe c if ic c on dit io n is me t. W he the r you u se a
f o r l o o p , a w h i l e , o r a d o i s m o s t l y a m a t t e r o f y o u r p r o g r a m m i n g s t y l e . w hile a n d d o
l o o p , a re e x a c t l y t h e s a m e a s i n C a n d C + + e x c e p t t h e i r t e s t c o n d i t i o n m u s t b e a b o o l e a n .
T h e w h i l e l o o p i s u s e d t o r e p e a t a s t a t e m e n t o r b l o c k o f s t a t e m e n t s a s l o n g a s a p a rt i c u l a r
c o nd iti on is t r ue . w hile l oo ps l oo k like th is:
w h i l e (c o n d i t i o n ) {
b o d yOf Loo p; }
T h e c o n d i t i o n i s a b o o l e a n e x p re s s i o n . If i t re t u r n s t ru e , t h e w h i l e l o o p e x e c u t e s t h e
s t a t e m e n t s i n b o d y O f L o o p a n d t h e n t e s t s t h e c o n d i t i o n a ga i n , r e p e a t i n g u n t i l t h e
c o nd iti on is f alse :
i nt c ou nt = 0;
The do loop is j ust like a while loop, except that do executes a given statement or block
u nt il the c on di tio n is f a lse . The ma i n dif f e re nc e is t ha t wh ile lo op s te st t he c on diti on
b e f o r e l o o p i n g, m a k i n g i t p o s s i b l e t h a t t h e b o d y o f t h e l o o p w i l l n e v e r e x e c u t e i f t h e
c on d iti o n is f a lse t he f ir s t t ime i t' s te ste d. do lo o p s r u n the bo d y of t he l oo p a t le a st on c e
be f o re te sti n g the c o ndit io n. do loo ps l oo k like t his :
do {
b o d yOf Loo p;
} wh ile ( c o n d i t i o n ) ;
i nt x = 1 ;
do {
} wh ile ( x < = 10 );
L o o p i n g, r o u n d 1 L o o p i n g, r o u n d 2 L o o p i n g, r o u n d 3 L o o p i n g, r o u n d 4 L o o p i n g, r o u n d 5
L o o p i n g, r o u n d 6
L o o p i n g, r o u n d Lo o p i n g, r o u n d Lo o p i n g, r o u n d L o o p i n g , r o u n d
x Classes:
Classes in Java; Declaring a class; Class name; Super classes; Constructors; Creating instances of
class; Inner classes. Inheritance: Simple, multiple, and multilevel inheritance; Overriding,
overloading.
basics; Applet Architecture; An Applet skeleton; Simple Applet display methods; Requesting
repainting; Using the Status Window; The HTML APPLET tag; Passing parameters to Applets;
getDocumentbase() and getCodebase(); ApletContext and showDocument(); The AudioClip
Interface; The AppletStub Interface; Output to the Console.
x To define a class, use the class keyword and the name of the class:
class MyClassName {
... }
x If this class is a subclass of another class, use extends to indicate the superclass of this
class:
...
x If this class implements a specific interface, use implements to refer to that interface: class
MyRunnableClassName implements Runnable {
...
Super Classes
x Each class has a superclass (the class above it in the hierarchy), and each class can have one
or more subclasses (classes below that class in the hierarchy). Classes further down in the
hierarchy are said to inherit from classes further up in the hierarchy.
x Subclasses inherit all the methods and variables from their superclassesthat is, in any
particular class, if the superclass defines behavior that your class needs, you don't have to
redefine it or copy that code from some other class. Your class automatically gets that
behavior from its superclass, that superclass gets behavior from its superclass, and so on all
the way up the hierarchy.
x At the top of the Java class hierarchy is the class Object; all classes inherit from this one
superclass. Object is the most general class in the hierarchy; it defines behavior inherited by
all the classes in the Java class hierarchy. Each class farther down in the hierarchy adds more
information and becomes more tailored to a specific purpose.
E.g.
The following example demonstrates the creation of classes, creating objects and the usage of
constructors
class Motorcycle { }
void startEngine() {
if (engineState == true)
void startEngine() {
The showAttesnm gientehSotdatp e rints t=he currtreunet ;values of the instance variables in an instance of your
Motorcycle cSlayssste. m
H.eoruet's.pw
rihnatltni(t"lTohoeks}like:
void showAt}ts() {
System. out .println ("This motorcycle is a " + color + " " + make);
if (engineState == true)
The showAtts method prints two lines to the screen: the make and color of the motorcycle
object, and whether or not the engine is on or off.
public static void main (String args[]) { Motorcycle m = new Motorcycle(); m.make = "Yamaha
RZ350";
m.color = "yellow";
"); System.out.println("Starting
engine..."); m.startEngine();
System.out.println("");
"); System.out.println("Starting
engine..."); m.startEngine();
With the main() method, the Motorcycle class is now an application, and you can compile it
again and this time it'll run. Here's how the output should look:
Calling showAtts...
Calling showAtts...
Starting engine...
2.3. Inheritance
Inheritance is a powerful mechanism that means when you write a class you only have to
specify how that class is different from some other class; inheritance will give you automatic
access to the information contained in that other class.
With inheritance, all classesthose you write, those from other class libraries that you use, and
those from the standard utility classes as wellare arranged in a strict hierarchy
Single inheritance means that each Java class can have only one superclass (although any given
superclass can have multiple subclasses).
In other object-oriented programming languages, such as C++, classes can have more than one
superclass, and they inherit combined variables and methods from all those classes. This is
called multiple inheritance.
Multiple inheritance can provide enormous power in terms of being able to create classes that
factor just about all imaginable behavior, but it can also significantly complicate class
definitions and the code to produce them. Java makes inheritance simpler by being only
singly inherited.
x When a method is called on an object, Java looks for that method definition in the class of
that object, and if it doesn't find one, it passes the method call up the class hierarchy until a
method definition is found.
x Method inheritance enables you to define and use methods repeatedly in subclasses without
having to duplicate the code itself.
x However, there may be times when you want an object to respond to the same methods but
have different behavior when that method is called. In this case, you can override that
method. Overriding a method involves defining a method in a subclass that has the same
signature as a method in a superclass. Then, when that method is called, the method in the
subclass is found and executed instead of the one in the superclass.
To override a method, all you have to do is create a method in your subclass that has the same
signature (name, return type, and parameter list) as a method defined by one of your class's
superclasses. Because Java executes the first method definition it finds that matches the
signature, this effectively "hides" the original method definition. Here's a simple example
class PrintClass {
int x = 0; int y = 1;
void printMe() {
this.getClass().getName());
public static void main(String args[]) { PrintSubClass obj = new PrintSubClass(); obj
.printMe();
X is 0, Y is 1
In the main() method of PrintSubClass, you create a PrintSubClass object and call the printMe()
method. Note that PrintSubClass doesn't define this method, so Java looks for it in each of
PrintSubClass's superclassesand finds it, in this case, in PrintClass. because printMe() is still
defined in PrintClass, it doesn't print the z instance variable.
To call the original method from inside a method definition, use the super keyword to pass the
method call up the hierarchy:
super.myMethod(a, b);
The super keyword, somewhat like the this keyword, is a placeholder for this class's superclass.
You can use it anywhere you can use this, but to refer to the superclass rather than to the current
class.
An exception is an event that occurs during the execution of a program that disrupts the normal
flow of instructions.
x Checked exceptions are subject to the Catch or Specify Requirement. All exceptions are
checked exceptions, except for those indicated by Error, RuntimeException, and their
subclasses.
x Errors are not subject to the Catch or Specify Requirement. Errors are those exceptions
indicated by Error and its subclasses.
x Runtime exceptions are not subject to the Catch or Specify Requirement. Runtime
exceptions are those indicated by Runtime Except ion and its subclasses.
Valid Java programming language code must honor the Catch or Specify Requirement. This
means that code that might throw certain exceptions must be enclosed by either of the
following:
A try statement that catches the exception. The try must provide a handler for the exception,
as described in Catching and Handling Exceptions.
A method that specifies that it can throw the exception. The method must provide a throws
clause that lists the exception, as described in Specifying the Exceptions Thrown by a Method.
Code that fails to honor the Catch or Specify Requirement will not compile.
This example describes how to use the three exception handler components the try, cat ch,
and finally blocks
The first step in constructing an exception handler is to enclose the code that might throw an
exception within a try block. In general, a try block looks like the following.
try {
code
Example :
try {
You associate exception handlers with a try block by providing one or more catch blocks
directly after the try block. No code can be between the end of the try block and the beginning
of the first catch block.
try {
Each catch block is an exception handler and handles the type of exception indicated by its
argument
finally block
The runtime system always executes the statements within the finally block regardless of what
happens within the try block. So it's the perfect place to perform cleanup.
The following finally block for the write Li st method cleans up and then closes the PrintWriter.
finally {
if (out != null) {
} else {
Applet Basics
x An applet is a special kind of Java program that a browser enabled with Java technology can
download from the internet and run.
x An applet is typically embedded inside a web-page and runs in the context of the browser.
x An applet must be a subclass of the java.applet.Applet class, which provides the standard
interface between the applet and the browser environment.
x Simple example :
An applet can be included in an HTML page, much in the same way an image is included in a
page.
When Java technology enabled Browser is used to view a page that contains an applet, the
applet's code is transferred to your system and executed by the browser's Java Virtual Machine
(JVM)
1 .Local applet - operate in single machine browser which is not connected in network,
2.Remote applet - remote applet operate over internet via network.
Applet Architecture
Event driven :
The AWT notifies the applet about an event by calling event handler that has been provided by
the applet.
The applet takes appropriate action and then quickly return control to AWT All Swing
components descend from the AWT Container class
User initiates interaction with an Applet (and not the other way around) An Applet Skeleton
import java.awt.*;
import javax.swing.*;
/*
</applet>
*/
// initialization
/* Called second, after init(). Also called whenever the applet is restarted. */
SJBIT, Dept. of ISE Page 21
Java and J2EE (06IS753)
// suspends execution
method executed. */
Requesting Repainting
repaint( ) function is called when you have changed something and want your changes to show
up on the screen
paint(g);
Parameters:
Many browsers and applet viewers provide such a window, where the application can inform
users of its current state.
Example :
panel.add(showStatus);
browser = getAppletContext(); }
if (e.target == showStatus)
x The APPLET tag is used to start an applet from both an HTML document and from an
applet viewer.
x An applet viewer will execute each APPLET tag that it finds in a separate window,while
web browsers like Netscape Navigator, Internet Explorer, and HotJava will allow many
applets on a single page.
x The syntax for the standard APPLET tag is shown here. Bracketed items are optional.
< APPLET
[CODEBASE = codebaseURL]
CODE = appletFile
[ALT = alte rnate Text]
[NAME = appletInstanceName]
WIDTH = pixels HEIGHT = pixels
[ALIGN = alignment]
[VSPACE = pixels] [HSPACE = pixels]
>
[< PARAM NAME = AttributeName VALUE = Attribute Value>] [< PARAM NAME =
AttributeName2 VALUE = Attribute Value>] . . .
[HTML Displayed in the absence of Java]
</APPLET>
x CODEBASE is an optional attribute that specifies the base URL of the applet code, which
is the directory that will be searched for the applets executable class file (specified by the
CODE tag). The HTML documents URL directory is used as the CODEBASE if this
attribute is not specified. The CODEBASE does not have to be on the host from which the
HTML document was read.
x CODE is a required attribute that gives the name of the file containing your applets
compiled .class file. This file is relative to the code base URL of the applet, which is the
directory that the HTML file was in or the directory indicated by CODEBASE if set.
x ALT is an optional attribute used to specify a short text message that should be displayed if
the browser understands the APPLET tag but cant currently run Java applets. This is
distinct from the alternate HTML you provide for browsers that dont support applets.
x WIDTH AND HEIGHT are required attributes that give the size (in pixels) of the applet
display area.
x ALIGN is an optional attribute that specifies the alignment of the applet. This attribute is
treated the same as the HTML IMG tag with these possible values:
VSPACE AND HSPACE These attributes are optional. VSPACE specifies the space, in
p i x e l s , a b o ve a n d b e l o w t h e a p p l e t . H S P A C E s p e c i f i e s t h e s p a c e , i n pi x e l s , o n e a c h
s i d e o f t h e a p p l e t . T h e y r e t r e a t e d t h e s a m e a s th e I M G t a g s V S P A C E a n d H S P A C E
att r ib utes.
PARAM NAME AND VALUE The PARAM ta g all o ws you to s pecify ap plet specific
a rgumen ts in an HTM L pa ge. Applet s access thei r att ri bute s wit h the getParameter( )
met ho d.
I n s i d e t h e a p p l e t , yo u r e a d t h e va l u e s p a s s e d t h r o u g h t h e P A R A M t a gs w i t h t h e
ge t Pa r a m e t e r ( ) me th od of t he j a va . a p p l e t . A p p l e t c la ss.
T h e a p p l e t p a r a m e t e r " M e s s a ge " i s t h e s t r i n g t o b e d r a w n .
import java.applet. *; im po rt
j a va . a w t . * ;
S t r i n g i n p u t F r o m P a ge = t h i s . ge t P a r a m e t e r ( " M e s s a g e " ) ;
i f ( i n p u t F r o m P a g e = = n u l l ) i n p u t F r o m P a g e = d e f a u l t M e s s a ge ;
g . d ra w St ri n g ( i n p u t F r o m Pa g e , 5 0 , 2 5 );
}
}
H T M L f i l e t h a t r e f e r e n c e s t h e a b o ve a p p l e t .
< / HE A D >
< B O DY >
<PARAM name="Message" value="Howdy, there!"> This page will be very boring if your
</APPLET>
</BODY> </HTML>
Returns:
the URL of the document that contains this applet.
Returns:
the base URL of the directory which contains this applet.
x Gets the base URL. This is the URL of the directory which contains this applet.
x Example segments:
URL codeBase = getCodeBase();
Image myImage = getImage(codeBase, "images/myimage.gif"); Applet Context and
showDocument()
AppletContext is an interface that provides the means to control the browser environment in
which the applet is running.
x The AudioC lip interface is a simple abstraction for playing a sound clip.
x Multiple Audi oC lip items can be playing at the same time, and the resulting sound is
mixed together to produce a composite.
play
public abstract void play()
Starts playing this audio clip. Each time this method is called, the
loop clip is restarted from the beginning.
stop public abstract void loop()
public abstract voSitdarsttsopp(la) ying this audio clip in a loop.
Stops playing this audio clip.
What are threads? How to make the classes threadable; Extending threads; Implementing
runnable; Synchronization; Changing state of the thread; Bounded buffer problems, read-write
problem, producer-consumer problems.
Event Handling:
Two event handling mechanisms; The delegation event model; Event classes; Sources of events;
Event listener interfaces; Using the delegation event model; Adapter classes; Inner classes.
x A Multithreaded program contains two or more parts that can run concurrently.
(1) implement the Runnable Interface and apply its run() method.
1. Implementing Runnable Interface: The easiest way to create a thread is to create a class
that implements the Runnable interface. To implement Runnable, a class need only
implement a single method called run().
2. Extending Thread: The second way to create a thread is to create a new class that extends
the Thread class and then to create an instance of this class. This class must override the
run() method which is the entry point for the new thread.
You can inherit the Thread class as another way to create a thread in your program. When
you declare an instance of your class, youll also have access to members of the Thread
class. Whenever your class inherits the Thread class, you must override the run() method,
which is an entry into the new thread. The following example shows how to inherit the
Thread class and how to override the run() method. This example defines the MyThread
class, which inherits the Thread class. The constructor of the MyThread class calls the
constructor of the Thread class by using the super keyword and passes it the name of the
new thread, which is My thread. It then calls the start() method to activate the new thread.
The start() method calls the run() method of the MyThread class
MyThread() {
super("My thread");
start();
}}
class Demo {
MyThread(); System.out.println("Main
thread started");
}}
The example in the next segment demonstrates the use of Runnable and its implementation.
Synchronization
1. Two or more threads accessing the same data simultaneously may lead to loss of data
integrity. In order to avoid this java uses the concept of monitor. A monitor is an object used as
a mutually exclusive lock.
2. At a time only one thread can access the Monitor. A second thread cannot enter the monitor
until the first comes out. Till such time the other thread is said to be waiting.
3. The keyword Synchronized is use in the code to enable synchronization and it can be used
along with a method.
There might be times when you need to temporarily stop a thread from processing and then
resume processing, such as when you want to let another thread use the current resource. You
can achieve this objective by defining your own suspend and resume methods, as shown in the
following example. This example defines a MyThread class. The MyThread class defines three
methods: the run() method, the suspendThread() method, and the resumeThread() method. In
addition, the MyThread class declares the instance variable suspended, whose value is used to
indicate whether or not the thread is suspended.
boolean suspended;
MyThread() {
t = new Thread(this, "Thread");
suspended = false ; t.start();
}
public void run() {
try {
for (int i = 0; i < 10; i++) { System.out.println("Thread: " + i ); Thread.sleep(200);
synchronized (this) {
while (suspended) {
wait();
}
}
}
} catch (InterruptedException e ) { System.out.println("Thread: interrupted."); }
System.out.println("Thread exiting.");
}
void suspendThread() { suspended = true;
suspended = false;
notify();
class Demo {
try{
} catch ( InterruptedException e) {
try {
t1.t.join();
Problem Description :
The producer's job is to generate a piece of data, put it into the buffer and start again. At the
same time the consumer is consuming the data (i.e. removing it from the buffer) one piece at a
time. The problem is to make sure that the producer won't try to add data into the buffer if it's
full and that the consumer won't try to remove data from an empty buffer. This is the code for
solving the above stated:
class BufferItem {
public volatile double value = 0; // multiple threads access public volatile boolean occupied =
false; // so make these `volatile' }
class BoundedBuffer { // designed for a single producer thread and // a single consumer thread
double value;
value = buffer[takeOut].value; // C
Read-Write problem
x Many threads can acquire the same read/write lock if they acquire a shared read lock on the
read/write lock object.
x Only one thread can acquire an exclusive write lock on a read/write lock object.
x When an exclusive write lock is held, no other threads are allowed to hold any lock.
wait();
readers++;
SJBIT, Dept. of ISE Page 34
Java and J2EE (06IS753)
notifyAll();
writeRequests++;
writeRequests--;
writers++;
notifyAll();
Producer-Consumer problems
x Examples are a message sender and a message receiver, or two machines working on items
in sequence.
x The synchronization here must ensure that the consumer process does not consume more
items than have been produced. If necessary, the consumer process is blocked (must wait)
if no item is available to be consumed.
x The buffer can be bounded (have a capacity limit) or unbounded (be able to store an
unlimited number of items).
In Java, events represent all activity that goes on between the user and the application.
Delegation event model : It defines standard and consistent mechanisms to generate and
process events. Here the source generates an event and sends it to on or more listeners. The
listener simply waits until it receives an event. Once it is obtained, It processes this event and
returns. Listeners should register themselves with a source in order to receive an even
notification. Notifications are sent only to listeners that want to receive them.
Events
In the delegation model, an event is an object that describes a state change in a source. It can be
generated as a consequence of a person interacting with the elements in a graphical user
interface. Some of the activities that cause events to be generated are : pressing a button,
entering a character via the keyboard, selecting an item in a list, and clicking the mouse.
Events may also occur that are not directly caused by interactions with a user interface. For
example, an event may be generated when a timer expires, a counter exceeds a value, a
software or hardware failure occurs, or an operation is completed.
Event Classes
The classes that represent events are at the core of Javas event handling mechanism.
EventObject : It is at the root of the Java event class hierarchy in java.util. It is the superclass
for all events. Its one constructor is shown here: EventObject(Object src) Here, src is the
object that generates this event. EventObject contains two methods: getSource( ) and toString(
). The getSource( ) method returns the source of the event.
ActionEvent(Object src, int type, String cmd, long when, int modifiers) Here, src is a reference
to the object that generated this event. The type of the event is specified by type, and its
command string is cmd. The argument modifiers indicates which modifier keys (ALT, CTRL,
META, and/or SHIFT) were pressed when the event was generated. The when parameter
specifies when the event occurred
x The ItemEvent Class : An ItemEvent is generated when a check box or a list item
is clicked or when a checkable menu item is selected or deselected
x The TextEvent Class Instances of this class describe text events. These are
generated
by text fields and text areas when characters are entered by a user or program.
x The WindowEvent Class There are ten types of window events. The WindowEvent
Sources of Events
x Checkbox - Generates item events when the check box is selected or deselected.
x List - Generates action events when an item is double-clicked; generates item events
x Menu Item - Generates action events when a menu item is selected; generates item
x Text components - Generates text events when the user enters a character.
Listeners are created by implementing one or more of the interfaces defined by the
java.awt.event package.
When an event occurs, the event source invokes the appropriate method defined by the listener
and provides an event object as its argument.
Interface Description
FocusListener - Defines two methods to recognize when a component gains or loses keyboard
focus.
ItemListener - Defines one method to recognize when the state of an item changes.
KeyListener - Defines three methods to recognize when a key is pressed, released, or typed.
MouseListener - Defines five methods to recognize when the mouse is clicked, enters a
component, exits a component, is pressed, or is released.
MouseWheelListener - Defines one method to recognize when the mouse wheel is moved.
Applet programming using the delegation event model is done following these two steps:
1. Implement the appropriate interface in the listener so that it will receive the type of event
desired.
2. Implement code to register and unregister (if necessary) the listener as a recipient for the
event notifications.
Adapter Classes
x Adapter classes are useful when you want to receive and process only some of the events
that are handled by a particular event listener interface.
x New class to act as an event listener by extending one of the adapter classes and
implementing only those events in which you are interested.
x For example, the MouseMotionAdapter class has two methods, mouseDragged( ) and
mouseMoved( ). The signatures of these empty methods are exactly as defined in the
MouseMotionListener interface. If you were interested in only mouse drag events, then
you could simply extend MouseMotionAdapter and implement mouseDragged( ). The
empty implementation of mouseMoved( ) would handle the mouse motion events for you.
/*
</applet>
*/
addMouseListener(new MyMouseAdapter(this));
addMouseMotionListener(new MyMouseMotionAdapter(this));
}}
AdapterDemo adapterDemo;
SJBIT, Dept. of ISE Page 39
Java and J2EE (06IS753)
this.adapterDemo = adapterDemo;
adapterDemo.showStatus("Mouse clicked");
}}
AdapterDemo adapterDemo;
this.adapterDemo = adapterDemo;
adapterDemo.showStatus("Mouse dragged");
}}
Inner Classes
Consider the applet shown in the following listing. It does not use an inner class. Its goal is to
display the string
Mouse Pressed in the status bar of the applet viewer or browser when the mouse is pressed.
There are two top-level classes in this program. MousePressedDemo extends Applet, and
MyMouseAdapter extends MouseAdapter. The init( ) method of MousePressedDemo
instantiates MyMouseAdapter and provides this object as an argument to the
addMouseListener( ) method.
method.
import java.applet. *;
import java.awt.event.*;
/*
*/
addMouseListener(new MyMouseAdapter(this));
}}
UNIT-4: SWINGS
SWINGS:
JTextField;
JTabbedpane;
JScrollPane;
JList;
JComboBox;
JTable.
Swing is built on top of AWT and is entirely written in Java, using AWTs lightweight
component support. In particular, unlike AWT, t he architecture of Swing components makes it
easy to customize both their appearance and behavior. Components from AWT and Swing can be
mixed, allowing you to add Swing support to existing AWT-based programs. For example, swing
components such as JSlider, JButton and JCheckbox could be used in the same program with
standard AWT labels, textfields and scrollbars.
Swing components are basic building blocks of an application. Swing toolkit has a wide range
of various widgets. Buttons, check boxes,sliders, list boxes etc. Everything a programmer
needs for his job. In this section of the tutorial, we will describe several useful components.
JLabel Component
JLabel is a simple component for displaying text, images or both. It does not react to input
events.
JCheckBox
JCheckBox is a widget that has two states. On and Off. It is a box with a label JSlider
JSlider is a component that lets the user graphically select a value by sliding a knob within a
bounded interval
JComboBox
Combobox is a component that combines a button or editable field and a drop-down list. The
user can select a value from the drop-down list, which appears at the user's request.
JProgressBar
A progress bar is a widget that is used, when we process lengthy tasks. It is animated so that
the user knows, that our task is progressing
JToggleButton
JToggleButton is a button that has two states. Pressed and not pressed. You toggle between
these two states by clicking on it
Containers
Swing contains a number of components that provides for grouping other components together.
In AWT, such components extended java.awt.Container and included Panel, Window, Frame,
and Dialog.
JPanel is Swings version of the AWT class Panel and uses the same default layout,
FlowLayout. JPanel is descended directly from JComponent.
JFrame is Swings version of Frame and is descended directly from that class. The
components added to the frame are referred to as its contents; these are managed by the
contentPane. To add a component to a JFrame, we must use its contentPane instead.
JWindow is Swings version of Window and is descended directly from that class. Like
Window, it uses BorderLayout by default.
JDialog is Swings version of Dialog and is descended directly from that class. Like Dialog, it
uses BorderLayout by default. Like JFrame and JWindow,
JDialog contains a rootPane hierarchy including a contentPane, and it allows layered and glass
panes. All dialogs are modal, which means the current
thread is blocked until user interaction with it has been completed. JDialog class is intended as
the basis for creating custom dialogs; however, some
of the most common dialogs are provided through static methods in the class JOptionPane.
extends JComponent
x A label does not react to input events. As a result, it cannot get the keyboard focus.
x A label can display a keyboard alternative as a convenience for a nearby component that
has a keyboard alternative but can't display it.
x Text-only labels are leading edge aligned, by default; image-only labels are
Can use the setIconTextGap method to specify how many pixels should appear between the
text and the image. The default is 4 pixels.
ImageIcon
Syntax :
this(filename, filename);
Creates an ImageIcon from the specified file. The image will be preloaded by using
MediaTracker to monitor the loading state of the image.
The specified String can be a file name or a file path. When specifying a path, use the Internet-
standard forward-slash ("/") as a separator. (The string is converted to an URL, so the forward-
slash works on all systems.)
new ImageIcon("images/myImage.gif")
import javax.swing.Icon;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new
FlowLayout(FlowLayout.LEFT));
getContentPane().add(label1); getContentPane().add(label2);
}
SJBIT, Dept. of ISE Page 45
Java and J2EE (06IS753)
JTextField
x JTextField is a lightweight component that allows the editing of a single line of text.
java.awt.TextField class.
x JTextField has a method to establish the string used as the command string for the action
event that gets fired.
x The java.awt.TextField used the text of the field as the command string for the
ActionEvent.
x JTextField will use the command string set with the setActionCommand method if not null,
otherwise it will use the text of the field as a compatibility with java.awt.TextField.
1. Swing Package
Syntax :
package com.ack.gui.swing.simple;
import java.awt.*;
super( title );
System.exit( 0 );
} );
init();
setVisible( true );
jb.setToolTipText( i + ".gif" );
my_panel.add( jb );
getContentPane().add( my_panel );
my_panel.setBorder( BorderFactory.createEtchedBorder() );
JTabbedpane
extends JComponent
x A component that lets the user switch between a group of components by clicking on a tab
with a given title and/or icon.
x Tabs/components are added to a TabbedPane object by using the addTab and insertTab
methods.
x A tab is represented by an index corresponding to the position it was added in, where the
first tab has an index equal to 0 and the last tab has an index equal to the tab count minus
x The TabbedPane uses a Single SelectionModel to represent the set of tab indices and the
currently selected index. If the tab count is greater than 0, then there will always be a
selected index, which by default will be initialized to the first tab. If the tab count is 0, then
the selected index will be -1.
JScrollPane
extends JComponent
x A JScrollPane manages a viewport, optional vertical and horizontal scroll bars, and
optional row and column heading viewports.
x The JViewport provides a window, or "viewport" onto a data source -- for example, a text
file. That data source is the "scrollable client" (aka data model) displayed by the JViewport
view.
x A JScrollPane basically consists of JScrollBars, a JViewport, and the wiring between them,
as shown in the diagram at right.
JList
extends JComponent
A component that allows the user to select one or more objects from a list. A separate model,
ListModel, represents the contents of the list.
String[] data = {"one", "two", "three", "four"}; JList dataList = new JList(data);
JComboBox
extends JComponent
x The user can select a value from the drop-down list, which appears at the user's request.
x If you make the combo box editable, then the combo box includes an editable field into
which the user can type a value.
JTable
extends JComponent
The JTable is used to display and edit regular two-dimensional tables of cells.
The JTable has many facilities that make it possible to customize its rendering and
editing but provides defaults for these features so that simple tables can be set up
easily.
JDBC Packages; A Brief Overview of the JDBC process; Database Connection; Associating the
JDBC/ODBC Bridge with the Database; Statement Objects; ResultSet; Transaction Processing;
Metadata, Data types; Exceptions.
x The J2EE platform gives you a multitiered distributed application model, the
ability to reuse components, integrated XML-based data interchange, a unified
security model, and flexible transaction control.
x Vendors and customers enjoy the freedom to choose the products and components
that best meet their business and technological requirements.
x The JDBC ( Java Database Connectivity) API defines interfaces and classes for
x Using JDBC you can send SQL, PL/SQL statements to almost any relational
database. JDBC is a Java API for executing SQL statements and supports basic SQL
functionality.
x It provides RDBMS access by allowing you to embed SQL inside Java code.
Before you can create a java jdbc connection to the database, you must first import the java.sql
package.
import java.sql.*; The star ( * ) indicates that all of the classes in the package java.sql are to be
imported.
Java application calls the JDBC library. JDBC loads a driver which talks to the database. We
can change database engines without changing database code.
x In this step of the jdbc connection process, we load the driver class by calling Class.forName()
with the Driver class name as an argument. Once loaded, the Driver class creates an instance of
itself.
x A client can connect to Database Server through JDBC Driver. Since most of the Database
servers support ODBC driver therefore JDBC-ODBC Bridge driver is commonly used.
x The return type of the Class.forName (String ClassName) method is Class. Class is a class in
java.lang package.
catch(Exception x) {
The JDBC DriverManager class defines objects which can connect Java applications to a JDBC
driver. DriverManager is considered the backbone of JDBC architecture. DriverManager class
manages the JDBC drivers that are installed on the system.
a username, password, and a jdbc url to establish a connection to the database and
x A Connection object provides metadata i.e. information about the database, tables, and
fields. It also contains methods to deal with transactions.
Each subprotocol has its own syntax for the source. Were using the jdbc odbc subprotocol, so
the DriverManager knows to use the sun.jdbc.odbc.JdbcOdbcDriver.
try{
catch( SQLException x ){
Connection interface defines methods for interacting with the database via the established
connection.
x To execute SQL statements, you need to instantiate a Statement object from your connection
object by using the createStatement() method.
Statement createStatement()
x Prepared Statement: Execute precompiled sql queries with or without parameters. Prep
aredS tatement prepare Statement(String sql)
returns a new PreparedStatement object. Prep aredStatement objects are precompiled SQL
statements.
returns a new CallableStatement object. CallableStatement objects are SQL stored procedure
call statements.
5.4. Executing a SQL statement with the Statement object, and returning a jdbc resultSet.
x Statement interface defines methods that are used to interact with database via the
execution of SQL statements.
x For statements that create or modify tables, the method to use is executeUpdate. Note:
Statements that create a table, alter a table, or drop a table are all examples of DDL
statements and are executed with the method executeUpdate. execute() executes an SQL
statement that is written as String object.
ResultSet provides access to a table of data generated by executing a Statement. The table rows
are retrieved in sequence. A ResultSet maintains a cursor pointing to its current row of data.
The next() method is used to successively step through the rows of the tabular results.
ResultSetMetaData Interface holds information on the types and properties of the columns in a
ResultSet. It is constructed from the Connection object.
Servlet Development;
Background
Definition : Servlets are modules of Java code that run in a server application (hence the name
"Servlets", similar to "Applets" on the client side) to answer client requests.
x Servlets are not tied to a specific client-server protocol but they are most commonly used
with HTTP and the word "Servlet" is often used in the meaning of "HTTP Servlet".
x Servlets make use of the Java standard extension classes in the packages
javax. servlet (the basic Servlet framework) and javax. servlet .http
o Providing dynamic content, e.g. returning the results of a database query to the client.
o Managing state information on top of the stateless HTTP, e.g. for an online shopping
cart system which manages shopping carts for many concurrent customers and maps
every request to the right customer.
The life cycle of a servlet is controlled by the container in which the servlet has been deployed.
When a request is mapped to a servlet, the container performs the following steps:
c. Initializes the servlet instance by calling the init method. Initialization is covered in
Initializing a Servlet
3. If the container needs to remove the servlet, it finalizes the servlet by calling the servlets
destroy method.
HttpServletResponse res)
out.close();
x Two packages contain the classes and interfaces that are required to build servlets. They are
javax.servlet and javax.servlet.http.
x The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing
servlets. All servlets must implement the Servlet interface, which defines life cycle
methods.
x The javax.servlet package contains a number of classes and interfaces that describe
and define the contracts between a servlet class and the runtime environment provided for an
instance of such a class by a conforming servlet container.
x All servlets implement this interface either directly, or more commonly, by extending a
class that implements the interface.
x The two classes in the servlet API that implement the Servlet interface are GeneriISErvlet
and HttpServlet .
x For most purposes, developers will extend HttpServlet to implement their servlets while
implementing web applications employing the HTTP protocol.
x The basic Servlet interface defines a service method for handling client requests. This
method is called for each request that the servlet container routes to an instance of a servlet.
x Servlets can be used for handling both the GET Requests and the POST Requests.
x The HttpServlet class is used for handling HTTP GET Requests as it has som specialized
methods that can efficiently handle the HTTP requests. These methods are;
doGet()
doPost()
doPut()
An individual developing servlet for handling HTTP Requests needs to override one of these
methods in order to process the request and generate a response. The servlet is invoked
dynamically when an end-user submits a form.
Example:
Heres the code for ColServlet.java that overrides the doGet() method to retrieve data from the
HTTP Request and it then generates a response as well.
// import the java packages that are needed for the servlet to work
import javax.servlet. *;
import javax.servlet.http. *;
// defining a class
info .println(col);
info.close();
6.2 Cookies
Cookies are small bits of textual information that a Web server sends to a browser and that the
browser returns unchanged when visiting the same Web site or domain later.
By having the server read information it sent the client previously, the site can provide visitors
with a number of conveniences like:
x Customizing a site.
x Focusing advertising.
To send cookies to the client, a servlet would create one or more cookies with the appropriate
names and values via new Cookie (name, value)
x The cookie is added to the Set-Cookie response header by means of the addCookie method
of HttpServletResponse. For example:
x To send cookies to the client, you created a Cookie then used addCookie to send a Set-
Cookie HTTP response header.
x To read the cookies that come back from the client, call getCookies on the
HttpServletRequest. This returns an array of Cookie objects corresponding to the values that
came in on the Cookie HTTP request header
x Once this array is obtained, loop down it, calling getName on each Cookie until find one
matching the name you have in mind. You then call getValue on the matching Cookie,
doing some processing specific to the resultant value.
String defaultValue) {
if (cookieName.equals(cookie.getName()))
return(cookie.getValue());
return(defaultValue);
x Session Tracking
x Why id it needed : In many internet applications it is important to keep track of the session
when the user moves from one page to another or when there are different users logging on
to the same website at the same time
Cookies.
x HTTP cookies can be used to store information about a shopping session, and
x each subsequent connection can look up the current session and then extract
x information about that session from some location on the server machine.
URL Rewriting.
x You can append some extra data on the end of each URL that identifies the session, and the
server can associate that session identifier with data it has stored about that session.
x This is also an excellent solution, and even has the advantage that it works with browsers
that don't support cookies or where the user has disabled cookies.
x However, it has most of the same problems as cookies, namely that the server-side program
has a lot of straightforward but tedious processing to do. In addition, you have to be very
careful that every URL returned to the user (even via indirect means like
x HTML forms have an entry that looks like the following: <INPUT TYPE="HIDDEN"
NAME="session" VALUE="...">.
x This means that, when the form is submitted, the specified name and value are included in
the GET or POST data.
x However, it has the major disadvantage that it only works if every page is dynamically
generated, since the whole point is that each session has a unique identifier.
Servlets solution :
x The servlet author doesn't need to bother with many of the details, doesn't have to
explicitly manipulate cookies or information appended to the URL, and is automatically
given a convenient place to store data that is associated with each session.
example,
doSomethingWith(previousItems);
} else {
doSomethingElseWith(previousItems);
}
SJBIT, Dept. of ISE Page 60
Java and J2EE (06IS753)
JSP, JSP Tags, Tomcat, Request String, User Sessions, Cookies, Session Objects.
x JavaServer Pages (JSP) is a Sun Microsystems specification for combining Java with HTML
to provide dynamic content forWeb pages.
x When you create dynamic content, JSPs are more convenient to write than HTTP servlets
because they allow to embed Java code directly into HTML pages, in contrast with HTTP
servlets, in which you embed HTML inside Java code.
x JSP enables to separate the dynamic content of aWeb page from its presentation.
x It caters to two different types of developers: HTML developers, who are responsible for the
graphical design of the page, and Java developers, who handle the development of software to
create the dynamic content.
The following table describes the basic tags that you can use in a JSP page. Each shorthand
tag has an XML equivalent.
x The Java Servlet and JavaServer Pages specifications are developed under the Java
Community Process.
x Apache Tomcat is developed in an open and participatory environment and released under
the Apache Software
Simple example
<html>
<head><title>Hello, World</title></head>
<table>
<tr>
</table>
</body></html>
Request string
class="hello.NameHandler" />
<html>
<head><title>Hello, User</title></head>
<td width="550">
<h1>My name is Duke. What's yours?</h1>
</td> </tr> <tr>
<td width="150" </td>
<td width="550">
<form method="get">
<input type="text" name="username" size="25">
<br>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</td> </tr> </form>
</table>
<%
if ( request.getParameter("username") != null ) {
%>
<% @ include file="response.jsp" %>
<%
}
%> </body> </html>
The data the user enters is stored in the request object, which usually implements
javax.servlet.HttpServletRequest (or if your implementation uses a different protocol, another
interface that is subclassed from javax.servlet.ServletRequest). You can access the request
object directly within a scriptlet.
servlet to a Web browser, saved by the browser, and later sent back to the server.
x A cookie has a name, a single value, and optional attributes such as a comment,
The getCookies() method of the request object returns an array of Cookie objects. Cookies can
be constructed using the following code:
7.2 RMI
x RMI applications are often comprised of two separate programs: a server and a client.
x A typical server application creates a number of remote objects, makes references to those
remote objects accessible, and waits for clients to invoke methods on those remote objects.
x A typical client application gets a remote reference to one or more remote objects in the
server and then invokes methods on them. RMI provides the mecahnism by which the server
and the client communicate and pass information back and forth. Such an applications is
sometimes referred to as a distributed object application.
In RMI, a remote interface is an interface that declares a set of methods that may be invoked
from a remote Java virtual machine. A remote interface must satisfy the following
requirements:
A remote interface must at least extend, either directly or indirectly, the interface
java.rmi.Remote.
The interface ServerRef represents the server-side handle for a remote object implementation.
package java.rmi.server;
x The method exportObject finds or creates a client stub object for the
x The parameter data contains information necessary to export the object (such as port
number).
x The method getClientHost returns the host name of the current client.
When called from a thread actively handling a remote method invocation, the host name
of the client invoking the call is returned.
There is no special configuration necessary to enable the client to send RMI calls through a
firewall. The client can, however, disable the packaging of RMI calls as HTTP requests by
setting the java.rmi.server.disableHttp property to equal the boolean value true.
Deployment Descriptors
Message-Driven Bean
The EJB specification intends to provide a standard way to implement the back-end 'business'
code typically found in enterprise applications (as opposed to 'front-end' interface code). Such
code addresses the same types of problems, and solutions to these problems are often repeatedly
re-implemented by programmers. Enterprise JavaBeans are intended to handle such common
concerns as persistence, transactional integrity, and security in a standard way, leaving
programmers free to concentrate on the particular problem at hand.
There are three different types of EJB that are suited to different purposes:
x Session EJBA Session EJB is useful for mapping business process flow (or equivalent
application concepts). There are two sub-types of Session EJB stateless and stateful
represent "pure" functionality that is created as it is needed.
x Entity EJBAn Entity EJB maps a combination of data (or equivalent application
concept) and associated functionality. Entity EJBs are usually based on an underlying
data store and will be created based on that data within it.
1. Deployment Descriptors
Definition : A deployment descriptor is a file that defines the following kinds of information:
EJB structural information, such as the EJB name, class, home and remote interfaces, bean
type (session or entity), environment entries, resource factory references, EJB references,
security role references, as well as additional information based on the bean type. Application
assembly information, such as EJB references, security roles, security role references, method
permissions, and container transaction attributes. Specifying assembly descriptor information is
an optional task that an Application Assembler performs.
x Stateless session beans are components that perform transient services; stateful session
beans are components that are dedicated to one client and act as a server-side extension of
that client.
Session beans can act as agents modeling workflow or provide access to special transient
business services. As an agent, a stateful session bean might represent a customer's session at an
online shopping site.
x As a transitive service, a stateless session bean might provide access to validate and
process credit card orders.
x Session beans do not normally represent persistent business concepts like Employee or Order.
This is the domain of a different component type called an entity bean.
import javax.ejb.*;
import java.rmi.Remote;
/* *
*/
x Typically, each entity bean has an underlying table in a relational database, and each
instance of the bean corresponds to a row in that table.
Message-Driven Bean
x It acts as a JMS message listener, which is similar to an event listener except that it
receives messages instead of events.
x The messages may be sent by any J2EE component--an application client, another
enterprise bean, or a Web component--or by a JMS application or system that does not use
J2EE technology.
Message-driven beans currently process only JMS messages, but in the future they may be used to
process other kinds of messages
The Java Archive (JAR) file format enables you to bundle multiple files into a single archive file.
Typically a JAR file contains the class files and auxiliary resources associated with applets and
applications.
x Security: You can digitally sign the contents of a JAR file. Users who recognize your
signature can then optionally grant your software security privileges it wouldn't otherwise
have.
x Decreased download time: If your applet is bundled in a JAR file, the applet's class files
and associated resources can be downloaded to a browser in a single HTTP transaction
without the need for opening a new connection for each file.
x Compression: The JAR format allows you to compress your files for efficient storage.
x Packaging for extensions: The extensions framework provides a means by which you can
add functionality to the Java core platform, and the JAR file format defines the packaging
for extensions. By using the JAR file format, you can turn your software into extensions as
well.
x Package Sealing: Packages stored in JAR files can be optionally sealed so that the package
can enforce version consistency. Sealing a package within a JAR file means that all classes
defined in that package must be found in the same JAR file.
x Package Versioning: A JAR file can hold data about the files it contains, such as vendor
and version information.
x Portability: The mechanism for handling JAR files is a standard part of the Java platform's
core API.
Execution
EJBs are deployed in an EJB container, typically but not necessarily, within an application server.
The specification describes how an EJB interacts with its container and how client code interacts
with the container/EJB combination. The EJB classes used by applications are included in
the javax.ejb package. (The javax.ejb.spi package is a service provider interfaceused only by EJB
container implementations.)
Clients of EJB beans do not instantiate those beans directly via Java's new operator, but instead
have to obtain a reference via the EJB container. This reference is then not a reference to the
implementation bean itself, but to a proxy, which either dynamically implements the local or
remote business interface that the client requested or dynamically implements a sub-type of the
actual bean. The proxy can then be directly cast to the interface or bean. A client is said to have a
'view' on the EJB, and the local interface, remote interface and bean type itself respectively
correspond with the local view, remote view and no-interface view.
This proxy is needed in order to give the EJB container the opportunity to transparently provide
cross-cutting (AOP-like) services to a bean like transactions, security, interceptions, injections,
remoting, etc.
E.g. a client invokes a method on a proxy, which will then first start a transaction with the help of
the EJB container and then call the actual bean method. When the actual bean method returns, the
proxy ends the transaction (i.e. by committing it or doing a rollback) and transfers control back to
the client.
Transactions
EJB containers must support both container managed ACID transactions and bean managed
transactions.
Container-managed transactions (CMT) are by default active for calls to session beans. That is, no
explicit configuration is needed. This behavior may be declaratively tuned by the bean via
annotations and if needed such configuration can later be overridden in the deployment descriptor.
Tuning includes switching off transactions for the whole bean or specific methods, or requesting
alternative strategies for transaction propagation and starting or joining a transaction. Such
strategies mainly deal with what should happen if a transaction is or isn't already in progress at the
time the bean is called. The following variations are supported:
Type Explanation
Alternatively, the bean can also declare via an annotation that it wants to handle transactions
programmatically via the JTA API. This mode of operation is called Bean Managed Transactions
(BMT), since the bean itself handles the transaction instead of the container.
Events
JMS (Java Message Service) is used to send messages from beans to clients, to let clients receive
asynchronous messages from these beans. MDBs can be used to receive messages from clients
asynchronously using either a JMS Queue or a Topic.
As an alternative to injection, clients of an EJB can obtain a reference to the session bean's proxy
object (the EJB stub) using JNDI. This alternative can be used in cases where injection is not
available, such as non-managed beans or standalone remote Java SE clients, or when it's necessary
to programmatically determine which bean to obtain.
JNDI names for EJB session beans are assigned by the EJB container via the following scheme:
JNDI names
java:global[/<app-name>]/<module-name>/<bean-name>[!<fully-qualified-interface-
Global
name>]
Application java:app/<module-name>/<bean-name>[!<fully-qualified-interface-name>]
Module java:module/<bean-name>[!<fully-qualified-interface-name>]
A single bean can be obtained by any name matching the above patterns, depending on the
'location' of the client. Clients in the same module as the required bean can use the module scope
and larger scopes, clients in the same application as the required bean can use the app scope and
higher, etc.