You are on page 1of 679

MAT SOFT

JAVA REFERENCE GUIDE


1
DAY 1: History of Java
The Birth of Modern Programming: C
The C language shook the computer world. Its impact should not be underestimated, because it
fundamentally changed the way programming was approached and thought about. The creation of C
was a direct result of the need for a structured, efficient, high-level language that could replace
assembly code when creating systems programs. As you probably know, when a computer language is
designed, trade-offs are often made, such as the following:
- Ease-of-use versus power
- Safety versus efficiency
- Rigidity versus extensibility
Prior to C, programmers usually had to choose between languages that optimized one set of traits or
the other. For example, although FORTRAN could be used to write fairly efficient programs for scientific
applications, it was not very good for system code. And while BASIC was easy to learn, it wasnt very
powerful, and its lack of structure made its usefulness questionable for large programs. Assembly
language can be used to produce highly efficient programs, but it is not easy to learn or use
effectively. Further, debugging assembly code can be quite difficult.
Another compounding problem was that early computer languages such as BASIC, COBOL, and
FORTRAN were not designed around structured principles. Instead, they relied upon the GOTO as a
primary means of program control. As a result, programs written using these languages tended to
produce "spaghetti code-a mass of tangled jumps and conditional branches that make a program
virtually impossible to understand. While languages like Pascal are structured, they were not designed
for efficiency, and failed to include certain features necessary to make them applicable to a wide range
of programs. (Specifically, given the standard dialects of Pascal available at the time, it was not
practical to consider using Pascal for systems-level code.) So, just prior to the invention of C, no one
language had reconciled the conflicting attributes that had dogged earlier efforts. Yet the need for
such a language was pressing. By the early 1970s, the computer revolution was beginning to take
hold, and the demand for software was rapidly outpacing programmers ability to produce it. A great
deal of effort was being expended in academic circles in an attempt to create a better computer
language. But, and perhaps most importantly, a secondary force was beginning to be felt. Computer
hardware was finally becoming common enough that a critical mass was being reached. No longer
were computers kept behind locked doors.
Invented and first implemented by Dennis Ritchie on a DEC PDP-11 running the UNIX operating
system, C was the result of a development process that started with an older language called BCPL,
developed by Martin Richards. BCPL influenced a language called B, invented by Ken Thompson, which
led to the development of C in the 1970s. For many years, the de facto standard for C was the one
supplied with the UNIX operating system and described in The C Programming Language by Brian
Kernighan and Dennis Ritchie (Prentice-Hall, 1978). C was formally standardized in December 1989,
when the American National Standards Institute (ANSI) standard for C was adopted.
Prior to the invention of C, computer languages were generally designed either as academic exercises
or by bureaucratic committees. C is different. It was designed, implemented, and developed by real,
working programmers, reflecting the way that they approached the job of programming. Its features
were honed, tested, thought about, and rethought by the people who actually used the language. The
result was a language that programmers liked to use. Indeed, C quickly attracted many followers
who had a near-religious zeal for it. As such, it found wide and rapid acceptance in the programmer
community. In short, C is a language designed by and for programmers. As you will see, Java
inherited this legacy.
MAT SOFT
JAVA REFERENCE GUIDE
2
C++: The Next Step
During the late 1970s and early 1980s, C became the dominant computer programming language, and
it is still widely used today. Since C is a successful and useful language, you might ask why a need for
something else existed. The answer is complexity. Throughout the history of programming, the
increasing complexity of programs has driven the need for better ways to manage that complexity. C+
+ is a response to that need. To better understand why managing program complexity is fundamental
to the creation of C++, consider the following.
Approaches to programming have changed dramatically since the invention of the computer. For
example, when computers were first invented, programming was done by manually toggling in the
binary machine instructions by use of the front panel. As long as programs were just a few hundred
instructions long, this approach worked. As programs grew, assembly language was invented so that a
programmer could deal with larger, increasingly complex programs by using symbolic representations
of the machine instructions. As programs continued to grow, high-level languages were introduced
that gave the programmer more tools with which to handle complexity. The first widespread language
was, of course, FORTRAN. While FORTRAN was an impressive first step, it is hardly a language that
encourages clear and easy-to-understand programs. The 1960s gave birth to structured programming.
This is the method of programming championed by languages such as C. The use of structured
languages enabled programmers to write, for the first time, moderately complex programs fairly
easily. However, even with structured programming methods, once a project reaches a certain size, its
complexity exceeds what a programmer can manage. By the early 1980s, many projects were pushing
the structured approach past its limits. To solve this problem, a new way to program was invented,
calledobject-oriented programming (OOP). Object-oriented programming is discussed in detail later in
this book, but here is a brief definition: OOP is a programming methodology that helps organize
complex programs through the use of inheritance, encapsulation, and polymorphism. In the final
analysis, although C is one of the worlds great programming languages, there is a limit to its ability to
handle complexity. Once the size of a program exceeds a certain point, it becomes so complex that it
is difficult to grasp as a totality. While the precise size at which this occurs differs, depending upon
both the nature of the program and the programmer, there is always a threshold at which a program
becomes unmanageable. C++ added features that enabled this threshold to be broken, allowing
programmers to comprehend and manage larger programs. C++ was invented by Bjarne Stroustrup in
1979, while he was working at Bell Laboratories in Murray Hill, New Jersey. Stroustrup initially called
the new language "C with Classes. However, in 1983, the name was changed to C++. C++ extends C
by adding object-oriented features. Because C++ is built on the foundation of C, it includes all of Cs
features, attributes and benefits. This is a crucial reason for the success of C++ as a language. The
invention of C++ was not an attempt to create a completely new programming language. Instead, it
was an enhancement to an already highly successful one.
The Stage Is Set for Java
By the end of the 1980s and the early 1990s, object-oriented programming using C++ took hold.
Indeed, for a brief moment it seemed as if programmers had finally found the perfect language.
Because C++ blended the high efficiency and stylistic elements of C with the object-oriented
paradigm, it was a language that could be used to create a wide range of programs. However, just as
in the past, forces were brewing that would, once again, drive computer language evolution forward.
Within a few years, the World Wide Web and the Internet would reach critical mass. This event would
precipitate another revolution in programming.
MAT SOFT
JAVA REFERENCE GUIDE
3
Day 2: Introduction to Java, Features, Classes and Methods
The Creation of Java
Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at
Sun Microsystems, Inc. in 1991. It took 18 months to develop the first working version. This language
was initially called "Oak, but was renamed "Java in 1995. Between the initial implementation of Oak
in the fall of 1992 and the public announcement of Java in the spring of 1995, many more people
contributed to the design and evolution of the language. Bill Joy, Arthur van Hoff, Jonathan Payne,
Frank Yellin, and Tim Lindholm were key contributors to the maturing of the original prototype.
Somewhat surprisingly, the original impetus for Java was not the Internet! Instead, theprimary
motivation was the need for a platform-independent (that is, architecture-neutral) language that could
be used to create software to be embedded in various consumer electronic devices, such as microwave
ovens and remote controls. As you can probably guess, many different types of CPUs are used as
controllers. The trouble with C and C++ (and most other languages) is that they are designed to be
compiled for a specific target. Although it is possible to compile a C++ program for just about any
type of CPU, to do so requires a full C++ compiler targeted for that CPU. The problem is that
compilers are expensive and time-consuming to create. An easier-and more cost-efficient-solution
was needed. In an attempt to find such a solution, Gosling and others began work on a portable,
platform-independent language that could be used to produce code that would run on a variety of
CPUs under differing environments. This effort ultimately led to the creation of Java.
About the time that the details of Java were being worked out, a second, and ultimately more
important, factor was emerging that would play a crucial role in the future of Java. This second force
was, of course, the World Wide Web. Had the Web not taken shape at about the same time that Java
was being implemented, Java might have remained a useful but obscure language for programming
consumer electronics. However, with the emergence of the World Wide Web, Java was propelled to the
forefront of computer language design, because the Web, too, demanded portable programs. Most
programmers learn early in their careers that portable programs are as elusive as they are desirable.
While the quest for a way to create efficient, portable (platform-independent) programs is nearly as
old as the discipline of programming itself, it had taken a back seat to other, more pressing problems.
Further, because (at that time) much of the computer world had divided itself into the three competing
camps of Intel, Macintosh, and UNIX, most programmers stayed within their fortified boundaries, and
the urgent need for portable code was reduced. However, with the advent of the Internet and the Web,
the old problem of portability returned with a vengeance. After all, the Internet consists of a diverse,
distributed universe populated with various types of computers, operating systems, and CPUs. Even
though many kinds of platforms are attached to the Internet, users would like them all to be able to
run the same program. What was once an irritating but low-priorityproblem had become a high-profile
necessity.
By 1993, it became obvious to members of the Java design team that the problems of portability
frequently encountered when creating code for embedded controllers are also found when attempting
to create code for the Internet. In fact, the same problem that Java was initially designed to solve on
a small scale could also be applied to the Internet on a large scale. This realization caused the focus of
Java to switch from consumer electronics to Internet programming. So, while the desire for an
architecture-neutral programming language provided the initial spark, the Internet ultimately led to
Javas large-scale success. As mentioned earlier, Java derives much of its character from C and C++.
This is by intent. The Java designers knew that using the familiar syntax of C and echoing the object-
oriented features of C++ would make their language appealing to the legions of experienced C/C++
programmers. In addition to the surface similarities, Java shares some of the other attributes that
helped make C and C++ successful. First, Java was designed, tested, and refined by real, working
programmers. It is a language grounded in the needs and experiences of the people who devised it.
Thus, Java is a programmers language. Second, Java is cohesive and logically consistent. Third,
except for those constraints imposed by the Internet environment, Java gives you, the programmer,
and full control. If you program well, your programs reflect it. If you program poorly, your programs
reflect that, too.
Javas Magic: The Bytecode
MAT SOFT
JAVA REFERENCE GUIDE
4
The key that allows Java to solve both the security and the portability problems just described is that
the output of a Java compiler is not executable code. Rather, it is bytecode. Bytecode is a highly
optimized set of instructions designed to be executed by the Java run-time system, which is called the
a!a "irtual #achine ("#). In essence, the original JVM was designed as an interpreter $or bytecode.
This may come as a bit of a surprise since many modern languages are designed to be compiled into
executable code because of performance concerns. However, the fact that a Java program is executed
by the JVM helps solve the major problems associated with web-based programs. Here is why.
Translating a Java program into bytecode makes it much easier to run a program in a wide variety of
environments because only the JVM needs to be implemented for each platform. Once the run-time
package exists for a given system, any Java program can run on it. Remember, although the details of
the JVM will differ from platform to platform, all understand the same Java bytecode. If a Java
program were compiled to native code, then different versions of the same program would have to
exist for each type of CPU connected to the Internet. This is, of course, not a feasible solution. Thus,
the execution of bytecode by the JVM is the easiest way to create truly portable programs. The fact
that a Java program is executed by the JVM also helps to make it secure. Because the JVM is in
control, it can contain the program and prevent it from generating side effects outside of the system.
As you will see, safety is also enhanced by certain restrictions that exist in the Java language. In
general, when a program is compiled to an intermediate form and then interpreted by a virtual
machine, it runs slower than it would run if compiled to executable code. However, with Java, the
differential between the two is not so great. Because bytecode has been highly optimized, the use of
bytecode enables the JVM to execute programs much faster than you might expect. Although Java was
designed as an interpreted language, there is nothing about Java that prevents on-the-fly compilation
of bytecode into native code in order to boost performance. For this reason, Sun began supplying its
HotSpot technology not long after Javas initial release. HotSpot provides a Just-In-Time (JIT) compiler
for bytecode. When a JIT compiler is part of the JVM, selected portions of bytecode are compiled into
executable code in real time, on a piece-by-piece, demand basis. It is important to understand that it
is not practical to compile an entire Java program into executable code all at once, because Java
performs various run-time checks that can be done only at run time. Instead, a JIT compiler compiles
code as it is needed, during execution.
Java featres:
!"#ect !riented : In java everything is an Object. Java can be easily extended since it is
based on the Object model.
P$atform independent: Unlike many other programming languages including C and C++
when Java is compiled, it is not compiled into platform specific machine, rather into platform
independent byte code. This byte code is distributed over the web and interpreted by virtual
Machine (JVM) on whichever platform it is being run.
Simp$e :Java is designed to be easy to learn. If you understand the basic concept of OOP java
would be easy to master.
Secre : With Java's secure feature it enables to develop virus-free, tamper-free systems.
Authentication techniques are based on public-key encryption.
%rchitectra$& netra$ :Java compiler generates an architecture-neutral object file format
which makes the compiled code to be executable on many processors, with the presence Java
runtime system.
Porta"$e :being architectural neutral and having no implementation dependent aspects of the
specification makes Java portable. Compiler and Java is written in ANSI C with a clean
portability boundary which is a POSIX subset.
'o"st :Java makes an effort to eliminate error prone situations by emphasizing mainly on
compile time error checking and runtime checking.
MAT SOFT
JAVA REFERENCE GUIDE
5
M$ti&threaded : With Java's multi-threaded feature it is possible to write programs that can
do many tasks simultaneously. This design feature allows developers to construct smoothly
running interactive applications.
Interpreted :Java byte code is translated on the fly to native machine instructions and is not
stored anywhere. The development process is more rapid and analytical since the linking is an
incremental and light weight process.
(igh Performance: With the use of Just-In-Time compilers Java enables high performance.
)istri"ted :Java is designed for the distributed environment of the internet.
)ynamic : Java is considered to be more dynamic than C or C++ since it is designed to adapt
to an evolving environment. Java programs can carry extensive amount of run-time
information that can be used to verify and resolve accesses to objects on run-time.
Tools you will need:
For performing the examples, you will need a Pentium 200-MHz computer with a minimum of 64 MB of
RAM (128 MB of RAM recommended).
You also will need the following softwares:
Linux 7.1 or Windows 95/98/2000/XP/7 operating system.
Java JDK 5
Microsoft Notepad or any other text editor
Setting up the path for windows 2000/XP:
Assuming you have installed Java in c%&Program 'iles&ja!a&jd( directory:
Right-click on 'My Computer' and select 'Properties'.
Click on the 'Environment variables' button under the 'Advanced' tab.
Now alter the 'Path' variable so that it also contains the path to the Java executable. Example,
if the path is currently set to 'C:\WINDOWS\SYSTEM32', then change your path to read
'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'.
Setting up the path for windows 95/98/ME/XP/7:
Assuming you have installed Java in c%&Program 'iles&ja!a&jd( directory:
Edit the 'C:\autoexec.bat' file and add the following line at the end:
'SET PATH=%PATH%;C:\Program Files\java\jdk\bin'
MAT SOFT
JAVA REFERENCE GUIDE
6
Setting up the path for Linux, UNIX, Solaris, Free BSD:
Environment variable PATH should be set to point to where the java binaries have been installed. Refer
to your shell documentation if you have trouble doing this.
Example, if you use bash as your shell, then you would add the following line to the end of your
'.bashrc: export PATH=/path/to/java:$PATH'
Day 3: Java basic Syntax
When we consider a Java program it can be defined as a collection of objects that communicate via
invoking each others methods. Let us now briefly look into what do class, object, methods and instant
variables mean.
!"#ect & Objects have states and behaviors. Example: A dog has states-color, name, breed as
well as behaviors -wagging, barking, eating. An object is an instance of a class.
C$ass & A class can be defined as a template/ blue print that describe the behaviors/states
that object of its type support.
Methods & A method is basically a behavior. A class can contain many methods. It is in
methods where the logics are written, data is manipulated and all the actions are executed.
Instant *aria"$es & Each object has its unique set of instant variables. An object's state is
created by the values assigned to these instant variables.
First Java Program:
Let us look at a simple code that would print the words )ello *orld.
public class MyFirstJavaProgram{
/* This is my first java program.
* This will print '!llo "orl#' as th! output
*/
public static voi# main$%tring &'args({
%yst!m.out.println$)!llo "orl#)(* // prints !llo "orl#
+
+
Lets look at how to save the file, compile and run the program. Please follow the steps given below:
1. Open notepad and add the code as above.
MAT SOFT
JAVA REFERENCE GUIDE
7
2. Save the file as : MyFirstJavaProgram.java.
3. Open a command prompt window and go o the directory where you saved the class. Assume
its C:\.
4. Type ' javac MyFirstJavaProgram.java ' and press enter to compile your code. If there are no
errors in your code the command prompt will take you to the next line.( Assumption : The
path variable is set).
5. Now type ' java MyFirstJavaProgram ' to run your program.
6. You will be able to see ' Hello World ' printed on the window.
, - . javac MyFirstJavaProgram.java
, - . java MyFirstJavaProgram
!llo "orl#
Basic Syntax:
About Java programs, it is very important to keep in mind the following points.
Case Sensitivity & Java is case sensitive which means identifier (e$$o and he$$o would have
different meaning in Java.
C$ass Names & For all class names the first letter should be in Upper Case.
If several words are used to form a name of the class each inner words first letter should be in
Upper Case.
Example class #y'irsta!aClass
Method Names & All method names should start with a Lower Case letter.
If several words are used to form the name of the method, then each inner word's first letter
should be in Upper Case.
Example public !oid my#ethod+ame()
Program +i$e Name & Name of the program file should exactly match the class name.
When saving the file you should save it using the class name (Remember java is case
sensitive) and append '.java' to the end of the name. (if the file name and the class name do
not match your program will not compile).
Example : Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved
as ,#y'irsta!aProgram.ja!a,
p"$ic static void main,String args-./ & java program processing starts from the main()
method which is a mandatory part of every java program..
Java Identifers:
MAT SOFT
JAVA REFERENCE GUIDE
8
All java components require names. Names used for classes, variables and methods are called
identifiers. In java there are several points to remember about identifiers. They are as follows:
All identifiers should begin with a letter (A to Z or a to z ), currency character ($) or an
underscore (-).
After the first character identifiers can have any combination of characters.
A key word cannot be used as an identifier.
Most importantly identifiers are case sensitive.
Examples of legal identifiers:age, $salary, _value, __1_value
Examples of illegal identifiers : 123abc, -salary
Java Modifers:
Like other languages it is possible to modify classes, methods etc by using modifiers. There are two
categories of modifiers.
%ccess Modifiers : defualt, public , protected, private
Non&access Modifiers : final, abstract, strictfp
We will be looking into more details about modifiers in the next section.
Java Variables:
We would see following type of variables in Java:
Local Variables
Class Variables (Static Variables)
Instance Variables (Non static variables)
Java Arrays:
Arrays are objects that store multiple variables of the same type. However an Array itself is an object
on the heap. We will look into how to declare, construct and initialize in the upcoming chapters.
Java Enums:
Enums were introduced in java 5.0. Enums restrict a variable to have one of only a few predefined
values. The values in this enumerated list are called enums.
With the use of enums it is possible to reduce the number of bugs in your code.
MAT SOFT
JAVA REFERENCE GUIDE
9
For example if we consider an application for a fresh juice shop it would be possible to restrict the
glass size to small, medium and Large. This would make sure that it would not allow anyone to order
any size other than the small, medium or large.
Example:
class Fr!shJuic!{
!num Fr!shJuic!%i/!{ %M0112 M3456M2 10783 +
Fr!shJuic!%i/! si/!*
+
public class Fr!shJuic!T!st{
public static voi# main$%tring args&'({
Fr!shJuic! juic! 9 n!w Fr!shJuic!$(*
juic!.si/! 9 Fr!shJuic!. Fr!shJuic!%i/!.M3456M *
+
+
Note: enums can be declared as their own or inside a class. Methods, variables, constructors can be
defined inside enums as well.
Java Keywords:
The following list shows the reserved words in Java. These reserved words may not be used as
constant or variable or any other identifier names.
Abstract assert boolean break
Byte case catch char
Class const continue default
Do double else enum
Extends final finally float
For goto if implements
Import instanceof int interface
Long native new package
Private protected public return
Short static strictfp super
MAT SOFT
JAVA REFERENCE GUIDE
10
Switch synchronized this throw
Throws transient try void
Volatile while
Comments in Java
Java supports single line and multi-line comments very similar to c and c++. All characters available
inside any comment are ignored by Java compiler.
public class MyFirstJavaProgram{
/* This is my first java program.
* This will print '!llo "orl#' as th! output
* This is an !:ampl! of multi;lin! comm!nts.
*/
public static voi# main$%tring &'args({
// This is an !:ampl! of singl! lin! comm!nt
/* This is also an !:ampl! of singl! lin! comm!nt. */
%yst!m.out.println$)!llo "orl#)(*
++
Using Blank Lines:
A line containing only whitespace, possibly with a comment, is known as a blank line, and Java totally
ignores it.
OBJECTS & CLASSES
!"#ect & Objects have states and behaviors. Example: A dog has states-color, name, breed as
well as behaviors -wagging, barking, eating. An object is an instance of a class.
C$ass & A class can be defined as a template/ blue print that describe the behaviors/states
that object of its type support.
Objects in Java:
Let us now look deep into what are objects. If we consider the real-world we can find many objects
around us, Cars, Dogs, Humans etc. All these objects have a state and behavior.
If we consider a dog then its state is . name, breed, color, and the behavior is . barking, wagging,
running
If you compare the software object with a real world object, they have very similar characteristics.
MAT SOFT
JAVA REFERENCE GUIDE
11
Software objects also have a state and behavior. A software object's state is stored in fields and
behavior is shown via methods.
So in software development methods operate on the internal state of an object and the object-to-
object communication is done via methods.
Classes in Java:
A class is a blue print from which individual objects are created.
A sample of a class is given below:
public class 4og{
%tring br!!#*
int ag!*
%tring color*
voi# bar<ing$({ +

voi# hungry$({ +

voi# sl!!ping$({ +
+
A class can contain any of the following variable types.
0oca$ varia"$es 1 variables defined inside methods, constructors or blocks are called local
variables. The variable will be declared and initialized within the method and the variable will
be destroyed when the method has completed.
Instance varia"$es 1 Instance variables are variables within a class but outside any method.
These variables are instantiated when the class is loaded. Instance variables can be accessed
from inside any method, constructor or blocks of that particular class.
C$ass varia"$es 1 Class variables are variables declared with in a class, outside any method,
with the static keyword.
A class can have any number of methods to access the value of various kind of methods. In the above
example, barking(), hungry() and sleeping() are variables.
Below mentioned are some of the important topics that need to be discussed when looking into classes
of the Java Language.
Creating an Object:
As mentioned previously a class provides the blueprints for objects. So basically an object is created
from a class. In java the new key word is used to create new objects. There are three steps when
creating an object from a class:
)ec$aration 1 A variable declaration with a variable name with an object type.
Instantiation 1 The 'new' key word is used to create the object.
MAT SOFT
JAVA REFERENCE GUIDE
12
Initia$i2ation 1 The 'new' keyword is followed by a call o a constructor. This call initializes the
new object.
Example of creating an object is given below:
class Puppy{
public Puppy$%tring nam!({
// This constructor has on! param!t!r2 name.
%yst!m.out.println$)Pass!# =am! is -) > nam! (*
+
public static voi# main$%tring &'args({
// Following stat!m!nt woul# cr!at! an obj!ct myPuppy
Puppy myPuppy 9 n!w Puppy$ )tommy) (*
+
+
If we compile and run the above program then it would produce following result:
Pass!# =am! is -tommy
Accessing Instance Variables and Methods:
Instance variables and methods are accessed via created objects. To access an instance variable the
fully qualified path should be as follows:
/* First cr!at! an obj!ct */
?bj!ct7!f!r!nc! 9 n!w ,onstructor$(*
/* =ow call a variabl! as follows */
?bj!ct7!f!r!nc!.variabl!=am!*
/* =ow you can call a class m!tho# as follows */
?bj!ct7!f!r!nc!.M!tho#=am!$(*
Example:
This example explains how to access instance variables and methods of a class:
class Puppy{

int puppy0g!*
public Puppy$%tring nam!({
// This constructor has on! param!t!r2 name.
%yst!m.out.println$)Pass!# =am! is -) > nam! (*
+
public s!t0g!$ int ag! ({
MAT SOFT
JAVA REFERENCE GUIDE
13
puppy0g! 9 ag!*
+
public g!t0g!$ ({
%yst!m.out.println$)Puppy's ag! is -) > puppy0g! (*
r!turn puppy0g!*
+
public static voi# main$%tring &'args({
/* ?bj!ct cr!ation */
Puppy myPuppy 9 n!w Puppy$ )tommy) (*
/* ,all class m!tho# to s!t puppy's ag! */
myPuppy.s!t0g!$ @ (*
/* ,all anoth!r class m!tho# to g!t puppy's ag! */
myPuppy.g!t0g!$ (*
/* Aou can acc!ss instanc! variabl! as follows as w!ll */
%yst!m.out.println$)Bariabl! Balu! -) > myPuppy.puppy0g! (*
+
+
If we compile and run the above program then it would produce following result:
Pass!# =am! is -tommy
Puppy's ag! is -@
Bariabl! Balu! -@
A Java method is a collection of statements that are grouped together to perform an operation. When
you call the System.out.println method, for example, the system actually executes several statements
in order to display a message on the console. Now you will learn how to create your own methods with
or without return values, invoke a method with or without parameters, overload methods using the
same names, and apply method abstraction in the program design.
Creating a Method:
In general, a method has the following syntax:
mo#ifi!r r!turnBalu!Typ! m!tho#=am!$list of param!t!rs( {
// M!tho# bo#y* +
A method definition consists of a method header and a method body. Here are all the parts of a
method:
Modifiers: The modifier, which is optional, tells the compiler how to call the method. This
defines the access type of the method.
'etrn Type: A method may return a value. The returnValueType is the data type of the value
the method returns. Some methods perform the desired operations without returning a value.
In this case, the returnValueType is the keyword void.
MAT SOFT
JAVA REFERENCE GUIDE
14
Method Name: This is the actual name of the method. The method name and the parameter
list together constitute the method signature.
Parameters: A parameter is like a placeholder. When a method is invoked, you pass a value
to the parameter. This value is referred to as actual parameter or argument. The parameter
list refers to the type, order, and number of the parameters of a method. Parameters are
optional; that is, a method may contain no parameters.
Method Body: The method body contains a collection of statements that define what the
method does.
Note: In certain other languages, methods are referred to as procedures and functions. A method
with a nonvoid return value type is called a function; a method with a void return value type is called a
procedure.
Example:
Here is the source code of the above defined method called max(). This method takes two parameters
num1 and num2 and returns the maximum between the two:
/** 7!turn th! ma: b!tw!!n two numb!rs */
public static int ma:$int numC2 int num@( {
int r!sult*
if $numC . num@(
r!sult 9 numC*
!ls!
r!sult 9 num@*
r!turn r!sult*
+
Calling a Method:
In creating a method, you give a definition of what the method is to do. To use a method, you have to
call or invoke it. There are two ways to call a method; the choice is based on whether the method
returns a value or not.
MAT SOFT
JAVA REFERENCE GUIDE
15
When a program calls a method, program control is transferred to the called method. A called method
returns control to the caller when its return statement is executed or when its method-ending closing
brace is reached.
If the method returns a value, a call to the method is usually treated as a value. For example:
int larg!r 9 ma:$DE2 FE(*
If the method returns void, a call to the method must be a statement. For example, the method
println returns void. The following call is a statement:
%yst!m.out.println$)"!lcom! to JavaG)(*
Example:
Following is the example to demonstrate how to define a method and how to call it:
public class T!stMa: {
/** Main m!tho# */
public static voi# main$%tring&' args( {
int i 9 H*
int j 9 @*
int < 9 ma:$i2 j(*
%yst!m.out.println$)Th! ma:imum b!tw!!n ) > i >
) an# ) > j > ) is ) > <(*
+
/** 7!turn th! ma: b!tw!!n two numb!rs */
public static int ma:$int numC2 int num@( {
int r!sult*
if $numC . num@(
r!sult 9 numC*
!ls!
r!sult 9 num@*
r!turn r!sult*
+
This would produce following result:
Th! ma:imum b!tw!!n H an# @ is H
This program contains the main method and the max method. The main method is just like any other
method except that it is invoked by the JVM.
The main method's header is always the same, like the one in this example, with the modifiers public
and static, return value type void, method name main, and a parameter of the String[] type. String[]
indicates that the parameter is an array of String.
The void Keyword:
MAT SOFT
JAVA REFERENCE GUIDE
16
This section shows how to declare and invoke a void method. Following example gives a program that
declares a method named printGrade and invokes it to print the grade for a given score.
Example:
public class T!stBoi#M!tho# {
public static voi# main$%tring&' args( {
print8ra#!$IJ.H(*
+
public static voi# print8ra#!$#oubl! scor!( {
if $scor! .9 KE.E( {
%yst!m.out.println$'0'(*
+
!ls! if $scor! .9 JE.E( {
%yst!m.out.println$'L'(*
+
!ls! if $scor! .9 IE.E( {
%yst!m.out.println$','(*
+
!ls! if $scor! .9 ME.E( {
%yst!m.out.println$'4'(*
+
!ls! {
%yst!m.out.println$'F'(*
+
+
+
This would produce following result:
,
Here the printGrade method is a void method. It does not return any value. A call to a void method
must be a statement. So, it is invoked as a statement in line 3 in the main method. This statement is
like any Java statement terminated with a semicolon.
Passing Parameters by Values:
When calling a method, you need to provide arguments, which must be given in the same order as
their respective parameters in the method specification. This is known as parameter order association.
For example, the following method prints a message n times:
public static voi# nPrintln$%tring m!ssag!2 int n( {
for $int i 9 E* i N n* i>>(
%yst!m.out.println$m!ssag!(*
+
MAT SOFT
JAVA REFERENCE GUIDE
17
Here, you can use nPrintln("Hello", 3) to print "Hello" three times. The nPrintln("Hello", 3) statement
passes the actual string parameter, "Hello", to the parameter, message; passes 3 to n; and prints
"Hello" three times. However, the statement nPrintln(3, "Hello") would be wrong.
When you invoke a method with a parameter, the value of the argument is passed to the parameter.
This is referred to as pass-by-value. If the argument is a variable rather than a literal value, the value
of the variable is passed to the parameter. The variable is not affected, regardless of the changes
made to the parameter inside the method.
For simplicity, Java programmers often say passing an argument x to a parameter y, which actually
means passing the value of x to y.
Example:
Following is a program that demonstrates the effect of passing by value. The program creates a
method for swapping two variables. The swap method is invoked by passing two arguments.
Interestingly, the values of the arguments are not changed after the method is invoked.
public class T!stPassLyBalu! {
public static voi# main$%tring&' args( {
int numC 9 C*
int num@ 9 @*
%yst!m.out.println$)L!for! swap m!tho#2 numC is ) >
numC > ) an# num@ is ) > num@(*
// 6nvo<! th! swap m!tho#
swap$numC2 num@(*
%yst!m.out.println$)0ft!r swap m!tho#2 numC is ) >
numC > ) an# num@ is ) > num@(*
+
/** M!tho# to swap two variabl!s */
public static voi# swap$int nC2 int n@( {
%yst!m.out.println$)Ot6nsi#! th! swap m!tho#)(*
%yst!m.out.println$)OtOtL!for! swapping nC is ) > nC
> ) n@ is ) > n@(*
// %wap nC with n@
int t!mp 9 nC*
nC 9 n@*
n@ 9 t!mp*
%yst!m.out.println$)OtOt0ft!r swapping nC is ) > nC
> ) n@ is ) > n@(*
+
+
This would produce following result:
L!for! swap m!tho#2 numC is C an# num@ is @
6nsi#! th! swap m!tho#
L!for! swapping nC is C n@ is @
0ft!r swapping nC is @ n@ is C
0ft!r swap m!tho#2 numC is C an# num@ is @
MAT SOFT
JAVA REFERENCE GUIDE
18
The Scope of Variables:
The scope of a variable is the part of the program where the variable can be referenced. A variable
defined inside a method is referred to as a local variable.
The scope of a local variable starts from its declaration and continues to the end of the block that
contains the variable. A local variable must be declared before it can be used.
A parameter is actually a local variable. The scope of a method parameter covers the entire method.
A variable declared in the initial action part of a for loop header has its scope in the entire loop. But a
variable declared inside a for loop body has its scope limited in the loop body from its declaration to
the end of the block that contains the variable as shown below:
You can declare a local variable with the same name multiple times in different non-nesting blocks in a
method, but you cannot declare a local variable twice in nested blocks.
Using Command-Line Arguments:
Sometimes you will want to pass information into a program when you run it. This is accomplished by
passing command-line arguments to main( ). A command-line argument is the information that
directly follows the program's name on the command line when it is executed. To access the
command-line arguments inside a Java program is quite easy.they are stored as strings in the String
array passed to main( ).
Example:
The following program displays all of the command-line arguments that it is called with:
class ,omman#1in! {
public static voi# main$%tring args&'({
for$int i9E* iNargs.l!ngth* i>>({
%yst!m.out.println$)args&) > i > )'- ) >
args&i'(*
+
+
MAT SOFT
JAVA REFERENCE GUIDE
19
+
Try executing this program, as shown here:
java ,omman#1in! this is a comman# lin! @EE ;CEE
This would produce following result:
args&E'- this
args&C'- is
args&@'- a
args&D'- comman#
args&F'- lin!
args&H'- @EE
args&M'- ;CEE
Day 4: Constructors
It can be tedious to initialize all of the variables in a class each time an instance is created. Even
when you add convenience functions like set)im, /, it would be simpler and more concise
to have all of the setup done at the time the object is first created. Because the requirement
for initialization is so common, Java allows objects to initialize themselves when they are
created. This automatic initialization is performed through the use of a constructor.
Aconstructor initializes an object immediately upon creation. It has the same name as the
class in which it resides and is syntactically similar to a method. Once defined, the constructor
is automatically called immediately after the object is created, before the ne3 operator
completes.
Constructors look a little strange because they have no return type, not even void. This is
because the implicit return type of a class constructor is the class type itself. It is the
constructors job to initialize the internal state of an object so that the code creating an instance
will have a fully initialized, usable object immediately.
You can rework the Box example so that the dimensions of a box are automatically
initialized when an object is constructed. To do so, replace set)im, / with a constructor.
MAT SOFT
JAVA REFERENCE GUIDE
20
Lets begin by defining a simple constructor that simply sets the dimensions of each box
to the same values. This version is shown here:
/* Here, Box uses a constructor to initialize the
dimensions of a box.
*/
class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box() {
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
class BoxDemo6 {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
When this program is run, it generates the following results:
Constructing Box
Constructing Box
Volume is 1000.0
Volume is 1000.0
As you can see, both my"ox4 and my"ox5 were initialized by the Box, / constructor when
they were created. Since the constructor gives all boxes the same dimensions, 10 by 10 by 10,
both my"ox4 and my"ox5 will have the same volume. The print$n, / statement inside Box, /
is for the sake of illustration only. Most constructors will not display anything. They will
simply initialize an object.
Before moving on, lets reexamine the ne3 operator. As you know, when you allocate an
object, you use the following general form:
class-!ar = new classname( );
Now you can understand why the parentheses are needed after the class name. What is actually
happening is that the constructor for the class is being called. Thus, in the line
Box mybox1 = new Box();
ne3 Box, / is calling the Box, / constructor. When you do not explicitly define a constructor
for a class, then Java creates a default constructor for the class. This is why the preceding line
of code worked in earlier versions of Box that did not define a constructor. The default
MAT SOFT
JAVA REFERENCE GUIDE
21
constructor automatically initializes all instance variables to zero. The default constructor is
often sufficient for simple classes, but it usually wont do for more sophisticated ones. Once
you define your own constructor, the default constructor is no longer used.
Parameteri2ed Constrctors
While the Box, / constructor in the preceding example does initialize a Box object, it is not
very useful-all boxes have the same dimensions. What is needed is a way to construct Box
objects of various dimensions. The easy solution is to add parameters to the constructor. As
you can probably guess, this makes them much more useful. For example, the following version
of Box defines a parameterized constructor that sets the dimensions of a box as specified by
those parameters. Pay special attention to how Box objects are created.
/* Here, Box uses a parameterized constructor to
initialize the dimensions of a box.
*/
class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
class BoxDemo7 {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
The output from this program is shown here:
Volume is 3000.0
Volume is 162.0
As you can see, each object is initialized as specified in the parameters to its constructor.
For example, in the following line,
Box mybox1 = new Box(10, 20, 15);
the values 10, 20, and 15 are passed to the Box, / constructor when ne3 creates the object.
Thus, my"ox4s copy of 3idth, height, and depth will contain the values 10, 20, and 15,
respectively.
The this 6ey3ord
MAT SOFT
JAVA REFERENCE GUIDE
22
Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines
the this keyword. this can be used inside any method to refer to the current object. That is,
this is always a reference to the object on which the method was invoked. You can use this
anywhere a reference to an object of the current class type is permitted.
To better understand what this refers to, consider the following version of Box, /:
// A redundant use of this.
Box(double w, double h, double d) {
this.width = w;
this.height = h;
this.depth = d;
}
This version of Box, / operates exactly like the earlier version. The use of this is redundant,
but perfectly correct. Inside Box, /, this will always refer to the invoking object. While it is
redundant in this case, this is useful in other contexts, one of which is explained in the next
section.
Day 5: Data types, Variables, Operators & Control Flow
DATA TYPES
Variables are nothing but reserved memory locations to store values. This means that when you create
a variable you reserve some space in memory.
Based on the data type of a variable, the operating system allocates memory and decides what can be
stored in the reserved memory. Therefore, by assigning different data types to variables, you can
store integers, decimals, or characters in these variables.
There are two data types available in Java:
1. Primitive Data Types
2. Reference/Object Data Types
Primitive Data Types:
MAT SOFT
JAVA REFERENCE GUIDE
23
There are eight primitive data types supported by Java. Primitive data types are predefined by the
language and named by a key word. Let us now look into detail about the eight primitive data types.
byte:
Byte data type is a 8-bit signed two's complement integer.
Minimum value is -128 (-2^7)
Maximum value is 127 (inclusive)(2^7 -1)
Default value is 0
Byte data type is used to save space in large arrays, mainly in place of integers, since a byte
is four times smaller than an int.
Example : byte a = 100 , byte b = -50
short:
Short data type is a 16-bit signed two's complement integer.
Minimum value is -32,768 (-2^15)
Maximum value is 32,767(inclusive) (2^15 -1)
Short data type can also be used to save memory as byte data type. A short is 2 times smaller
than an int
Default value is 0.
Example : short s= 10000 , short r = -20000
int:
Int data type is a 32-bit signed two's complement integer.
Minimum value is - 2,147,483,648.(-2^31)
Maximum value is 2,147,483,647(inclusive).(2^31 -1)
Int is generally used as the default data type for integral values unless there is a concern
about memory.
The default value is 0.
Example : int a = 100000, int b = -200000
MAT SOFT
JAVA REFERENCE GUIDE
24
long:
Long data type is a 64-bit signed two's complement integer.
Minimum value is -9,223,372,036,854,775,808.(-2^63)
Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1)
This type is used when a wider range than int is needed.
Default value is 0L.
Example : int a = 100000L, int b = -200000L
foat:
Float data type is a single-precision 32-bit IEEE 754 floating point.
Float is mainly used to save memory in large arrays of floating point numbers.
Default value is 0.0f.
Float data type is never used for precise values such as currency.
Example : float f1 = 234.5f
double:
double data type is a double-precision 64-bit IEEE 754 floating point.
This data type is generally used as the default data type for decimal values. generally the
default choice.
Double data type should never be used for precise values such as currency.
Default value is 0.0d.
Example : double d1 = 123.4
boolean:
boolean data type represents one bit of information.
There are only two possible values : true and false.
This data type is used for simple flags that track true/false conditions.
Default value is false.
MAT SOFT
JAVA REFERENCE GUIDE
25
Example : boolean one = true
char:
char data type is a single 16-bit Unicode character.
Minimum value is '\u0000' (or 0).
Maximum value is '\uffff' (or 65,535 inclusive).
Char data type is used to store any character.
Example . char letterA ='A'
Reference Data Types:
Reference variables are created using defined constructors of the classes. They are used to
access objects. These variables are declared to be of a specific type that cannot be changed.
For example, Employee, Puppy etc.
Class objects, and various type of array variables come under reference data type.
Default value of any reference variable is null.
A reference variable can be used to refer to any object of the declared type or any compatible
type.
Example : Animal animal = new Animal("giraffe");
Java Literals:
A literal is a source code representation of a fixed value. They are represented directly in the code
without any computation.
Literals can be assigned to any primitive type variable. For example:
byt! a 9 MJ*
char a 9 '0'
byte, int, long, and short can be expressed in decimal(base 10),hexadecimal(base 16) or octal(base 8)
number systems as well.
Prefix 0 is used to indicates octal and prefix 0x indicates hexadecimal when using these number
systems for literals. For example:
int #!cimal 9 CEE*
int octal 9 ECFF*
int h!:a 9 E:MF*
MAT SOFT
JAVA REFERENCE GUIDE
26
String literals in Java are specified like they are in most other languages by enclosing a sequence of
characters between a pair of double quotes. Examples of string literals are:
)!llo "orl#)
)twoOnlin!s)
)O)This is in Puot!sO))
String and char types of literals can contain any Unicode characters. For example:
char a 9 'OuEEEC'*
%tring a 9 )OuEEEC)*
Java language supports few special escape sequences for String and char literals as well. They are:
Notation Character represented
\n Newline (0x0a)
\r Carriage return (0x0d)
\f Formfeed (0x0c)
\b Backspace (0x08)
\s Space (0x20)
\t tab
\" Double quote
\' Single quote
\\ backslash
\ddd Octal character (ddd)
\uxxxx Hexadecimal UNICODE character (xxxx)
VARIABLES
In Java, all variables must be declared before they can be used. The basic form of a variable
declaration is shown here:
MAT SOFT
JAVA REFERENCE GUIDE
27
typ! i#!ntifi!r & 9 valu!'&2 i#!ntifi!r &9 valu!' ...' *
The type is one of Java's datatypes. The identi$ier is the name of the variable. To declare more than
one variable of the specified type, use a comma-separated list.
Here are several examples of variable declarations of various types. Note that some include an
initialization.
int a2 b2 c* // #!clar!s thr!! ints2 a2 b2 an# c.
int # 9 D2 !2 f 9 H* // #!clar!s thr!! mor! ints2 initiali/ing
// # an# f.
byt! / 9 @@* // initiali/!s /.
#oubl! pi 9 D.CFCHK* // #!clar!s an appro:imation of pi.
char : 9 ':'* // th! variabl! : has th! valu! ':'.
This chapter will explain various variable types available in Java Language. There are three kinds of
variables in Java:
1. Local variables
2. Instance variables
3. Class/static variables
Local variables :
Local variables are declared in methods, constructors, or blocks.
Local variables are created when the method, constructor or block is entered and the variable
will be destroyed once it exits the method, constructor or block.
Access modifiers cannot be used for local variables.
Local variables are visible only within the declared method, constructor or block.
Local variables are implemented at stack level internally.
There is no default value for local variables so local variables should be declared and an initial
value should be assigned before the first use.
Example:
Here age is a local variable. This is defined inside pup-ge() method and its scope is limited to this
method only.
public class T!st{
public voi# pup0g!$({
int ag! 9 E*
ag! 9 ag! > I*
%yst!m.out.println$)Puppy ag! is - ) > ag!(
MAT SOFT
JAVA REFERENCE GUIDE
28
+

public static voi# main$%tring args&'({
T!st t!st 9 n!w T!st$(*
T!st.pup0g!$(*
+
+
This would produce following result:
Puppy ag! is- I
Example:
Following example uses age without initializing it, so it would give an error at the time of compilation.
public class T!st{
public voi# pup0g!$({
int ag!*
ag! 9 ag! > I*
%yst!m.out.println$)Puppy ag! is - ) > ag!(
+

public static voi# main$%tring args&'({
T!st t!st 9 n!w T!st$(*
T!st.pup0g!$(*
+
+
This would produce following error while compiling it:
T!st.java-F-variabl! numb!r might not hav! b!!n initiali/!#
ag! 9 ag! > I*
Q
C !rror
Instance variables :
Instance variables are declared in a class, but outside a method, constructor or any block.
When a space is allocated for an object in the heap a slot for each instance variable value is
created.
Instance variables are created when an object is created with the use of the key word 'new'
and destroyed when the object is destroyed.
MAT SOFT
JAVA REFERENCE GUIDE
29
Instance variables hold values that must be referenced by more than one method, constructor
or block, or essential parts of an object.s state that must be present through out the class.
Instance variables can be declared in class level before or after use.
Access modifiers can be given for instance variables.
The instance variables are visible for all methods, constructors and block in the class. Normally
it is recommended to make these variables private (access level).However visibility for
subclasses can be given for these variables with the use of access modifiers.
Instance variables have default values. For numbers the default value is 0, for Booleans it is
false and for object references it is null. Values can be assigned during the declaration or
within the constructor.
Instance variables can be accessed directly by calling the variable name inside the class.
However within static methods and different class ( when instance variables are given
accessibility) the should be called using the fully qualified
name .Object.e$erence."ariable+ame.
Example:
import java.io.**
class 3mploy!!{
// this instanc! variabl! is visibl! for any chil# class.
public %tring nam!*

// salary variabl! is visibl! in 3mploy!! class only.
privat! #oubl! salary*

// Th! nam! variabl! is assign!# in th! constructor.
public 3mploy!! $%tring !mp=am!({
nam! 9 !mp=am!*
+
// Th! salary variabl! is assign!# a valu!.
public voi# s!t%alary$#oubl! !mp%al({
salary 9 !mp%al*
+

// This m!tho# prints th! !mploy!! #!tails.
public voi# print3mp$({
%yst!m.out.println$)nam! - ) > nam! (*
%yst!m.out.println$)salary -) > salary(*
+
public static voi# main$%tring args&'({
3mploy!! !mp?n! 9 n!w 3mploy!!$)7ansi<a)(*
!mp?n!.s!t%alary$CEEE(*
!mp?n!.print3mp$(*
+
MAT SOFT
JAVA REFERENCE GUIDE
30
+
This would produce following result:
nam! - 7ansi<a
salary -CEEE.E
Class/static variables :
Class variables also known as static variables are declared with the static keyword in a class,
but outside a method, constructor or a block.
There would only be one copy of each class variable per class, regardless of how many objects
are created from it.
Static variables are rarely used other than being declared as constants. Constants are
variables that are declared as public/private, final and static. Constant variables never change
from their initial value.
Static variables are stored in static memory. It is rare to use static variables other than
declared final and used as either public or private constants.
Static variables are created when the program starts and destroyed when the program stops.
Visibility is similar to instance variables. However, most static variables are declared public
since they must be available for users of the class.
Default values are same as instance variables. For numbers the default value is 0, for
Booleans it is false and for object references it is null. Values can be assigned during the
declaration or within the constructor. Additionally values can be assigned in special static
initializer blocks.
Static variables can be accessed by calling with the class name .Class+ame."ariable+ame.
When declaring class variables as public static final, then variables names (constants) are all
in upper case. If the static variables are not public and final the naming syntax is the same as
instance and local variables.
Example:
import java.io.**
class 3mploy!!{
// salary variabl! is a privat! static variabl!
privat! static #oubl! salary*
// 43P07TM3=T is a constant
public static final %tring 43P07TM3=T 9 )4!v!lopm!nt)*
MAT SOFT
JAVA REFERENCE GUIDE
31
public static voi# main$%tring args&'({
salary 9 CEEE*
%yst!m.out.println$43P07TM3=T>)av!rag! salary-)>salary(*
+
+
This would produce following result:
4!v!lopm!nt av!rag! salary-CEEE
Note: If the variables are access from an outside class the constant should be accessed as
Employee.DEPARTMENT
MODIFIERS
Modifiers are keywords that you add to those definitions to change their meanings. The Java language
has a wide variety of modifiers, including the following:
Java Access Modifiers
Non Access Modifiers
To use a modifier, you include its keyword in the definition of a class, method, or variable. The
modifier precedes the rest of the statement, as in the following examples (Italic ones):
public class class=am! {
// ...
+
private bool!an myFlag*
static final #oubl! w!!<s 9 K.H*
protected static final int L?R"64T 9 F@*
public static voi# main$%tring&' argum!nts( {
// bo#y of m!tho#
+
Access Control Modifers:
Java provides a number of access modifiers to set access levels for classes, variables, methods and
constructors. The four access levels are:
1. Visible to the package. the default. No modifiers are needed.
2. Visible to the class only (private).
3. Visible to the world (public).
4. Visible to the package and all subclasses (protected).
MAT SOFT
JAVA REFERENCE GUIDE
32
Non Access Modifers:
Java provides a number of non-access modifiers to achieve many other functionality.
The static modifier for creating class methods and variables
The $inal modifier for finalizing the implementations of classes, methods, and variables.
The abstract modifier for creating abstract classes and methods.
The synchroni/ed and !olatile modifiers, which are used for threads.
OPERATORS
Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into
the following groups:
Arithmetic Operators
Relational Operators
Bitwise Operators
Logical Operators
Assignment Operators
Misc Operators
The Arithmetic Operators:
Arithmetic operators are used in mathematical expressions in the same way that they are used in
algebra. The following table lists the arithmetic operators:
Assume integer variable A holds 10 and variable B holds 20 then:
!perator )escription 7xamp$e
+ Addition - Adds values on either side of the
operator
A + B will give 30
- Subtraction - Subtracts right hand operand
from left hand operand
A - B will give -10
* Multiplication - Multiplies values on either
side of the operator
A * B will give 200
/ Division - Divides left hand operand by right B / A will give 2
MAT SOFT
JAVA REFERENCE GUIDE
33
hand operand
% Modulus - Divides left hand operand by right
hand operand and returns remainder
B % A will give 0
++ Increment - Increase the value of operand
by 1
B++ gives 21
-- Decrement - Decrease the value of operand
by 1
B-- gives 19
The Relational Operators:
There are following relational operators supported by Java language
Assume variable A holds 10 and variable B holds 20 then:
!perator )escription 7xamp$e
== Checks if the value of two operands are
equal or not, if yes then condition becomes
true.
(A == B) is not true.
!= Checks if the value of two operands are
equal or not, if values are not equal then
condition becomes true.
(A != B) is true.
> Checks if the value of left operand is greater
than the value of right operand, if yes then
condition becomes true.
(A > B) is not true.
< Checks if the value of left operand is less
than the value of right operand, if yes then
condition becomes true.
(A < B) is true.
>= Checks if the value of left operand is greater
than or equal to the value of right operand,
if yes then condition becomes true.
(A >= B) is not true.
<= Checks if the value of left operand is less
than or equal to the value of right operand,
(A <= B) is true.
MAT SOFT
JAVA REFERENCE GUIDE
34
if yes then condition becomes true.
The Bitwise Operators:
Java defines several bitwise operators which can be applied to the integer types, long, int, short, char,
and byte.
Bitwise operator works on bits and perform bit by bit operation. Assume if a = 60; and b = 13; Now in
binary format they will be as follows:
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
The following table lists the bitwise operators:
Assume integer variable A holds 60 and variable B holds 13 then:
!perator )escription 7xamp$e
& Binary AND Operator copies a bit to the
result if it exists in both operands.
(A & B) will give 12 which is 0000 1100
| Binary OR Operator copies a bit if it exists in
eather operand.
(A | B) will give 61 which is 0011 1101
^ Binary XOR Operator copies the bit if it is
set in one operand but not both.
(A ^ B) will give 49 which is 0011 0001
~ Binary Ones Complement Operator is unary
and has the efect of 'flipping' bits.
(~A ) will give -60 which is 1100 0011
<< Binary Left Shift Operator. The left operands
value is moved left by the number of bits
specified by the right operand.
A << 2 will give 240 which is 1111 0000
MAT SOFT
JAVA REFERENCE GUIDE
35
>> Binary Right Shift Operator. The left
operands value is moved right by the
number of bits specified by the right
operand.
A >> 2 will give 15 which is 1111
>>> Shift right zero fill operator. The left
operands value is moved right by the
number of bits specified by the right
operand and shifted values are filled up with
zeros.
A >>>2 will give 15 which is 0000 1111
The Logical Operators:
The following table lists the logical operators:
Assume boolean variables A holds true and variable B holds false then:
!perator )escription 7xamp$e
&& Called Logical AND operator. If both the
operands are non zero then then condition
becomes true.
(A && B) is false.
|| Called Logical OR Operator. If any of the two
operands are non zero then then condition
becomes true.
(A || B) is true.
! Called Logical NOT Operator. Use to reverses
the logical state of its operand. If a
condition is true then Logical NOT operator
will make false.
!(A && B) is true.
The Assignment Operators:
There are following assignment operators supported by Java language:
!perator )escription 7xamp$e
= Simple assignment operator, Assigns
values from right side operands to left
C = A + B will assigne value of A + B into C
MAT SOFT
JAVA REFERENCE GUIDE
36
side operand
+= Add AND assignment operator, It adds
right operand to the left operand and
assign the result to left operand
C += A is equivalent to C = C + A
-= Subtract AND assignment operator, It
subtracts right operand from the left
operand and assign the result to left
operand
C -= A is equivalent to C = C - A
*= Multiply AND assignment operator, It
multiplies right operand with the left
operand and assign the result to left
operand
C *= A is equivalent to C = C * A
/= Divide AND assignment operator, It
divides left operand with the right
operand and assign the result to left
operand
C /= A is equivalent to C = C / A
%= Modulus AND assignment operator, It
takes modulus using two operands and
assign the result to left operand
C %= A is equivalent to C = C % A
<<= Left shift AND assignment operator C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator C &= 2 is same as C = C & 2
^= bitwise exclusive OR and assignment
operator
C ^= 2 is same as C = C ^ 2
|= bitwise inclusive OR and assignment
operator
C |= 2 is same as C = C | 2
Misc Operators
There are few other operators supported by Java Language.
MAT SOFT
JAVA REFERENCE GUIDE
37
Conditional Operator ( ? : ):
Conditional operator is also known as the ternary operator. This operator consists of three operands
and is used to evaluate boolean expressions. The goal of the operator is to decide which value should
be assigned to the variable. The operator is written as :
variabl! : 9 $!:pr!ssion( S valu! if tru! - valu! if fals!
Following is the example:
public class T!st {
public static voi# main$%tring args&'({
int a 2 b*
a 9 CE*
b 9 $a 99 C( S @E- DE*
%yst!m.out.println$ )Balu! of b is - ) > b (*
b 9 $a 99 CE( S @E- DE*
%yst!m.out.println$ )Balu! of b is - ) > b (*
+
+
This would produce following result:
Balu! of b is - DE
Balu! of b is - @E
instanceOf Operator:
This operator is used only for object reference variables. The operator checks whether the object is of
a particular type(class type or interface type). instanceOf operator is wriiten as:
$ ?bj!ct r!f!r!nc! variabl! ( instanc!?f $class/int!rfac! typ!(
If the object referred by the variable on the left side of the operator passes the IS-A check for the
class/interface type on the right side then the result will be true. Following is the example:
%tring nam! 9 9 'Jam!s'*
bool!an r!sult 9 nam! instanc!?f %tring*
// This will r!turn tru! sinc! nam! is typ! of %tring
This operator will still return true if the object being compared is the assignment compatible with the
type on the right. Following is one more example:
class B!hicl! {+
public class ,ar !:t!n#s B!hicl! {
MAT SOFT
JAVA REFERENCE GUIDE
38
public static voi# main$%tring args&'({
B!hicl! a 9 n!w ,ar$(*
bool!an r!sult 9 a instanc!of ,ar*
%yst!m.out.println$ r!sult(*
+
+
This would produce following result:
tru!
Precedence of Java Operators:
Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator:
For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher precedenace
than + so it first get multiplied with 3*2 and then adds into 7.
Here operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedenace operators will be evaluated first.
Category !perator %ssociativity
Postfix () [] . (dot operator) Left to right
Unary ++ - - ! ~ Right to left
Multiplicative * / % Left to right
Additive + - Left to right
Shift >> >>> << Left to right
Relational > >= < <= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
MAT SOFT
JAVA REFERENCE GUIDE
39
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left
Comma , Left to right
FLOW CONTROL
DECESSION MAKIN STATEMENTS
There are two types of decision making statements in Java. They are:
if statements
switch statements
The if Statement:
An if statement consists of a Boolean expression followed by one or more statements.
Syntax:
The syntax of an if statement is:
if$Lool!anT!:pr!ssion(
{
//%tat!m!nts will !:!cut! if th! Lool!an !:pr!ssion is tru!
+
If the boolean expression evaluates to true then the block of code inside the if statement will be
executed. If not the first set of code after the end of the if statement(after the closing curly brace) will
be executed.
Example:
public class T!st {
public static voi# main$%tring args&'({
int : 9 CE*
MAT SOFT
JAVA REFERENCE GUIDE
40
if$ : N @E ({
%yst!m.out.print$)This is if stat!m!nt)(*
+
+
+
This would produce following result:
This is if stat!m!nt
The if...else Statement:
An if statement can be followed by an optional else statement, which executes when the Boolean
expression is false.
Syntax:
The syntax of a if...else is:
if$Lool!anT!:pr!ssion({
//3:!cut!s wh!n th! Lool!an !:pr!ssion is tru!
+!ls!{
//3:!cut!s wh!n th! Lool!an !:pr!ssion is fals!
+
Example:
public class T!st {
public static voi# main$%tring args&'({
int : 9 DE*
if$ : N @E ({
%yst!m.out.print$)This is if stat!m!nt)(*
+!ls!{
%yst!m.out.print$)This is !ls! stat!m!nt)(*
+
+
+
This would produce following result:
This is !ls! stat!m!nt
The if...else if...else Statement:
MAT SOFT
JAVA REFERENCE GUIDE
41
An if statement can be followed by an optional else i$...else statement, which is very usefull to test
various conditions using single if...else if statement.
When using if , else if , else statements there are few points to keep in mind.
An if can have zero or one else's and it must come after any else if's.
An if can have zero to many else if's and they must come before the else.
Once an else if succeeds, none of he remaining else if's or else's will be tested.
Syntax:
The syntax of a if...else is:
if$Lool!anT!:pr!ssion C({
//3:!cut!s wh!n th! Lool!an !:pr!ssion C is tru!
+!ls! if$Lool!anT!:pr!ssion @({
//3:!cut!s wh!n th! Lool!an !:pr!ssion @ is tru!
+!ls! if$Lool!anT!:pr!ssion D({
//3:!cut!s wh!n th! Lool!an !:pr!ssion D is tru!
+!ls! {
//3:!cut!s wh!n th! non! of th! abov! con#ition is tru!.
+
Example:
public class T!st {
public static voi# main$%tring args&'({
int : 9 DE*
if$ : 99 CE ({
%yst!m.out.print$)Balu! of R is CE)(*
+!ls! if$ : 99 @E ({
%yst!m.out.print$)Balu! of R is @E)(*
+!ls! if$ : 99 DE ({
%yst!m.out.print$)Balu! of R is DE)(*
+!ls!{
%yst!m.out.print$)This is !ls! stat!m!nt)(*
+
+
+
This would produce following result:
Balu! of R is DE
Nested if...else Statement:
MAT SOFT
JAVA REFERENCE GUIDE
42
It is always legal to nest if-else statements, which means you can use one if or else if statement inside
another if or else if statement.
Syntax:
The syntax for a nested if...else is as follows:
if$Lool!anT!:pr!ssion C({
//3:!cut!s wh!n th! Lool!an !:pr!ssion C is tru!
if$Lool!anT!:pr!ssion @({
//3:!cut!s wh!n th! Lool!an !:pr!ssion @ is tru!
+
+
You can nest else i$...else in the similar way as we have nested i$ statement.
Example:
public class T!st {
public static voi# main$%tring args&'({
int : 9 DE*
int y 9 CE*
if$ : 99 DE ({
if$ y 99 CE ({
%yst!m.out.print$)R 9 DE an# A 9 CE)(*
+
+
+
This would produce following result:
R 9 DE an# A 9 CE
The switch Statement:
A s0itch statement allows a variable to be tested for equality against a list of values. Each value is
called a case, and the variable being switched on is checked for each case.
Syntax:
The syntax of enhanced for loop is:
switch$!:pr!ssion({
cas! valu! -
//%tat!m!nts
br!a<* //optional
MAT SOFT
JAVA REFERENCE GUIDE
43
cas! valu! -
//%tat!m!nts
br!a<* //optional
//Aou can hav! any numb!r of cas! stat!m!nts.
#!fault - //?ptional
//%tat!m!nts
+
The following rules apply to a switch statement:
The variable used in a switch statement can only be a byte, short, int, or char.
You can have any number of case statements within a switch. Each case is followed by the
value to be compared to and a colon.
The value for a case must be the same data type as the variable in the switch, and it must be
a constant or a literal.
When the variable being switched on is equal to a case, the statements following that case will
execute until a brea( statement is reached.
When a brea( statement is reached, the switch terminates, and the flow of control jumps to
the next line following the switch statement.
Not every case needs to contain a break. If no break appears, the flow of control will $all
through to subsequent cases until a break is reached.
A s0itch statement can have an optional default case, which must appear at the end of the
switch. The default case can be used for performing a task when none of the cases is true. No
break is needed in the default case.
Example:
public class T!st {
public static voi# main$%tring args&'({
char gra#! 9 args&E'.char0t$E(*
switch$gra#!(
{
cas! '0' -
%yst!m.out.println$)3:c!ll!ntG)(*
br!a<*
cas! 'L' -
cas! ',' -
%yst!m.out.println$)"!ll #on!)(*
br!a<*
cas! '4' -
%yst!m.out.println$)Aou pass!#)(*
cas! 'F' -
%yst!m.out.println$)L!tt!r try again)(*
br!a<*
#!fault -
MAT SOFT
JAVA REFERENCE GUIDE
44
%yst!m.out.println$)6nvali# gra#!)(*
+
%yst!m.out.println$)Aour gra#! is ) > gra#!(*
+
+
Compile and run above program using various command line arguments. This would produce following
result:
U java T!st a
6nvali# gra#!
Aour gra#! is a a
U java T!st 0
3:c!ll!ntG
Aour gra#! is a 0
U java T!st ,
"!ll #on!
Aour gra#! is a ,
U
CONDITIONAL LOOP CONTROL
There may be a sitution when we need to execute a block of code several number of times, and is
often referred to as a loop.
Java has very flexible three looping mechanisms. You can use one of the following three loops:
while Loop
do...while Loop
for Loop
As of java 5 the enhanced $or loop was introduced. This is mainly used for Arrays.
The while Loop:
A while loop is a control structure that allows you to repeat a task a certain number of times.
Syntax:
The syntax of a while loop is:
whil!$Lool!anT!:pr!ssion(
MAT SOFT
JAVA REFERENCE GUIDE
45
{
//%tat!m!nts
+
When executing, if the boolean1expression result is true then the actions inside the loop will be
executed. This will continue as long as the expression result is true.
Here key point of the 0hile loop is that the loop might not ever run. When the expression is tested and
the result is false, the loop body will be skipped and the first statement after the while loop will be
executed.
Example:
public class T!st {
public static voi# main$%tring args&'({
int :9 CE*
whil!$ : N @E ({
%yst!m.out.print$)valu! of : - ) > : (*
:>>*
%yst!m.out.print$)On)(*
+
+
+
This would produce following result:
valu! of : - CE
valu! of : - CC
valu! of : - C@
valu! of : - CD
valu! of : - CF
valu! of : - CH
valu! of : - CM
valu! of : - CI
valu! of : - CJ
valu! of : - CK
The do...while Loop:
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at
least one time.
Syntax:
The syntax of a do...while loop is:
MAT SOFT
JAVA REFERENCE GUIDE
46
#o
{
//%tat!m!nts
+whil!$Lool!anT!:pr!ssion(*
Notice that the Boolean expression appears at the end of the loop, so the statements in the loop
execute once before the Boolean is tested.
If the Boolean expression is true, the flow of control jumps back up to do, and the statements in the
loop execute again. This process repeats until the Boolean expression is false.
Example:
public class T!st {
public static voi# main$%tring args&'({
int :9 CE*
#o{
%yst!m.out.print$)valu! of : - ) > : (*
:>>*
%yst!m.out.print$)On)(*
+whil!$ : N @E (*
+
+
This would produce following result:
valu! of : - CE
valu! of : - CC
valu! of : - C@
valu! of : - CD
valu! of : - CF
valu! of : - CH
valu! of : - CM
valu! of : - CI
valu! of : - CJ
valu! of : - CK
The for Loop:
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.
A for loop is useful when you know how many times a task is to be repeated.
MAT SOFT
JAVA REFERENCE GUIDE
47
Syntax:
The syntax of a for loop is:
for$initiali/ation* Lool!anT!:pr!ssion* up#at!(
{
//%tat!m!nts
+
Here is the flow of control in a for loop:
1. The initialization step is executed first, and only once. This step allows you to declare and
initialize any loop control variables. You are not required to put a statement here, as long as a
semicolon appears.
2. Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is
false, the body of the loop does not execute and flow of control jumps to the next statement
past the for loop.
3. After the body of the for loop executes, the flow of control jumps back up to the update
statement. This statement allows you to update any loop control variables. This statement can
be left blank, as long as a semicolon appears after the Boolean expression.
4. The Boolean expression is now evaluated again. If it is true, the loop executes and the process
repeats itself (body of loop, then update step,then Boolean expression). After the Boolean
expression is false, the for loop terminates.
Example:
public class T!st {
public static voi# main$%tring args&'({
for$int : 9 CE* : N @E* : 9 :>C({
%yst!m.out.print$)valu! of : - ) > : (*
%yst!m.out.print$)On)(*
+
+
+
This would produce following result:
valu! of : - CE
valu! of : - CC
valu! of : - C@
valu! of : - CD
valu! of : - CF
valu! of : - CH
valu! of : - CM
valu! of : - CI
valu! of : - CJ
valu! of : - CK
MAT SOFT
JAVA REFERENCE GUIDE
48
Enhanced for loop in Java:
As of java 5 the enhanced for loop was introduced. This is mainly used for Arrays.
Syntax:
The syntax of enhanced for loop is:
for$#!claration - !:pr!ssion(
{
//%tat!m!nts
+
)ec$aration . The newly declared block variable, which is of a type compatible with the
elements of the array you are accessing. The variable will be available within the for block and
its value would be the same as the current array element.
7xpression . This evaluate to the array you need to loop through. The expression can be an
array variable or method call that returns an array.
Example:
public class T!st {
public static voi# main$%tring args&'({
int &' numb!rs 9 {CE2 @E2 DE2 FE2 HE+*
for$int : - numb!rs ({
%yst!m.out.print$ : (*
%yst!m.out.print$)2)(*
+
%yst!m.out.print$)On)(*
%tring &' nam!s 9{)Jam!s)2 )1arry)2 )Tom)2 )1acy)+*
for$ %tring nam! - nam!s ( {
%yst!m.out.print$ nam! (*
%yst!m.out.print$)2)(*
+
+
+
This would produce following result:
CE2@E2DE2FE2HE2
Jam!s21arry2Tom21acy2
The break Keyword:
The brea( keyword is used to stop the entire loop. The break keyword must be used inside any loop or
a switch statement.
MAT SOFT
JAVA REFERENCE GUIDE
49
The break keyword will stop the execution of the innermost loop and start executing the next line of
code after the block.
Syntax:
The syntax of a break is a single statement inside any loop:
br!a<*
Example:
public class T!st {
public static voi# main$%tring args&'({
int &' numb!rs 9 {CE2 @E2 DE2 FE2 HE+*
for$int : - numb!rs ({
if$ : 99 DE ({
br!a<*
+
%yst!m.out.print$ : (*
%yst!m.out.print$)On)(*
+
+
+
This would produce following result:
CE
@E
The continue Keyword:
The continue keyword can be used in any of the loop control structures. It causes the loop to
immediately jump to the next iteration of the loop.
In a for loop, the continue keyword causes flow of control to immediately jump to the update
statement.
In a while loop or do/while loop, flow of control immediately jumps to the Boolean expression.
Syntax:
The syntax of a continue is a single statement inside any loop:
continu!*
MAT SOFT
JAVA REFERENCE GUIDE
50
Example:
public class T!st {
public static voi# main$%tring args&'({
int &' numb!rs 9 {CE2 @E2 DE2 FE2 HE+*
for$int : - numb!rs ({
if$ : 99 DE ({
continu!*
+
%yst!m.out.print$ : (*
%yst!m.out.print$)On)(*
+
+
+
This would produce following result:
CE
@E
FE
HE
)ay 8: 9rapper C$asses : Strings
WRAPPER T!PES
Normally, when we work with Numbers, we use primitive data types such as byte, int, long, double
etc.
MAT SOFT
JAVA REFERENCE GUIDE
51
Example:
int i 9 HEEE*
float gpa 9 CD.MH*
byt! mas< 9 E:af*
However in development we come across situations were we need to use objects instead of primitive
data types. In-order to achieve this Java provides wrapper classes for each primitive data type.
All the wrapper classes ( Integer, Long, Byte, Double, Float, Short) are subclasses of the abstract class
Number.
This wrapping is taken care of by the compiler The process is called boxing. So when a primitive is
used when an object is required the compiler boxes the primitive type in its wrapper class. Similarly
the compiler unboxes the object to a primitive as well. The Nm"er is part of the java.lang package.
Here is an example of boxing and unboxing:
public class T!st{
public static voi# main$%tring args&'({
6nt!g!r : 9 H* // bo:!s int to an 6nt!g!r obj!ct
: 9 : > CE* // unbo:!s th! 6nt!g!r to a int
%yst!m.out.println$:(*
+
+
This would produce following result:
CH
When x is assigned integer values, the compiler boxes the integer because x is integer objects. Later,
x is unboxed so that they can be added as integers.
Number Methods:
Here is the list of the instance methods that all the subclasses of the Number class implement:
MAT SOFT
JAVA REFERENCE GUIDE
52
SN Methods 3ith )escription
1 xxxValue()
Converts the value of this Number object to the xxx data type and returned it.
2 compareTo()
Compares this Number object to the argument.
3 equals()
Determines whether this number object is equal to the argument.
4 valueOf()
Returns an Integer object holding the value of the specified primitive.
5 toString()
Returns a String object representing the value of specified int or Integer.
6 parseInt()
This method is used to get the primitive data type of a certain String.
7 abs()
Returns the absolute value of the argument.
8 ceil()
Returns the smallest integer that is greater than or equal to the argument. Returned as a double.
9 floor()
Returns the largest integer that is less than or equal to the argument. Returned as a double.
10 rint()
Returns the integer that is closest in value to the argument. Returned as a double.
11 round()
Returns the closest long or int, as indicated by the method's return type, to the argument.
12 min()
Returns the smaller of the two arguments.
13 max()
Returns the larger of the two arguments.
14 exp()
Returns the base of the natural logarithms, e, to the power of the argument.
15 log()
MAT SOFT
JAVA REFERENCE GUIDE
53
Returns the natural logarithm of the argument.
16 pow()
Returns the value of the first argument raised to the power of the second argument.
17 sqrt()
Returns the square root of the argument.
18 sin()
Returns the sine of the specified double value.
19 cos()
Returns the cosine of the specified double value.
20 tan()
Returns the tangent of the specified double value.
21 asin()
Returns the arcsine of the specified double value.
22 acos()
Returns the arccosine of the specified double value.
23 atan()
Returns the arctangent of the specified double value.
24 atan2()
Converts rectangular coordinates (x, y) to polar coordinate (r, theta) and returns theta.
25 toDegrees()
Converts the argument to degrees
26 toRadians()
Converts the argument to radians.
27 random()
Returns a random number.
Normally, when we work with characters, we use primitive data types char.
MAT SOFT
JAVA REFERENCE GUIDE
54
Example:
char ch 9 'a'*
// 5nico#! for upp!rcas! 8r!!< om!ga charact!r
char uni,har 9 'OuEDK0'*
// an array of chars
char&' char0rray 9{ 'a'2 'b'2 'c'2 '#'2 '!' +*
However in development we come across situations were we need to use objects instead of primitive
data types. In-order to achieve this Java provides wrapper classe Character for primitive data type
char.
The Character class offers a number of useful class (i.e., static) methods for manipulating characters.
You can create a Character object with the Character constructor:
,haract!r ch 9 n!w ,haract!r$'a'(*
The Java compiler will also create a Character object for you under some circumstances. For example,
if you pass a primitive char into a method that expects an object, the compiler automatically converts
the char to a Character for you. This feature is called autoboxing or unboxing, if the conversion goes
the other way.
Example:
// !r! following primitiv! char 'a'
// is bo:!# into th! ,haract!r obj!ct ch
,haract!r ch 9 'a'*
// !r! primitiv! ':' is bo:!# for m!tho# t!st2
// r!turn is unbo:!# to char 'c'
char c 9 t!st$':'(*
Escape Sequences:
A character preceded by a backslash (\) is an escape sequence and has special meaning to the
compiler.
The newline character (\n) has been used frequently in this material in System.out.println()
statements to advance to the next line after the string is printed.
Following table shows the Java escape sequences:
7scape Se;ence )escription
\t Insert a tab in the text at this point.
MAT SOFT
JAVA REFERENCE GUIDE
55
\b Insert a backspace in the text at this point.
\n Insert a newline in the text at this point.
\r Insert a carriage return in the text at this point.
\f Insert a form feed in the text at this point.
\' Insert a single quote character in the text at this point.
\" Insert a double quote character in the text at this point.
\\ Insert a backslash character in the text at this point.
When an escape sequence is encountered in a print statement, the compiler interprets it accordingly.
Example:
If you want to put quotes within quotes you must use the escape sequence, \", on the interior quotes:
public class T!st{
public static voi# main$%tring args&'({
%yst!m.out.println$)%h! sai# O)!lloGO) to m!.)(*
+
+
This would produce following result:
%h! sai# )!lloG) to m!.
Character Methods:
Here is the list of the important instance methods that all the subclasses of the Character class
implement:
SN Methods 3ith )escription
1 isLetter()
Determines whether the specified char value is a letter.
2 isDigit()
Determines whether the specified char value is a digit.
MAT SOFT
JAVA REFERENCE GUIDE
56
3 isWhitespace()
Determines whether the specified char value is white space.
4 isUpperCase()
Determines whether the specified char value is uppercase.
5 isLowerCase()
Determines whether the specified char value is lowercase.
6 toUpperCase()
Returns the uppercase form of the specified char value.
7 toLowerCase()
Returns the lowercase form of the specified char value.
8 toString()
Returns a String object representing the specified character valuethat is, a one-character string.
For a complete list of methods, please refer to the java.lang.Character API specification.
STRINS
Strings, which are widely used in Java programming, are a sequence of characters. In the Java
programming language, strings are objects. The Java platform provides the String class to create and
manipulate strings.
Creating Strings:
The most direct way to create a string is to write:
%tring gr!!ting 9 )!llo worl#G)*
Whenever it encounters a string literal in your code, the compiler creates a String object with its
valuein this case, "Hello world!'. As with any other object, you can create String objects by using the
new keyword and a constructor. The String class has eleven constructors that allow you to provide the
initial value of the string using different sources, such as an array of characters:
MAT SOFT
JAVA REFERENCE GUIDE
57
public class %tring4!mo{
public static voi# main$%tring args&'({
char&' h!llo0rray 9 { 'h'2 '!'2 'l'2 'l'2 'o'2 '.'+*
%tring h!llo%tring 9 n!w %tring$h!llo0rray(*
%yst!m.out.println$ h!llo%tring (*
+
+
This would produce following result:
!llo
Note: The String class is immutable, so that once it is created a String object cannot be changed. If
there is a necessity to make alot of modifications to Strings of characters then you should use String
Buffer & String Builder Classes.
String Length:
Methods used to obtain information about an object are known as accessor methods. One accessor
method that you can use with strings is the length() method, which returns the number of characters
contained in the string object.
After the following two lines of code have been executed, len equals 17:
public class %tring4!mo{
public static voi# main$%tring args&'({
%tring palin#rom! 9 )4ot saw 6 was To#)*
int l!n 9 palin#rom!.l!ngth$(*
%yst!m.out.println$ )%tring 1!ngth is - ) > l!n (*
+
+
This would produce following result:
%tring 1!ngth is - CI
Concatenating Strings:
The String class includes a method for concatenating two strings:
stringC.concat$string@(*
This returns a new string that is string1 with string2 added to it at the end. You can also use the
concat() method with string literals, as in:
)My nam! is ).concat$)Vara)(*
MAT SOFT
JAVA REFERENCE GUIDE
58
Strings are more commonly concatenated with the + operator, as in:
)!llo2) > ) worl#) > )G)
which results in:
)!llo2 worl#G)
Let us look at the followinge example:
public class %tring4!mo{
public static voi# main$%tring args&'({
%tring stringC 9 )saw 6 was )*
%yst!m.out.println$)4ot ) > stringC > )To#)(*
+
+
This would produce following result:
4ot saw 6 was To#
Creating Format Strings:
You have printf() and format() methods to print output with formatted numbers. The String class has
an equivalent class method, format(), that returns a String object rather than a PrintStream object.
Using String's static format() method allows you to create a formatted string that you can reuse, as
opposed to a one-time print statement. For example, instead of:
%yst!m.out.printf$)Th! valu! of th! float variabl! is ) >
)Wf2 whil! th! valu! of th! int!g!r ) >
)variabl! is W#2 an# th! string ) >
)is Ws)2 floatBar2 intBar2 stringBar(*
you can write:
%tring fs*
fs 9 %tring.format$)Th! valu! of th! float variabl! is ) >
)Wf2 whil! th! valu! of th! int!g!r ) >
)variabl! is W#2 an# th! string ) >
)is Ws)2 floatBar2 intBar2 stringBar(*
%yst!m.out.println$fs(*
String Methods:
Here is the list methods supported by String class:
MAT SOFT
JAVA REFERENCE GUIDE
59
SN Methods 3ith )escription
1 char charAt(int index)
Returns the character at the specified index.
2 int compareTo(Object o)
Compares this String to another Object.
3 int compareTo(String anotherString)
Compares two strings lexicographically.
4 int compareToIgnoreCase(String str)
Compares two strings lexicographically, ignoring case differences.
5 String concat(String str)
Concatenates the specified string to the end of this string.
6 boolean contentEquals(StringBuffer sb)
Returns true if and only if this String represents the same sequence of characters as the specified
StringBuffer.
7 static String copyValueOf(char[] data)
Returns a String that represents the character sequence in the array specified.
8 static String copyValueOf(char[] data, int offset, int count)
Returns a String that represents the character sequence in the array specified.
9 boolean endsWith(String suffix)
Tests if this string ends with the specified suffix.
10 boolean equals(Object anObject)
Compares this string to the specified object.
11 boolean equalsIgnoreCase(String anotherString)
Compares this String to another String, ignoring case considerations.
12 byte getBytes()
Encodes this String into a sequence of bytes using the platform's default charset, storing the
result into a new byte array.
13 byte[] getBytes(String charsetName)
Encodes this String into a sequence of bytes using the named charset, storing the result into a
new byte array.
14 void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Copies characters from this string into the destination character array.
15 int hashCode()
Returns a hash code for this string.
16 int indexOf(int ch)
Returns the index within this string of the first occurrence of the specified character.
17 int indexOf(int ch, int fromIndex)
Returns the index within this string of the first occurrence of the specified character, starting the
search at the specified index.
18 int indexOf(String str)
Returns the index within this string of the first occurrence of the specified substring.
19 int indexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at
MAT SOFT
JAVA REFERENCE GUIDE
60
the specified index.
20 String intern()
Returns a canonical representation for the string object.
21 int lastIndexOf(int ch)
Returns the index within this string of the last occurrence of the specified character.
22 int lastIndexOf(int ch, int fromIndex)
Returns the index within this string of the last occurrence of the specified character, searching
backward starting at the specified index.
23 int lastIndexOf(String str)
Returns the index within this string of the rightmost occurrence of the specified substring.
24 int lastIndexOf(String str, int fromIndex)
Returns the index within this string of the last occurrence of the specified substring, searching
backward starting at the specified index.
25 int length()
Returns the length of this string.
26 boolean matches(String regex)
Tells whether or not this string matches the given regular expression.
27 boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
Tests if two string regions are equal.
28 boolean regionMatches(int toffset, String other, int ooffset, int len)
Tests if two string regions are equal.
29 String replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this string with
newChar.
30 String replaceAll(String regex, String replacement
Replaces each substring of this string that matches the given regular expression with the given
replacement.
31 String replaceFirst(String regex, String replacement)
Replaces the first substring of this string that matches the given regular expression with the
given replacement.
32 String[] split(String regex)
Splits this string around matches of the given regular expression.
33 String[] split(String regex, int limit)
Splits this string around matches of the given regular expression.
34 boolean startsWith(String prefix)
Tests if this string starts with the specified prefix.
35 boolean startsWith(String prefix, int toffset)
Tests if this string starts with the specified prefix beginning a specified index.
36 CharSequence subSequence(int beginIndex, int endIndex)
Returns a new character sequence that is a subsequence of this sequence.
37 String substring(int beginIndex)
Returns a new string that is a substring of this string.
38 String substring(int beginIndex, int endIndex)
MAT SOFT
JAVA REFERENCE GUIDE
61
Returns a new string that is a substring of this string.
39 char[] toCharArray()
Converts this string to a new character array.
40 String toLowerCase()
Converts all of the characters in this String to lower case using the rules of the default locale.
41 String toLowerCase(Locale locale)
Converts all of the characters in this String to lower case using the rules of the given Locale.
42 String toString()
This object (which is already a string!) is itself returned.
43 String toUpperCase()
Converts all of the characters in this String to upper case using the rules of the default locale.
44 String toUpperCase(Locale locale)
Converts all of the characters in this String to upper case using the rules of the given Locale.
45 String trim()
Returns a copy of the string, with leading and trailing whitespace omitted.
46 static String valueOf(primitive data type x)
Returns the string representation of the passed data type argument.
Day 7: OOPS - Polymorphism
Polymorphism is the ability of an object to take on many forms. The most common use of
polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.
Any java object that can pass more than one IS-A test is considered to be polymorphic. In Java, all
java objects are polymorphic since any object will pass the IS-A test for their own type and for the
class Object.
It is important to know that the only possible way to access an object is through a reference variable.
A reference variable can be of only one type. Once declared the type of a reference variable cannot be
changed.
The reference variable can be reassigned to other objects provided that it is not declared final. The
type of the reference variable would determine the methods that it can invoke on the object.
A reference variable can refer to any object of its declared type or any subtype of its declared type. A
reference variable can be declared as a class or interface type.
Example:
Let us look at an example.
public int!rfac! B!g!tarian{+
public class 0nimal{+
public class 4!!r !:t!n#s 0nimal impl!m!nts B!g!tarian{+
MAT SOFT
JAVA REFERENCE GUIDE
62
Now the Deer class is considered to be polymorphic since this has multiple inheritance. Following are
true for the above example:
A Deer IS-A Animal
A Deer IS-A Vegetarian
A Deer IS-A Deer
A Deer IS-A Object
When we apply the reference variable facts to a Deer object reference, the following declarations are
legal:
4!!r # 9 n!w 4!!r$(*
0nimal a 9 #*
B!g!tarian v 9 #*
?bj!ct o 9 #*
All the reference variables d,a,v,o refer to the same Deer object in the heap.
Virtual Methods:
In this section, I will show you how the behavior of overridden methods in Java allows you to take
advantage of polymorphism when designing your classes.
We already have discussed method overriding, where a child class can override a method in its parent.
An overridden method is essentially hidden in the parent class, and is not invoked unless the child
class uses the super keyword within the overriding method.
/* Fil! nam! - 3mploy!!.java */
public class 3mploy!!
{
privat! %tring nam!*
privat! %tring a##r!ss*
privat! int numb!r*
public 3mploy!!$%tring nam!2 %tring a##r!ss2 int numb!r(
{
%yst!m.out.println$),onstructing an 3mploy!!)(*
this.nam! 9 nam!*
this.a##r!ss 9 a##r!ss*
this.numb!r 9 numb!r*
+
public voi# mail,h!c<$(
{
%yst!m.out.println$)Mailing a ch!c< to ) > this.nam!
> ) ) > this.a##r!ss(*
+
public %tring to%tring$(
{
r!turn nam! > ) ) > a##r!ss > ) ) > numb!r*
+
MAT SOFT
JAVA REFERENCE GUIDE
63
public %tring g!t=am!$(
{
r!turn nam!*
+
public %tring g!t0##r!ss$(
{
r!turn a##r!ss*
+
public voi# s!t0##r!ss$%tring n!w0##r!ss(
{
a##r!ss 9 n!w0##r!ss*
+
public int g!t=umb!r$(
{
r!turn numb!r*
+
+
Now suppose we extend Employee class as follows:
/* Fil! nam! - %alary.java */
public class %alary !:t!n#s 3mploy!!
{
privat! #oubl! salary* //0nnual salary
public %alary$%tring nam!2 %tring a##r!ss2 int numb!r2 #oubl!
salary(
{
sup!r$nam!2 a##r!ss2 numb!r(*
s!t%alary$salary(*
+
public voi# mail,h!c<$(
{
%yst!m.out.println$)"ithin mail,h!c< of %alary class )(*
%yst!m.out.println$)Mailing ch!c< to ) > g!t=am!$(
> ) with salary ) > salary(*
+
public #oubl! g!t%alary$(
{
r!turn salary*
+
public voi# s!t%alary$#oubl! n!w%alary(
{
if$n!w%alary .9 E.E(
{
salary 9 n!w%alary*
+
+
public #oubl! comput!Pay$(
{
%yst!m.out.println$),omputing salary pay for ) > g!t=am!$((*
r!turn salary/H@*
+
+
MAT SOFT
JAVA REFERENCE GUIDE
64
Now you study the following program carefully and try to determine its output:
/* Fil! nam! - Birtual4!mo.java */
public class Birtual4!mo
{
public static voi# main$%tring &' args(
{
%alary s 9 n!w %alary$)Moh# Mohtashim)2 )0mb!hta2 5P)2
D2 DMEE.EE(*
3mploy!! ! 9 n!w %alary$)John 0#ams)2 )Loston2 M0)2
@2 @FEE.EE(*
%yst!m.out.println$),all mail,h!c< using
%alary r!f!r!nc! ;;)(*
s.mail,h!c<$(*
%yst!m.out.println$)On ,all mail,h!c< using
3mploy!! r!f!r!nc!;;)(*
!.mail,h!c<$(*
+
+
This would produce following result:
,onstructing an 3mploy!!
,onstructing an 3mploy!!
,all mail,h!c< using %alary r!f!r!nc! ;;
"ithin mail,h!c< of %alary class
Mailing ch!c< to Moh# Mohtashim with salary DMEE.E
,all mail,h!c< using 3mploy!! r!f!r!nc!;;
"ithin mail,h!c< of %alary class
Mailing ch!c< to John 0#ams with salary @FEE.E
Here we instantiate two Salary objects . one using a Salary reference s, and the other using an
Employee reference e.
While invoking s.mailChec(() the compiler sees mailCheck() in the Salary class at compile time, and
the JVM invokes mailCheck() in the Salary class at run time.
Invoking mailCheck() on e is quite different because e is an Employee reference. When the compiler
seese.mailChec((), the compiler sees the mailCheck() method in the Employee class.
Here, at compile time, the compiler used mailCheck() in Employee to validate this statement. At run
time, however, the JVM invokes mailCheck() in the Salary class.
This behavior is referred to as virtual method invocation, and the methods are referred to as virtual
methods. All methods in Java behave in this manner, whereby an overridden method is invoked at run
time, no matter what data type the reference is that was used in the source code at compile time.
MAT SOFT
JAVA REFERENCE GUIDE
65
Day 8: Data Astra!tio" # E"!aps$latio"
DATA ABSTRACTION
Why Use Nested Classes?
There are several compelling reasons for using nested classes, among them:
I" #$ % &%' () *(+#,%**' +-(./#0+ ,*%$$1$ "2%" %-1 (0*' .$13 #0
(01 /*%,14
I" #0,-1%$1$ D%5% A5$"-%,"#(0 %03 2#3#0+ #6/*1610"%"#(0 ()
(."1- ,*%$$4
N1$"13 ,*%$$1$ ,%0 *1%3 "( 6(-1 -1%3%5*1 %03 6%#0"%#0%5*1
,(314
Logical grouping of classesIf a class is useful to only one other class, then it is
logical to embed it in that class and keep the two together. Nesting such "helper
classes" makes their package more streamlined.
Increased encapsulationonsider two top!level classes, " and #, where # needs
access to members of " that would otherwise be declared privat!. #y hiding class #
within class ", "$s members can be declared private and # can access them. In
addition, # itself can be hidden from the outside world.
More readable, maintainable codeNesting small classes within top!level classes
places the code closer to where it is used.
MAT SOFT
JAVA REFERENCE GUIDE
66
Static Nested Classes
"s with class methods and variables, a static nested class is associated with its outer
class. "nd like static class methods, a static nested class cannot refer directly to
instance variables or methods defined in its enclosing class it can use them only
through an ob%ect reference.
Not%: A $"%"#, 01$"13 ,*%$$ #0"1-%,"$ &#"2 "21 #0$"%0,1 61651-$ ()
#"$ (."1- ,*%$$ 7%03 ("21- ,*%$$1$8 9.$" *#:1 %0' ("21- "(/;*1<1* ,*%$$4
I0 1=1,"> % $"%"#, 01$"13 ,*%$$ #$ 512%<#(-%**' % "(/;*1<1* ,*%$$ "2%"
2%$ 5110 01$"13 #0 %0("21- "(/;*1<1* ,*%$$ )(- /%,:%+#0+
,(0<10#10,14
&tatic nested classes are accessed using the enclosing class name:
?ut!r,lass.%tatic=!st!#,lass
'or e(ample, to create an ob%ect for the static nested class, use this synta(:
?ut!r,lass.%tatic=!st!#,lass n!st!#?bj!ct 9
n!w ?ut!r,lass.%tatic=!st!#,lass$(*
Inner Classes
"s with instance methods and variables, an inner class is associated with an instance
of its enclosing class and has direct access to that ob%ect$s methods and fields. "lso,
because an inner class is associated with an instance, it cannot define any static
members itself.
)b%ects that are instances of an inner class e(ist within an instance of the outer class.
onsider the following classes:
class ?ut!r,lass {
...
class 6nn!r,lass {
...
+
+
MAT SOFT
JAVA REFERENCE GUIDE
67
"n instance of 6nn!r,lass can e(ist only within an instance of ?ut!r,lass and has
direct access to the methods and fields of its enclosing instance. The ne(t
figure illustrates this idea.
An Instance of InnerClass Exists Within an Instance of
OuterClass
To instantiate an inner class, you must first instantiate the outer class. Then, create the
inner ob%ect within the outer ob%ect with this synta(:
?ut!r,lass.6nn!r,lass inn!r?bj!ct 9 out!r?bj!ct.n!w 6nn!r,lass$(*
Inner Class Example
To see an inner class in use, let$s first consider an array. In the following e(ample, we
will create an array, fill it with integer values and then output only values of even
indices of the array in ascending order.
The 4ata%tructur! class below consists of:
The 4ata%tructur! outer class, which includes methods to add an integer
onto the array and print out values of even indices of the array.
The 6nn!r3v!n6t!rator inner class, which is similar to a standard
*ava iterator. Iterators are used to step through a data structure and typically
have methods to test for the last element, retrieve the current element, and
move to the ne(t element.
" main method that instantiates a 4ata%tructur! ob%ect +#s, and uses it to fill
the array?f6nts array with integer values +-, ., /, 0, etc.,, then calls
a print3v!nmethod to print out values of even indices of array?f6nts.
public class 4ata%tructur! {
// cr!at! an array
privat! final static int %6V3 9 CH*
MAT SOFT
JAVA REFERENCE GUIDE
68
privat! int&' array?f6nts 9 n!w int&%6V3'*

public 4ata%tructur!$( {
// fill th! array with asc!n#ing int!g!r valu!s
for $int i 9 E* i N %6V3* i>>( {
array?f6nts&i' 9 i*
+
+

public voi# print3v!n$( {
// print out valu!s of !v!n in#ic!s of th! array
6nn!r3v!n6t!rator it!rator 9 this.n!w 6nn!r3v!n6t!rator$(*
whil! $it!rator.has=!:t$(( {
%yst!m.out.println$it!rator.g!t=!:t$( > ) )(*
+
+

// inn!r class impl!m!nts th! 6t!rator patt!rn
privat! class 6nn!r3v!n6t!rator {
// start st!pping through th! array from th! b!ginning
privat! int n!:t 9 E*

public bool!an has=!:t$( {
// ch!c< if a curr!nt !l!m!nt is th! last in th! array
r!turn $n!:t N9 %6V3 ; C(*
+

public int g!t=!:t$( {
// r!cor# a valu! of an !v!n in#!: of th! array
int r!tBalu! 9 array?f6nts&n!:t'*
//g!t th! n!:t !v!n !l!m!nt
n!:t >9 @*
r!turn r!tBalu!*
+
+

public static voi# main$%tring s&'( {
// fill th! array with int!g!r valu!s an# print out only
// valu!s of !v!n in#ic!s
4ata%tructur! #s 9 n!w 4ata%tructur!$(*
#s.print3v!n$(*
+
+
The output is:
E @ F M J CE C@ CF
Note that the 6nn!r3v!n6t!rator class refers directly to the array?f6nts instance
variable of the 4ata%tructur! ob%ect.
Inner classes can be used to implement helper classes like the one shown in the
e(ample above. If you plan on handling user!interface events, you will need to know
MAT SOFT
JAVA REFERENCE GUIDE
69
how to use inner classes because the event!handling mechanism makes e(tensive use
of them.
Local and Anonymous Inner Classes
There are two additional types of inner classes. 1ou can declare an inner class within
the body of a method. &uch a class is known as a local inner class. 1ou can also
declare an inner class within the body of a method without naming it. These classes
are known as anonymous inner classes. 1ou will encounter such classes in advanced
*ava programming.
Modifiers
1ou can use the same modifiers for inner classes that you use for other members of
the outer class. 'or e(ample, you can use the access specifiers privat!, public,
andprot!ct!# to restrict access to inner classes, %ust as you do to other class
members.
ENCAPS?LATION
Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance,
polymorphism, and abstraction.
Encapsulation is the technique of making the fields in a class private and providing access to the fields
via public methods. If a field is declared private, it cannot be accessed by anyone outside the class,
thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data
hiding.
Encapsulation can be described as a protective barrier that prevents the code and data being
randomly accessed by other code defined outside the class. Access to the data and code is tightly
controlled by an interface.
The main benefit of encapsulation is the ability to modify our implemented code without breaking the
code of others who use our code. With this feature Encapsulation gives maintainability, flexibility and
extensibility to our code.
Example:
Let us look at an example that depicts encapsulation:
/* Fil! nam! - 3ncapT!st.java */
public class 3ncapT!st{
privat! %tring nam!*
privat! %tring i#=um*
MAT SOFT
JAVA REFERENCE GUIDE
70
privat! int ag!*
public int g!t0g!$({
r!turn ag!*
+
public %tring g!t=am!$({
r!turn nam!*
+
public %tring g!t6#=um$({
r!turn i#=um*
+
public voi# s!t0g!$ int n!w0g!({
ag! 9 n!w0g!*
+
public voi# s!t=am!$%tring n!w=am!({
nam! 9 n!w=am!*
+
public voi# s!t6#=um$ %tring n!w6#({
i#=um 9 n!w6#*
+
+
The public methods are the access points to this class's fields from the outside java world. Normally
these methods are referred as getters and setters. Therefore any class that wants to access the
variables should access them through these getters and setters.
The variables of the EncapTest class can be access as below::
/* Fil! nam! - 7un3ncap.java */
public class 7un3ncap{
public static voi# main$%tring args&'({
3ncapT!st !ncap 9 n!w 3ncapT!st$(*
!ncap.s!t=am!$)Jam!s)(*
!ncap.s!t0g!$@E(*
!ncap.s!t6#=um$)C@DFDms)(*
%yst!m.out.print$)=am! - ) > !ncap.g!t=am!$(>
) 0g! - )> !ncap.g!t0g!$((*
+
+
This would produce following result:
=am! - Jam!s 0g! - @E
MAT SOFT
JAVA REFERENCE GUIDE
71
Benefts of Encapsulation:
The fields of a class can be made read-only or write-only.
A class can have total control over what is stored in its fields.
The users of a class do not know how the class stores its data. A class can change the data
type of a field, and users of the class do not need to change any of their code.
Day &: IN'ERI(ANCE
Inheritance can be defined as the process where one object acquires the properties of another. With
the use of inheritance the information is made manageable in a hierarchical order.
When we talk about inheritance the most commonly used keyword would
be extends andimp$ements. These words would determine whether one object IS-A type of another.
By using these keywords we can make one object acquire the properties of another object.
IS-A Relationship:
IS-A is a way of saying : This object is a type of that object. Let us see how the extendskeyword is
used to achieve inheritance.
public class 0nimal{
+
public class Mammal !:t!n#s 0nimal{
+
public class 7!ptil! !:t!n#s 0nimal{
+
public class 4og !:t!n#s Mammal{
+
Now based on the above example, In Object Oriented terms following are true:
Animal is the superclass of Mammal class.
Animal is the superclass of Reptile class.
MAT SOFT
JAVA REFERENCE GUIDE
72
Mammal and Reptile are sub classes of Animal class.
Dog is the subclass of both Mammal and Animal classes.
Now if we consider the IS-A relationship we can say:
Mammal IS-A Animal
Reptile IS-A Animal
Dog IS-A Mammal
Hence : Dog IS-A Animal as well
With use of the extends keyword the subclasses will be able to inherit all the properties of the
superclass except for the private properties of the superclass.
We can assure that Mammal is actually an Animal with the use of the instance operator.
Example:
public class 4og !:t!n#s Mammal{
public static voi# main$%tring args&'({
0nimal a 9 n!w 0nimal$(*
Mammal m 9 n!w Mammal$(*
4og # 9 n!w 4og$(*
%yst!m.out.println$m instanc!of 0nimal(*
%yst!m.out.println$# instanc!of Mammal(*
%yst!m.out.println$# instanc!of 0nimal(*
+
+
This would produce following result:
tru!
tru!
tru!
Since we have a good understanding of the extends keyword let us look into how
theimp$ements keyword is used to get the IS-A relationship.
The imp$ements keyword is used by classes by inherit from interfaces. Interfaces can never be
extended by the classes.
Example:
public int!rfac! 0nimal {+
MAT SOFT
JAVA REFERENCE GUIDE
73
public class Mammal impl!m!nts 0nimal{
+
public class 4og !:t!n#s Mammal{
+
The instanceof Keyword:
Let us use the instanceof operator to check determine whether Mammal is actually an Animal, and
dog is actually an Animal
int!rfac! 0nimal{+
class Mammal impl!m!nts 0nimal{+
class 4og !:t!n#s Mammal{
public static voi# main$%tring args&'({
Mammal m 9 n!w Mammal$(*
4og # 9 n!w 4og$(*
%yst!m.out.println$m instanc!of 0nimal(*
%yst!m.out.println$# instanc!of Mammal(*
%yst!m.out.println$# instanc!of 0nimal(*
+
+
This would produce following result:
tru!
tru!
tru!
HAS-A relationship:
These relationships are mainly based on the usage. This determines whether a certain class(%S&
% certain thing. This relationship helps to reduce duplication of code as well as bugs.
Lets us look into an example:
public class B!hicl!{+
public class %p!!#{+
public class Ban !:t!n#s B!hicl!{
privat! %p!!# sp*
+
This shows that class Van HAS-A Speed. By having a separate class for Speed we do not have to put
the entire code that belongs to speed inside the Van class., which makes it possible to reuse the Speed
class in multiple applications.
MAT SOFT
JAVA REFERENCE GUIDE
74
In Object Oriented feature the users do not need to bother about which object is doing the real work.
To achieve this, the Van class hides the implementation details from the users of the Van class. SO
basically what happens is the users would ask the Van class to do a certain action and the Vann class
will either do the work by itself or ask another class to perform the action.
A very important fact to remember is that Java only supports only single inheritance. This means that
a class cannot extend more than one class. Therefore following is illegal:
public class !:t!n#s 0nimal2 Mammal{+
However a class can implement one or more interfaces. This has made Java get rid of the impossibility
of multiple inheritance
OVERRIDIN
If a class inherits a method from its super class, then there is a chance to override the method
provided that it is not marked final.
The benefit of overriding is: ability to define a behavior that's specific to the sub class type. Which
means a subclass can implement a parent calss method based on its requirement.
In object oriented terms, overriding means to override the functionality of any existing method.
Example:
Let us look at an example.
class 0nimal{
public voi# mov!$({
%yst!m.out.println$)0nimals can mov!)(*
+
+
class 4og !:t!n#s 0nimal{
public voi# mov!$({
%yst!m.out.println$)4ogs can wal< an# run)(*
+
+
public class T!st4og{
public static voi# main$%tring args&'({
0nimal a 9 n!w 0nimal$(* // 0nimal r!f!r!nc! an# obj!ct
0nimal b 9 n!w 4og$(* // 0nimal r!f!r!nc! but 4og obj!ct
a.mov!$(*// runs th! m!tho# in 0nimal class
b.mov!$(*//7uns th! m!tho# in 4og class
MAT SOFT
JAVA REFERENCE GUIDE
75
+
+
This would produce following result:
0nimals can mov!
4ogs can wal< an# run
In the above example you can see that the even though " is a type of Animal it runs the move method
in the Dog class. The reason for this is : In compile time the check is made on the reference type.
However in the runtime JVM figures out the object type and would run the method that belongs to that
particular object.
Therefore in the above example, the program will compile properly since Animal class has the method
move. Then at the runtime it runs the method specific for that object.
Consider the following example :
class 0nimal{
public voi# mov!$({
%yst!m.out.println$)0nimals can mov!)(*
+
+
class 4og !:t!n#s 0nimal{
public voi# mov!$({
%yst!m.out.println$)4ogs can wal< an# run)(*
+
public voi# bar<$({
%yst!m.out.println$)4ogs can bar<)(*
+
+
public class T!st4og{
public static voi# main$%tring args&'({
0nimal a 9 n!w 0nimal$(* // 0nimal r!f!r!nc! an# obj!ct
0nimal b 9 n!w 4og$(* // 0nimal r!f!r!nc! but 4og obj!ct
a.mov!$(*// runs th! m!tho# in 0nimal class
b.mov!$(*//7uns th! m!tho# in 4og class
b.bar<$(*
+
+
This would produce following result:
T!st4og.java-DE- cannot fin# symbol
symbol - m!tho# bar<$(
MAT SOFT
JAVA REFERENCE GUIDE
76
location- class 0nimal
b.bar<$(*
Q
This program will throw a compile time error since b's reference type Animal doesn't have a method by
the name of bark.
Rules for method overriding:
The argument list should be exactly the same as that of the overridden method.
The return type should be the same or a subtype of the return type declared in the original
overridden method in the super class.
The access level cannot be more restrictive than the overridden method's access level. For
example: if the super class method is declared public then the overridding method in the sub
class cannot be either private or public. However the access level can be less restrictive than
the overridden method's access level.
Instance methods can be overridden only if they are inherited by the subclass.
A method declared final cannot be overridden.
A method declared static cannot be overridden but can be re-declared.
If a method cannot be inherited then it cannot be overridden.
A subclass within the same package as the instance's superclass can override any superclass
method that is not declared private or final.
A subclass in a different package can only override the non-final methods declared public or
protected.
An overriding method can throw any uncheck exceptions, regardless of whether the overridden
method throws exceptions or not. However the overriding method should not throw checked
exceptions that are new or broader than the ones declared by the overridden method. The
overriding method can throw narrower or fewer exceptions than the overridden method.
Constructors cannot be overridden.
Using the super keyword:
When invoking a superclass version of an overridden method the sper keyword is used.
class 0nimal{
public voi# mov!$({
%yst!m.out.println$)0nimals can mov!)(*
MAT SOFT
JAVA REFERENCE GUIDE
77
+
+
class 4og !:t!n#s 0nimal{
public voi# mov!$({
sup!r.mov!$(* // invo<!s th! sup!r class m!tho#
%yst!m.out.println$)4ogs can wal< an# run)(*
+
+
public class T!st4og{
public static voi# main$%tring args&'({
0nimal b 9 n!w 4og$(* // 0nimal r!f!r!nc! but 4og obj!ct
b.mov!$(*//7uns th! m!tho# in 4og class
+
+
This would produce following result:
0nimals can mov!
4ogs can wal< an# run
Day 10: Abstract Classes & Interfaces
Abstract Classs:
Abstraction refers to the ability to make a class abstract in OOP. An abstract class is one that cannot
be instantiated. All other functionality of the class still exists, and its fields, methods, and constructors
are all accessed in the same manner. You just cannot create an instance of the abstract class.
If a class is abstract and cannot be instantiated, the class does not have much use unless it is
subclassed. This is typically how abstract classes come about during the design phase. A parent class
contains the common functionality of a collection of child classes, but the parent class itself is too
abstract to be used on its own.
Use the a"stract keyword to declare a class abstract. The keyword appears in the class declaration
somewhere before the class keyword.
/* Fil! nam! - 3mploy!!.java */
public abstract class 3mploy!!
MAT SOFT
JAVA REFERENCE GUIDE
78
{
privat! %tring nam!*
privat! %tring a##r!ss*
privat! int numb!r*
public 3mploy!!$%tring nam!2 %tring a##r!ss2 int numb!r(
{
%yst!m.out.println$),onstructing an 3mploy!!)(*
this.nam! 9 nam!*
this.a##r!ss 9 a##r!ss*
this.numb!r 9 numb!r*
+
public #oubl! comput!Pay$(
{
%yst!m.out.println$)6nsi#! 3mploy!! comput!Pay)(*
r!turn E.E*
+
public voi# mail,h!c<$(
{
%yst!m.out.println$)Mailing a ch!c< to ) > this.nam!
> ) ) > this.a##r!ss(*
+
public %tring to%tring$(
{
r!turn nam! > ) ) > a##r!ss > ) ) > numb!r*
+
public %tring g!t=am!$(
{
r!turn nam!*
+
public %tring g!t0##r!ss$(
{
r!turn a##r!ss*
+
public voi# s!t0##r!ss$%tring n!w0##r!ss(
{
a##r!ss 9 n!w0##r!ss*
+
public int g!t=umb!r$(
{
r!turn numb!r*
+
+
Notice that nothing is different in this Employee class. The class is now abstract, but it still has three
fields, seven methods, and one constructor.
Now if you would try as follows:
/* Fil! nam! - 0bstract4!mo.java */
public class 0bstract4!mo
{
public static voi# main$%tring &' args(
{

MAT SOFT
JAVA REFERENCE GUIDE
79
/* Following is not allow!# an# woul# rais! !rror */
3mploy!! ! 9 n!w 3mploy!!$)8!org! ".)2 )ouston2 TR)2 FD(*
%yst!m.out.println$)On ,all mail,h!c< using
3mploy!! r!f!r!nc!;;)(*
!.mail,h!c<$(*
+
+
When you would compile above class then you would get following error:
3mploy!!.java-FM- 3mploy!! is abstract* cannot b! instantiat!#
3mploy!! ! 9 n!w 3mploy!!$)8!org! ".)2 )ouston2 TR)2 FD(*
Q
C !rrorC
Extending Abstract Class:
We can extend Employee class in normal way as follows:
/* Fil! nam! - %alary.java */
public class %alary !:t!n#s 3mploy!!
{
privat! #oubl! salary* //0nnual salary
public %alary$%tring nam!2 %tring a##r!ss2 int numb!r2 #oubl!
salary(
{
sup!r$nam!2 a##r!ss2 numb!r(*
s!t%alary$salary(*
+
public voi# mail,h!c<$(
{
%yst!m.out.println$)"ithin mail,h!c< of %alary class )(*
%yst!m.out.println$)Mailing ch!c< to ) > g!t=am!$(
> ) with salary ) > salary(*
+
public #oubl! g!t%alary$(
{
r!turn salary*
+
public voi# s!t%alary$#oubl! n!w%alary(
{
if$n!w%alary .9 E.E(
{
salary 9 n!w%alary*
+
+
public #oubl! comput!Pay$(
{
MAT SOFT
JAVA REFERENCE GUIDE
80
%yst!m.out.println$),omputing salary pay for ) > g!t=am!$((*
r!turn salary/H@*
+
+
Here we cannot instantiate a new Employee, but if we instantiate a new Salary object, the Salary
object will inherit the three fields and seven methods from Employee.
/* Fil! nam! - 0bstract4!mo.java */
public class 0bstract4!mo
{
public static voi# main$%tring &' args(
{
%alary s 9 n!w %alary$)Moh# Mohtashim)2 )0mb!hta2 5P)2
D2 DMEE.EE(*
%alary ! 9 n!w %alary$)John 0#ams)2 )Loston2 M0)2
@2 @FEE.EE(*
%yst!m.out.println$),all mail,h!c< using
%alary r!f!r!nc! ;;)(*
s.mail,h!c<$(*
%yst!m.out.println$)On ,all mail,h!c< using
3mploy!! r!f!r!nc!;;)(*
!.mail,h!c<$(*
+
+
Abstract Methods:
If you want a class to contain a particular method but you want the actual implementation of that
method to be determined by child classes, you can declare the method in the parent class as abstract.
The abstract keyword is also used to declare a method as abstract.An abstract methods consist of a
method signature, but no method body.
Abstract method would have no definition, and its signature is followed by a semicolon, not curly
braces as follows:
public abstract class 3mploy!!
{
privat! %tring nam!*
privat! %tring a##r!ss*
privat! int numb!r*

public abstract #oubl! comput!Pay$(*
MAT SOFT
JAVA REFERENCE GUIDE
81

//7!main#!r of class #!finition
+
Declaring a method as abstract has two results:
The class must also be declared abstract. If a class contains an abstract method, the class
must be abstract as well.
Any child class must either override the abstract method or declare itself abstract.
A child class that inherits an abstract method must override it. If they do not, they must be
abstract,and any of their children must override it. Eventually, a descendant class has to implement
the abstract method; otherwise, you would have a hierarchy of abstract classes that cannot be
instantiated. If Salary is extending Employee class then it is required to implement computePay()
method as follows:
/* Fil! nam! - %alary.java */
public class %alary !:t!n#s 3mploy!!
{
privat! #oubl! salary* //0nnual salary

public #oubl! comput!Pay$(
{
%yst!m.out.println$),omputing salary pay for ) > g!t=am!$((*
r!turn salary/H@*
+
//7!main#!r of class #!finition
+
INTERFACES
An interface is a collection of abstract methods. A class implements an interface, thereby inheriting
the abstract methods of the interface.
An interface is not a class. Writing an interface is similar to writing a class, but they are two different
concepts. A class describes the attributes and behaviors of an object. An interface contains behaviors
that a class implements.
Unless the class that implements the interface is abstract, all the methods of the interface need to be
defined in the class.
An interface is similar to a class in the following ways:
An interface can contain any number of methods.
An interface is written in a file with a 1#ava extension, with the name of the interface matching
the name of the file.
The bytecode of an interface appears in a 1c$ass file.
MAT SOFT
JAVA REFERENCE GUIDE
82
Interfaces appear in packages, and their corresponding bytecode file must be in a directory
structure that matches the package name.
However, an interface is different from a class in several ways, including:
You cannot instantiate an interface.
An interface does not contain any constructors.
All of the methods in an interface are abstract.
An interface cannot contain instance fields. The only fields that can appear in an interface
must be declared both static and final.
An interface is not extended by a class; it is implemented by a class.
An interface can extend multiple interfaces.
Declaring Interfaces:
The interface keyword is used to declare an interface. Here is a simple example to declare an
interface:
Example:
Let us look at an example that depicts encapsulation:
/* Fil! nam! - =am!?f6nt!rfac!.java */
import java.lang.**
//0ny numb!r of import stat!m!nts
public int!rfac! =am!?f6nt!rfac!
{
//0ny numb!r of final2 static fi!l#s
//0ny numb!r of abstract m!tho# #!clarationsO
+
Interfaces have the following properties:
An interface is implicitly abstract. You do not need to use the a"stract keyword when
declaring an interface.
Each method in an interface is also implicitly abstract, so the abstract keyword is not needed.
Methods in an interface are implicitly public.
Example:
/* Fil! nam! - 0nimal.java */
MAT SOFT
JAVA REFERENCE GUIDE
83
int!rfac! 0nimal {
public voi# !at$(*
public voi# trav!l$(*
+
Implementing Interfaces:
When a class implements an interface, you can think of the class as signing a contract, agreeing to
perform the specific behaviors of the interface. If a class does not perform all the behaviors of the
interface, the class must declare itself as abstract.
Aclass uses the imp$ements keyword to implement an interface. The implements keyword appears in
the class declaration following the extends portion of the declaration.
/* Fil! nam! - Mammal6nt.java */
public class Mammal6nt impl!m!nts 0nimal{
public voi# !at$({
%yst!m.out.println$)Mammal !ats)(*
+
public voi# trav!l$({
%yst!m.out.println$)Mammal trav!ls)(*
+
public int no?f1!gs$({
r!turn E*
+
public static voi# main$%tring args&'({
Mammal6nt m 9 n!w Mammal6nt$(*
m.!at$(*
m.trav!l$(*
+
+
This would produce following result:
Mammal !ats
Mammal trav!ls
When overriding methods defined in interfaces there are several rules to be followed:
Checked exceptions should not be declared on implementation methods other than the ones
declared by the interface method or subclasses of those declared by the interface method.
The signature of the interface method and the same return type or subtype should be
maintained when overriding the methods.
An implementation class itself can be abstract and if so interface methods need not be
implemented.
MAT SOFT
JAVA REFERENCE GUIDE
84
When implementation interfaces there are several rules:
A class can implement more than one interface at a time.
A class can extend only one class, but implement many interface.
An interface can extend another interface, similarly to the way that a class can extend another
class.
Extending Interfaces:
An interface can extend another interface, similarly to the way that a class can extend another class.
The extends keyword is used to extend an interface, and the child interface inherits the methods of
the parent interface.
The following Sports interface is extended by Hockey and Football interfaces.
//Fil!nam!- %ports.java
public int!rfac! %ports
{
public voi# s!tom!T!am$%tring nam!(*
public voi# s!tBisitingT!am$%tring nam!(*
+
//Fil!nam!- Football.java
public int!rfac! Football !:t!n#s %ports
{
public voi# hom!T!am%cor!#$int points(*
public voi# visitingT!am%cor!#$int points(*
public voi# !n#?fXuart!r$int Puart!r(*
+
//Fil!nam!- oc<!y.java
public int!rfac! oc<!y !:t!n#s %ports
{
public voi# hom!8oal%cor!#$(*
public voi# visiting8oal%cor!#$(*
public voi# !n#?fP!rio#$int p!rio#(*
public voi# ov!rtim!P!rio#$int ot(*
+
The Hockey interface has four methods, but it inherits two from Sports; thus, a class that implements
Hockey needs to implement all six methods. Similarly, a class that implements Football needs to define
the three methods from Football and the two methods from Sports.
Extending Multiple Interfaces:
A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces are not
classes, however, and an interface can extend more than one parent interface.
The extends keyword is used once, and the parent interfaces are declared in a comma-separated list.
MAT SOFT
JAVA REFERENCE GUIDE
85
For example, if the Hockey interface extended both Sports and Event, it would be declared as:
public int!rfac! oc<!y !:t!n#s %ports2 3v!nt
Tagging Interfaces:
The most common use of extending interfaces occurs when the parent interface does not contain any
methods. For example, the MouseListener interface in the java.awt.event package extended
java.util.EventListener, which is defined as:
pac<ag! java.util*
public int!rfac! 3v!nt1ist!n!r
{+
An interface with no methods in it is referred to as a tagging interface. There are two basic design
purposes of tagging interfaces:
Creates a common parent: As with the EventListener interface, which is extended by dozens of
other interfaces in the Java API, you can use a tagging interface to create a common parent among a
group of interfaces. For example, when an interface extends EventListener, the JVM knows that this
particular interface is going to be used in an event delegation scenario.
%dds a data type to a c$ass: This situation is where the term tagging comes from. A class that
implements a tagging interface does not need to define any methods (since the interface does not
have any), but the class becomes an interface type through polymorphism.
Day )): Arrays
Java provides a data structure, the array, which stores a fixed-size sequential collection of elements
of the same type. An array is used to store a collection of data, but it is often more useful to think of
an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare
one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to
represent individual variables.
MAT SOFT
JAVA REFERENCE GUIDE
86
This material introduces how to declare array variables, create arrays, and process arrays using
indexed variables.
Declaring Array Variables:
To use an array in a program, you must declare a variable to reference the array, and you must
specify the type of array the variable can reference. Here is the syntax for declaring an array variable:
#ataTyp!&' array7!fBar* // pr!f!rr!# way.
or
#ataTyp! array7!fBar&'* // wor<s but not pr!f!rr!# way.
Note: The style dataType-. array'ef*ar is preferred. The style dataType array'ef*ar-.comes
from the C/C++ language and was adopted in Java to accommodate C/C++ programmers.
Example:
The following code snippets are examples of this syntax:
#oubl!&' my1ist* // pr!f!rr!# way.
or
#oubl! my1ist&'* // wor<s but not pr!f!rr!# way.
Creating Arrays:
You can create an array by using the new operator with the following syntax:
array7!fBar 9 n!w #ataTyp!&array%i/!'*
The above statement does two things:
It creates an array using new dataType[arraySize];
It assigns the reference of the newly created array to the variable arrayRefVar.
Declaring an array variable, creating an array, and assigning the reference of the array to the variable
can be combined in one statement, as shown below:
#ataTyp!&' array7!fBar 9 n!w #ataTyp!&array%i/!'*
Alternatively you can create arrays as follows:
MAT SOFT
JAVA REFERENCE GUIDE
87
#ataTyp!&' array7!fBar 9 {valu!E2 valu!C2 ...2 valu!<+*
The array elements are accessed through the index. Array indices are 0-based; that is, they start
from 0 to array'ef*ar1$ength&4.
Example:
Following statement declares an array variable, myList, creates an array of 10 elements of double
type, and assigns its reference to myList.:
#oubl!&' my1ist 9 n!w #oubl!&CE'*
Following picture represents array myList. Here myList holds ten double values and the indices are
from 0 to 9.
Day 12: Working more with Arrays
Processing Arrays:
When processing array elements, we often use either for loop or foreach loop because all of the
elements in an array are of the same type and the size of the array is known.
MAT SOFT
JAVA REFERENCE GUIDE
88
Example:
Here is a complete example of showing how to create, initialize and process arrays:
public class T!st0rray {
public static voi# main$%tring&' args( {
#oubl!&' my1ist 9 {C.K2 @.K2 D.F2 D.H+*
// Print all th! array !l!m!nts
for $int i 9 E* i N my1ist.l!ngth* i>>( {
%yst!m.out.println$my1ist&i' > ) )(*
+
// %umming all !l!m!nts
#oubl! total 9 E*
for $int i 9 E* i N my1ist.l!ngth* i>>( {
total >9 my1ist&i'*
+
%yst!m.out.println$)Total is ) > total(*
// Fin#ing th! larg!st !l!m!nt
#oubl! ma: 9 my1ist&E'*
for $int i 9 C* i N my1ist.l!ngth* i>>( {
if $my1ist&i' . ma:( ma: 9 my1ist&i'*
+
%yst!m.out.println$)Ma: is ) > ma:(*
+
+
This would produce following result:
C.K
@.K
D.F
D.H
Total is CC.I
Ma: is D.H
The foreach Loops:
JDK 1.5 introduced a new for loop, known as foreach loop or enhanced for loop, which enables you to
traverse the complete array sequentially without using an index variable.
Example:
The following code displays all the elements in the array myList:
public class T!st0rray {
public static voi# main$%tring&' args( {
#oubl!&' my1ist 9 {C.K2 @.K2 D.F2 D.H+*
MAT SOFT
JAVA REFERENCE GUIDE
89
// Print all th! array !l!m!nts
for $#oubl! !l!m!nt- my1ist( {
%yst!m.out.println$!l!m!nt(*
+
+
+
This would produce following result:
C.K
@.K
D.F
D.H
Passing Arrays to Methods:
Just as you can pass primitive type values to methods, you can also pass arrays to methods. For
example, the following method displays the elements in an int array:
public static voi# print0rray$int&' array( {
for $int i 9 E* i N array.l!ngth* i>>( {
%yst!m.out.print$array&i' > ) )(*
+
+
You can invoke it by passing an array. For example, the following statement invokes the printArray
method to display 3, 1, 2, 6, 4, and 2:
print0rray$n!w int&'{D2 C2 @2 M2 F2 @+(*
Returning an Array from a Method:
A method may also return an array. For example, the method shown below returns an array that is the
reversal of another array:
public static int&' r!v!rs!$int&' list( {
int&' r!sult 9 n!w int&list.l!ngth'*
for $int i 9 E* i 9 r!sult.l!ngth ; C*
i N list.l!ngth* i>>2 j;;( {
r!sult&j' 9 list&i'*
+
r!sult r!sult*
+
MAT SOFT
JAVA REFERENCE GUIDE
90
The Arrays Class:
The java.util.Arrays class contains various static methods for sorting and searching arrays, comparing
arrays, and filling array elements. These methods are overloaded for all primitive types.
SN Methods 3ith )escription
1 p"$ic static int "inarySearch,!"#ect-. a< !"#ect =ey/
Searches the specified array of Object ( Byte, Int , double etc) for the specified value using the
binary search algorithm. The array must be sorted prior to making this call. This returns index of
the search key, if it is contained in the list; otherwise, (-(insertion point + 1).
2 p"$ic static "oo$ean e;a$s,$ong-. a< $ong-. a5/
Returns true if the two specified arrays of longs are equal to one another. Two arrays are
considered equal if both arrays contain the same number of elements, and all corresponding pairs
of elements in the two arrays are equal. This returns true if the two arrays are equal. Same
method could be used by all other premitive data types ( Byte, short, Int etc.)
3 p"$ic static void fi$$,int-. a< int va$/
Assigns the specified int value to each element of the specified array of ints. Same method could
be used by all other premitive data types ( Byte, short, Int etc.)
4 p"$ic static void sort,!"#ect-. a/
Sorts the specified array of objects into ascending order, according to the natural ordering of its
elements. Same method could be used by all other premitive data types ( Byte, short, Int etc.)
)ay 45: 7>C7PTI!N (%N)0IN?
An exception is a problem that arises during the execution of a program. An exception can occur for
many different reasons, including the following:
A user has entered invalid data.
A file that needs to be opened cannot be found.
A network connection has been lost in the middle of communications, or the JVM has run out
of memory.
MAT SOFT
JAVA REFERENCE GUIDE
91
Some of these exceptions are caused by user error, others by programmer error, and others by
physical resources that have failed in some manner.
To understand how exception handling works in Java, you need to understand the three categories of
exceptions:
Chec=ed exceptions: A checked exception is an exception that is typically a user error or a
problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but
the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at
the time of compilation.
'ntime exceptions: A runtime exception is an exception that occurs that probably could
have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions
are ignored at the time of compliation.
7rrors: These are not exceptions at all, but problems that arise beyond the control of the user
or the programmer. Errors are typically ignored in your code because you can rarely do
anything about an error. For example, if a stack overflow occurs, an error will arise. They are
also ignored at the time of compilation.
Exception Hierarchy:
All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of
the Throwable class. Other than the exception class there is another subclass called Error which is
derived from the Throwable class.
Errors are not normally trapped form the Java programs. These conditions normally happen in case of
severe failures, which are not handled by the java programs. Errors are generated to indicate errors
generated by the runtime environment. Example : JVM is out of Memory. Normally programs cannot
recover from errors.
The Exception class has two main subclasses : IOException class and RuntimeException Class.
Here is a list of most common checked and unchecked Java's Built-in Exceptions.
MAT SOFT
JAVA REFERENCE GUIDE
92
Exceptions Methods:
Following is the list of important medthods available in the Throwable class.
SN Methods 3ith )escription
1 p"$ic String getMessage,/
Returns a detailed message about the exception that has occurred. This message is initialized in
the Throwable constructor.
2 p"$ic Thro3a"$e getCase,/
Returns the cause of the exception as represented by a Throwable object.
3 p"$ic String toString,/
Returns the name of the class concatenated with the result of getMessage()
4 p"$ic void printStac=Trace,/
Prints the result of toString() along with the stack trace to System.err, the error output stream.
5 p"$ic Stac=Trace7$ement -. getStac=Trace,/
Returns an array containing each element on the stack trace. The element at index 0 represents
the top of the call stack, and the last element in the array represents the method at the bottom
of the call stack.
6 p"$ic Thro3a"$e fi$$InStac=Trace,/
Fills the stack trace of this Throwable object with the current stack trace, adding to any previous
information in the stack trace.
Catching Exceptions:
A method catches an exception using a combination of the try and catch keywords. A try/catch block
is placed around the code that might generate an exception. Code within a try/catch block is referred
to as protected code, and the syntax for using try/catch looks like the following:
try
{
//Prot!ct!# co#!
+catch$3:c!ption=am! !C(
{
//,atch bloc<
+
A catch statement involves declaring the type of exception you are trying to catch. If an exception
occurs in protected code, the catch block (or blocks) that follows the try is checked. If the type of
exception that occurred is listed in a catch block, the exception is passed to the catch block much as
an argument is passed into a method parameter.
MAT SOFT
JAVA REFERENCE GUIDE
93
Example:
The following is an array is declared with 2 elements. Then the code tries to access the 3rd element of
the array which throws an exception.
// Fil! =am! - 3:c!pT!st.java
import java.io.**
public class 3:c!pT!st{
public static voi# main$%tring args&'({
try{
int a&' 9 n!w int&@'*
%yst!m.out.println$)0cc!ss !l!m!nt thr!! -) > a&D'(*
+catch$0rray6n#!:?ut?fLoun#s3:c!ption !({
%yst!m.out.println$)3:c!ption thrown -) > !(*
+
%yst!m.out.println$)?ut of th! bloc<)(*
+
+
This would produce following result:
3:c!ption thrown -java.lang.0rray6n#!:?ut?fLoun#s3:c!ption- D
?ut of th! bloc<
Multiple catch Blocks:
A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the
following:
try
{
//Prot!ct!# co#!
+catch$3:c!ptionTyp!C !C(
{
//,atch bloc<
+catch$3:c!ptionTyp!@ !@(
{
//,atch bloc<
+catch$3:c!ptionTyp!D !D(
{
//,atch bloc<
+
The previous statements demonstrate three catch blocks, but you can have any number of them after
a single try. If an exception occurs in the protected code, the exception is thrown to the first catch
block in the list. If the data type of the exception thrown matches ExceptionType1, it gets caught
there. If not, the exception passes down to the second catch statement. This continues until the
exception either is caught or falls through all catches, in which case the current method stops
execution and the exception is thrown down to the previous method on the call stack.
MAT SOFT
JAVA REFERENCE GUIDE
94
Example:
Here is code segment showing how to use multiple try/catch statements.
try
{
fil! 9 n!w Fil!6nput%tr!am$fil!=am!(*
: 9 $byt!( fil!.r!a#$(*
+catch$6?3:c!ption i(
{
i.print%tac<Trac!$(*
r!turn ;C*
+catch$Fil!=otFoun#3:c!ption f( //=ot vali#G
{
f.print%tac<Trac!$(*
r!turn ;C*
+
The throws/throw Keywords:
If a method does not handle a checked exception, the method must declare it using
the thro3skeyword. The throws keyword appears at the end of a method's signature.
You can throw an exception, either a newly instantiated one or an exception that you just caught, by
using the thro3 keyword. Try to understand the different in throws and throw keywords.
The following method declares that it throws a RemoteException:
import java.io.**
public class class=am!
{
public voi# #!posit$#oubl! amount( throws 7!mot!3:c!ption
{
// M!tho# impl!m!ntation
throw n!w 7!mot!3:c!ption$(*
+
//7!main#!r of class #!finition
+
Amethod can declare that it throws more than one exception, in which case the exceptions are
declared in a list separated by commas. For example, the following method declares that it throws a
RemoteException and an InsufficientFundsException:
import java.io.**
public class class=am!
{
public voi# with#raw$#oubl! amount( throws 7!mot!3:c!ption2
6nsuffici!ntFun#s3:c!ption
{
MAT SOFT
JAVA REFERENCE GUIDE
95
// M!tho# impl!m!ntation
+
//7!main#!r of class #!finition
+
The fnally Keyword
The finally keyword is used to create a block of code that follows a try block. A finally block of code
always executes, whether or not an exception has occurred.
Using a finally block allows you to run any cleanup-type statements that you want to execute, no
matter what happens in the protected code.
A finally block appears at the end of the catch blocks and has the following syntax:
try
{
//Prot!ct!# co#!
+catch$3:c!ptionTyp!C !C(
{
//,atch bloc<
+catch$3:c!ptionTyp!@ !@(
{
//,atch bloc<
+catch$3:c!ptionTyp!D !D(
{
//,atch bloc<
+finally
{
//Th! finally bloc< always !:!cut!s.
+
Example:
public class 3:c!pT!st{
public static voi# main$%tring args&'({
int a&' 9 n!w int&@'*
try{
%yst!m.out.println$)0cc!ss !l!m!nt thr!! -) > a&D'(*
+catch$0rray6n#!:?ut?fLoun#s3:c!ption !({
%yst!m.out.println$)3:c!ption thrown -) > !(*
+
finally{
a&E' 9 M*
%yst!m.out.println$)First !l!m!nt valu!- ) >a&E'(*
%yst!m.out.println$)Th! finally stat!m!nt is !:!cut!#)(*
+
+
+
MAT SOFT
JAVA REFERENCE GUIDE
96
This would produce following result:
3:c!ption thrown -java.lang.0rray6n#!:?ut?fLoun#s3:c!ption- D
First !l!m!nt valu!- M
Th! finally stat!m!nt is !:!cut!#
Note the followings:
A catch clause cannot exist without a try statement.
It is not compulsory to have finally clauses when ever a try/catch block is present.
The try block cannot be present without either catch clause or finally clause.
Any code cannot be present in between the try, catch, finally blocks.
Day 14: User Defned Exceptions
Declaring you own Exception:
You can create your own exceptions in Java. Keep the following points in mind when writing your own
exception classes:
All exceptions must be a child of Throwable.
If you want to write a checked exception that is automatically enforced by the Handle or
Declare Rule, you need to extend the Exception class.
If you want to write a runtime exception, you need to extend the RuntimeException class.
We can define our own Exception class as below:
class My3:c!ption !:t!n#s 3:c!ption{
+
You just need to extend the Exception class to create your own Exception class. These are considered
to be checked exceptions. The following InsufficientFundsException class is a user-defined exception
MAT SOFT
JAVA REFERENCE GUIDE
97
that extends the Exception class, making it a checked exception. An exception class is like any other
class, containing useful fields and methods.
Example:
// Fil! =am! 6nsuffici!ntFun#s3:c!ption.java
import java.io.**
public class 6nsuffici!ntFun#s3:c!ption !:t!n#s 3:c!ption
{
privat! #oubl! amount*
public 6nsuffici!ntFun#s3:c!ption$#oubl! amount(
{
this.amount 9 amount*
+
public #oubl! g!t0mount$(
{
r!turn amount*
+
+
To demonstrate using our user-defined exception, the following CheckingAccount class contains a
withdraw() method that throws an InsufficientFundsException.
// Fil! =am! ,h!c<ing0ccount.java
import java.io.**
public class ,h!c<ing0ccount
{
privat! #oubl! balanc!*
privat! int numb!r*
public ,h!c<ing0ccount$int numb!r(
{
this.numb!r 9 numb!r*
+
public voi# #!posit$#oubl! amount(
{
balanc! >9 amount*
+
public voi# with#raw$#oubl! amount( throws
6nsuffici!ntFun#s3:c!ption
{
if$amount N9 balanc!(
{
balanc! ;9 amount*
+
!ls!
{
#oubl! n!!#s 9 amount ; balanc!*
throw n!w 6nsuffici!ntFun#s3:c!ption$n!!#s(*
+
+
public #oubl! g!tLalanc!$(
MAT SOFT
JAVA REFERENCE GUIDE
98
{
r!turn balanc!*
+
public int g!t=umb!r$(
{
r!turn numb!r*
+
+
The following BankDemo program demonstrates invoking the deposit() and withdraw() methods of
CheckingAccount.
// Fil! =am! Lan<4!mo.java
public class Lan<4!mo
{ public static voi# main$%tring &' args(
{ ,h!c<ing0ccount c 9 n!w ,h!c<ing0ccount$CEC(*
%yst!m.out.println$)4!positing UHEE...)(*
c.#!posit$HEE.EE(*
try
{
%yst!m.out.println$)On"ith#rawing UCEE...)(*
c.with#raw$CEE.EE(*
%yst!m.out.println$)On"ith#rawing UMEE...)(*
c.with#raw$MEE.EE(*
+catch$6nsuffici!ntFun#s3:c!ption !(
{
%yst!m.out.println$)%orry2 but you ar! short U)
> !.g!t0mount$((*
!.print%tac<Trac!$(*
+
++
Compile all the above three files and run BankDemo, this would produce following result:
4!positing UHEE...
"ith#rawing UCEE...
"ith#rawing UMEE...
%orry2 but you ar! short U@EE.E
6nsuffici!ntFun#s3:c!ption
at ,h!c<ing0ccount.with#raw$,h!c<ing0ccount.java-@H(
at Lan<4!mo.main$Lan<4!mo.java-CD(
PACKAES
Packages are used in Java in-order to prevent naming conflicts, to control access, to make
searching/locating and usage of classes, interfaces, enumerations and annotations easier etc.
A Package can be defined as a grouping of related types(classes, interfaces, enumerations and
annotations ) providing access protection and name space management.
MAT SOFT
JAVA REFERENCE GUIDE
99
Some of the existing packages in Java are::
#ava1$ang - bundles the fundamental classes
#ava1io - classes for input , output functions are bundled in this package
Programmers can define their own packages to bundle group of classes/interfaces etc. It is a good
practice to group related classes implemented by you so that a programmers can easily determine
that the classes, interfaces, enumerations, annotations are related.
Since the package creates a new namespace there won't be any name conflicts with names in other
packages. Using packages, it is easier to provide access control and it is also easier to locate the
related classed.
Creating a package:
When creating a package, you should choose a name for the package and put a pac=agestatement
with that name at the top of every source file that contains the classes, interfaces, enumerations, and
annotation types that you want to include in the package.
The pac=age statement should be the first line in the source file. There can be only one package
statement in each source file, and it applies to all types in the file.
If a package statement is not used then the class, interfaces, enumerations, and annotation types will
be put into an unnamed package.
Example:
Let us look at an example that creates a package called anima$s. It is common practice to use
lowercased names of packages to avoid any conflicts with the names of classes, interfaces.
Put an interface in the package animals:
/* Fil! nam! - 0nimal.java */
pac<ag! animals*
int!rfac! 0nimal {
public voi# !at$(*
public voi# trav!l$(*
+
Now put an implementation in the same package animals:
pac<ag! animals*
/* Fil! nam! - Mammal6nt.java */
public class Mammal6nt impl!m!nts 0nimal{
public voi# !at$({
%yst!m.out.println$)Mammal !ats)(*
+
MAT SOFT
JAVA REFERENCE GUIDE
100
public voi# trav!l$({
%yst!m.out.println$)Mammal trav!ls)(*
+
public int no?f1!gs$({
r!turn E*
+
public static voi# main$%tring args&'({
Mammal6nt m 9 n!w Mammal6nt$(*
m.!at$(*
m.trav!l$(*
+
+
Now you compile these two files and put them in a sub-directory called anima$s and try to run as
follows:
U m<#ir animals
U cp 0nimal.class Mammal6nt.class animals
U java animals/Mammal6nt
Mammal !ats
Mammal trav!ls
The import Keyword:
If a class wants to use another class in the same package, the package name does not need to be
used. Classes in the same package find each other without any special syntax.
Example:
Here a class named Boss is added to the payroll package that already contains Employee. The Boss
can then refer to the Employee class without using the payroll prefix, as demonstrated by the
following Boss class.
pac<ag! payroll*
public class Loss
{
public voi# pay3mploy!!$3mploy!! !(
{
!.mail,h!c<$(*
+
+
What happens if Boss is not in the payroll package? The Boss class must then use one of the following
techniques for referring to a class in a different package.
The fully qualified name of the class can be used. For example:
MAT SOFT
JAVA REFERENCE GUIDE
101
payroll.3mploy!!
The package can be imported using the import keyword and the wild card (*). For example:
import payroll.**
The class itself can be imported using the import keyword. For example:
import payroll.3mploy!!*
Note: A class file can contain any number of import statements. The import statements must appear
after the package statement and before the class declaration.
The Directory Structure of Packages:
Two major results occur when a class is placed in a package:
The name of the package becomes a part of the name of the class, as we just discussed in the
previous section.
The name of the package must match the directory structure where the corresponding
bytecode resides.
Here is simple way of managing your files in java:
Put the source code for a class, interface, enumeration, or annotation type in a text file whose name is
the simple name of the type and whose extension is 1#ava. For example:
// Fil! =am! - ,ar.java
pac<ag! v!hicl!*
public class ,ar {
// ,lass impl!m!ntation.
+
Now put the source file in a directory whose name reflects the name of the package to which the class
belongs:
....Ov!hicl!O,ar.java
Now the qualified class name and pathname would be as below:
Class name -> vehicle.Car
Path name -> vehicle\Car.java (in windows)
In general a company uses its reversed Internet domain name for its package names. Example: A
company's Internet domain name is apple.com, then all its package names would start with
com.apple. Each component of the package name corresponds to a subdirectory.
MAT SOFT
JAVA REFERENCE GUIDE
102
Example: The company had a com.apple.computers package that contained a Dell.java source file, it
would be contained in a series of subdirectories like this:
....OcomOappl!Ocomput!rsO4!ll.java
At the time of compilation, the compiler creates a different output file for each class, interface and
enumeration defined in it. The base name of the output file is the name of the type, and its extension
is 1c$ass
For example:
// Fil! =am!- 4!ll.java
pac<ag! com.appl!.comput!rs*
public class 4!ll{

+
class 5ps{

+
Now compile this file as follows using -d option:
Ujavac ;# . 4!ll.java
This would put compiled files as follows:
.OcomOappl!Ocomput!rsO4!ll.class
.OcomOappl!Ocomput!rsO5ps.class
You can import all the classes or interfaces defined in &com&apple&computers& as follows:
import com.appl!.comput!rs.**
Like the .java source files, the compiled .class files should be in a series of directories that reflect the
package name. However, the path to the .class files does not have to be the same as the path to the
.java source files. You can arrange your source and class directories separately, as:
Npath;on!.Osourc!sOcomOappl!Ocomput!rsO4!ll.java
Npath;two.Oclass!sOcomOappl!Ocomput!rsO4!ll.class
By doing this, it is possible to give the classes directory to other programmers without revealing your
sources. You also need to manage source and class files in this manner so that the compiler and the
Java Virtual Machine (JVM) can find all the types your program uses.
MAT SOFT
JAVA REFERENCE GUIDE
103
The full path to the classes directory, <path-two>\classes, is called the class path, and is set with the
CLASSPATH system variable. Both the compiler and the JVM construct the path to your .class files by
adding the package name to the class path.
Say <path-two>\classes is the class path, and the package name is com.apple.computers, then the
compiler and JVM will look for .class files in <path-two>\classes\com\apple\comptuers.
A class path may include several paths. Multiple paths should be separated by a semicolon (Windows)
or colon (Unix). By default, the compiler and the JVM search the current directory and the JAR file
containing the Java platform classes so that these directories are automatically in the class path.
Set CLASSPATH System Variable:
To display the current CLASSPATH variable, use the following commands in Windows and Unix (Bourne
shell):
In Windows -> C:\> set CLASSPATH
In Unix -> % echo $CLASSPATH
To delete the current contents of the CLASSPATH variable, use :
In Windows -> C:\> set CLASSPATH=
In Unix -> % unset CLASSPATH; export CLASSPATH
To set the CLASSPATH variable:
In Windows -> set CLASSPATH=C:\users\jack\java\classes
In Unix -> % CLASSPATH=/home/jack/java/classes; export CLASSPATH
MAT SOFT
JAVA REFERENCE GUIDE
104
Day )*: +U,(I('READING
Java provides built-in support for multithreaded programming. A multithreaded program contains two
or more parts that can run concurrently. Each part of such a program is called a thread, and each
thread defines a separate path of execution.
A multithreading is a specialized form of multitasking. Multitasking threads require less overhead than
multitasking processes.
I need to define another term related to threads: process: A process consists of the memory space
allocated by the operating system that can contain one or more threads. A thread cannot exist on its
own; it must be a part of a process. A process remains running until all of the non-daemon threads
are done executing.
Multithreading enables you to write very efficient programs that make maximum use of the CPU,
because idle time can be kept to a minimum.
Life Cycle of a Thread:
A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and
then dies. Following diagram shows complete life cycle of a thread.
MAT SOFT
JAVA REFERENCE GUIDE
105
Above mentioned stages are explained here:
Ne3: A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread. It is also referred to as a born thread.
'nna"$e: After a newly born thread is started, the thread becomes runnable. A thread in
this state is considered to be executing its task.
9aiting: Sometimes a thread transitions to the waiting state while the thread waits for
another thread to perform a task.A thread transitions back to the runnable state only when
another thread signals the waiting thread to continue executing.
Timed 3aiting: A runnable thread can enter the timed waiting state for a specified interval of
time. A thread in this state transitions back to the runnable state when that time interval
expires or when the event it is waiting for occurs.
Terminated: A runnable thread enters the terminated state when it completes its task or
otherwise terminates.
Thread Priorities:
Every Java thread has a priority that helps the operating system determine the order in which threads
are scheduled.
Java priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a
constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5).
MAT SOFT
JAVA REFERENCE GUIDE
106
Threads with higher priority are more important to a program and should be allocated processor time
before lower-priority threads. However, thread priorities cannot guarantee the order in which threads
execute and very much platform dependentant.
Creating a Thread:
Java defines two ways in which this can be accomplished:
You can implement the Runnable interface.
You can extend the Thread class, itself.
Create Thread by Implementing Runnable:
The easiest way to create a thread is to create a class that implements the 'nna"$e interface.
To implement Runnable, a class need only implement a single method called rn, /, which is declared
like this:
public voi# run$ (
You will define the code that constitutes the new thread inside run() method. It is important to
understand that run() can call other methods, use other classes, and declare variables, just like the
main thread can.
After you create a class that implements Runnable, you will instantiate an object of type Thread from
within that class. Thread defines several constructors. The one that we will use is shown here:
Thr!a#$7unnabl! thr!a#?b2 %tring thr!a#=am!(*
Here threadOb is an instance of a class that implements the Runnable interface and the name of the
new thread is specified by thread+ame.
After the new thread is created, it will not start running until you call its start, / method, which is
declared within Thread. The start( ) method is shown here:
voi# start$ (*
Example:
Here is an example that creates a new thread and starts it running:
// ,r!at! a n!w thr!a#.
class =!wThr!a# impl!m!nts 7unnabl! {
Thr!a# t*
=!wThr!a#$( {
// ,r!at! a n!w2 s!con# thr!a#
t 9 n!w Thr!a#$this2 )4!mo Thr!a#)(*
MAT SOFT
JAVA REFERENCE GUIDE
107
%yst!m.out.println$),hil# thr!a#- ) > t(*
t.start$(* // %tart th! thr!a#
+

// This is th! !ntry point for th! s!con# thr!a#.
public voi# run$( {
try {
for$int i 9 H* i . E* i;;( {
%yst!m.out.println$),hil# Thr!a#- ) > i(*
// 1!t th! thr!a# sl!!p for a whil!.
Thr!a#.sl!!p$HEE(*
+
+ catch $6nt!rrupt!#3:c!ption !( {
%yst!m.out.println$),hil# int!rrupt!#.)(*
+
%yst!m.out.println$)3:iting chil# thr!a#.)(*
+
+
class Thr!a#4!mo {
public static voi# main$%tring args&'( {
n!w =!wThr!a#$(* // cr!at! a n!w thr!a#
try {
for$int i 9 H* i . E* i;;( {
%yst!m.out.println$)Main Thr!a#- ) > i(*
Thr!a#.sl!!p$CEEE(*
+
+ catch $6nt!rrupt!#3:c!ption !( {
%yst!m.out.println$)Main thr!a# int!rrupt!#.)(*
+
%yst!m.out.println$)Main thr!a# !:iting.)(*
+
+
This would produce following result:
,hil# thr!a#- Thr!a#&4!mo Thr!a#2H2main'
Main Thr!a#- H
,hil# Thr!a#- H
,hil# Thr!a#- F
Main Thr!a#- F
,hil# Thr!a#- D
,hil# Thr!a#- @
Main Thr!a#- D
,hil# Thr!a#- C
3:iting chil# thr!a#.
Main Thr!a#- @
Main Thr!a#- C
Main thr!a# !:iting.
MAT SOFT
JAVA REFERENCE GUIDE
108
Create Thread by Extending Thread:
The second way to create a thread is to create a new class that extends Thread, and then to create
an instance of that class.
The extending class must override the rn, / method, which is the entry point for the new thread. It
must also call start, / to begin execution of the new thread.
Example:
Here is the preceding program rewritten to extend Thread:
// ,r!at! a s!con# thr!a# by !:t!n#ing Thr!a#
class =!wThr!a# !:t!n#s Thr!a# {
=!wThr!a#$( {
// ,r!at! a n!w2 s!con# thr!a#
sup!r$)4!mo Thr!a#)(*
%yst!m.out.println$),hil# thr!a#- ) > this(*
start$(* // %tart th! thr!a#
+
// This is th! !ntry point for th! s!con# thr!a#.
public voi# run$( {
try {
for$int i 9 H* i . E* i;;( {
%yst!m.out.println$),hil# Thr!a#- ) > i(*
// 1!t th! thr!a# sl!!p for a whil!.
Thr!a#.sl!!p$HEE(*
+
+ catch $6nt!rrupt!#3:c!ption !( {
%yst!m.out.println$),hil# int!rrupt!#.)(*
+
%yst!m.out.println$)3:iting chil# thr!a#.)(*
+
+
class 3:t!n#Thr!a# {
public static voi# main$%tring args&'( {
n!w =!wThr!a#$(* // cr!at! a n!w thr!a#
try {
for$int i 9 H* i . E* i;;( {
%yst!m.out.println$)Main Thr!a#- ) > i(*
Thr!a#.sl!!p$CEEE(*
+
+ catch $6nt!rrupt!#3:c!ption !( {
%yst!m.out.println$)Main thr!a# int!rrupt!#.)(*
+
%yst!m.out.println$)Main thr!a# !:iting.)(*
+
+
This would produce following result:
MAT SOFT
JAVA REFERENCE GUIDE
109
,hil# thr!a#- Thr!a#&4!mo Thr!a#2H2main'
Main Thr!a#- H
,hil# Thr!a#- H
,hil# Thr!a#- F
Main Thr!a#- F
,hil# Thr!a#- D
,hil# Thr!a#- @
Main Thr!a#- D
,hil# Thr!a#- C
3:iting chil# thr!a#.
Main Thr!a#- @
Main Thr!a#- C
Main thr!a# !:iting.
Thread Methods:
Following is the list of important medthods available in the Thread class.
SN Methods 3ith )escription
1 p"$ic void start,/
Starts the thread in a separate path of execution, then invokes the run() method on this Thread
object.
2 p"$ic void rn,/
If this Thread object was instantiated using a separate Runnable target, the run() method is
invoked on that Runnable object.
3 p"$ic fina$ void setName,String name/
Changes the name of the Thread object. There is also a getName() method for retrieving the
name.
4 p"$ic fina$ void setPriority,int priority/
Sets the priority of this Thread object. The possible values are between 1 and 10.
5 p"$ic fina$ void set)aemon,"oo$ean on/
A parameter of true denotes this Thread as a daemon thread.
6 p"$ic fina$ void #oin,$ong mi$$isec/
The current thread invokes this method on a second thread, causing the current thread to block
until the second thread terminates or the specified number of milliseconds passes.
7 p"$ic void interrpt,/
Interrupts this thread, causing it to continue execution if it was blocked for any reason.
8 p"$ic fina$ "oo$ean is%$ive,/
Returns true if the thread is alive, which is any time after the thread has been started but before
MAT SOFT
JAVA REFERENCE GUIDE
110
it runs to completion.
The previous methods are invoked on a particular Thread object. The following methods in the Thread
class are static. Invoking one of the static methods performs the operation on the currently running
thread
SN Methods 3ith )escription
1 p"$ic static void yie$d,/
Causes the currently running thread to yield to any other threads of the same priority that are
waiting to be scheduled
2 p"$ic static void s$eep,$ong mi$$isec/
Causes the currently running thread to block for at least the specified number of milliseconds
3 p"$ic static "oo$ean ho$ds0oc=,!"#ect x/
Returns true if the current thread holds the lock on the given Object.
4 p"$ic static Thread crrentThread,/
Returns a reference to the currently running thread, which is the thread that invokes this
method.
5 p"$ic static void dmpStac=,/
Prints the stack trace for the currently running thread, which is useful when debugging a
multithreaded application.
Example:
The following ThreadClassDemo program demonstrates some of these methods of the Thread class:
// Fil! =am! - 4isplayM!ssag!.java
// ,r!at! a thr!a# to impl!m!nt 7unnabl!
public class 4isplayM!ssag! impl!m!nts 7unnabl!
{
privat! %tring m!ssag!*
public 4isplayM!ssag!$%tring m!ssag!(
{
this.m!ssag! 9 m!ssag!*
+
public voi# run$(
{
whil!$tru!(
{
%yst!m.out.println$m!ssag!(*
+
+
MAT SOFT
JAVA REFERENCE GUIDE
111
+
// Fil! =am! - 8u!ss0=umb!r.java
// ,r!at! a thr!a# to !:t!nt# Thr!a#
public class 8u!ss0=umb!r !:t!n#s Thr!a#
{
privat! int numb!r*
public 8u!ss0=umb!r$int numb!r(
{
this.numb!r 9 numb!r*
+
public voi# run$(
{
int count!r 9 E*
int gu!ss 9 E*
#o
{
gu!ss 9 $int( $Math.ran#om$( * CEE > C(*
%yst!m.out.println$this.g!t=am!$(
> ) gu!ss!s ) > gu!ss(*
count!r>>*
+whil!$gu!ss G9 numb!r(*
%yst!m.out.println$)** ,orr!ctG ) > this.g!t=am!$(
> ) in ) > count!r > ) gu!ss!s.**)(*
+
+
// Fil! =am! - Thr!a#,lass4!mo.java
public class Thr!a#,lass4!mo
{
public static voi# main$%tring &' args(
{
7unnabl! h!llo 9 n!w 4isplayM!ssag!$)!llo)(*
Thr!a# thr!a#C 9 n!w Thr!a#$h!llo(*
thr!a#C.s!t4a!mon$tru!(*
thr!a#C.s!t=am!$)h!llo)(*
%yst!m.out.println$)%tarting h!llo thr!a#...)(*
thr!a#C.start$(*

7unnabl! by! 9 n!w 4isplayM!ssag!$)8oo#by!)(*
Thr!a# thr!a#@ 9 n!w Thr!a#$h!llo(*
thr!a#@.s!tPriority$Thr!a#.M6=TP76?76TA(*
thr!a#@.s!t4a!mon$tru!(*
%yst!m.out.println$)%tarting goo#by! thr!a#...)(*
thr!a#@.start$(*
%yst!m.out.println$)%tarting thr!a#D...)(*
Thr!a# thr!a#D 9 n!w 8u!ss0=umb!r$@I(*
thr!a#D.start$(*
try
{
thr!a#D.join$(*
+catch$6nt!rrupt!#3:c!ption !(
{
%yst!m.out.println$)Thr!a# int!rrupt!#.)(*
MAT SOFT
JAVA REFERENCE GUIDE
112
+
%yst!m.out.println$)%tarting thr!a#F...)(*
Thr!a# thr!a#F 9 n!w 8u!ss0=umb!r$IH(*

thr!a#F.start$(*
%yst!m.out.println$)main$( is !n#ing...)(*
+
+
This would produce following result. You can try this example again and again and you would get
different result every time.
%tarting h!llo thr!a#...
%tarting goo#by! thr!a#...
!llo
!llo
!llo
!llo
!llo
!llo
!llo
!llo
!llo
Thr!a#;@ gu!ss!s @I
!llo
** ,orr!ctG Thr!a#;@ in CE@ gu!ss!s.**
!llo
%tarting thr!a#F...
!llo
!llo
..........r!maining r!sult pro#uc!#.
THREAD CONTROLLING METHODS
While the suspend( ), resume( ), and stop( ) methods defined by Thread class seem to be a perfectly
reasonable and convenient approach to managing the execution of threads, they must not be used for
new Java programs and obsolete in newer versions of Java.
The following example illustrates how the wait( ) and notify( ) methods that are inherited from Object
can be used to control the execution of a thread.
This example is similar to the program in the previous section. However, the deprecated method calls
have been removed. Let us consider the operation of this program.
The NewThread class contains a boolean instance variable named suspendFlag, which is used to
control the execution of the thread. It is initialized to false by the constructor.
The run( ) method contains a synchronized statement block that checks suspendFlag. If that variable
is true, the wait( ) method is invoked to suspend the execution of the thread. The mysuspend( )
MAT SOFT
JAVA REFERENCE GUIDE
113
method sets suspendFlag to true. The myresume( ) method sets suspendFlag to false and invokes
notify( ) to wake up the thread. Finally, the main( ) method has been modified to invoke the
mysuspend( ) and myresume( ) methods.
Example:
// %usp!n#ing an# r!suming a thr!a# for Java @
class =!wThr!a# impl!m!nts 7unnabl! {
%tring nam!* // nam! of thr!a#
Thr!a# t*
bool!an susp!n#Flag*
=!wThr!a#$%tring thr!a#nam!( {
nam! 9 thr!a#nam!*
t 9 n!w Thr!a#$this2 nam!(*
%yst!m.out.println$)=!w thr!a#- ) > t(*
susp!n#Flag 9 fals!*
t.start$(* // %tart th! thr!a#
+
// This is th! !ntry point for thr!a#.
public voi# run$( {
try {
for$int i 9 CH* i . E* i;;( {
%yst!m.out.println$nam! > )- ) > i(*
Thr!a#.sl!!p$@EE(*
synchroni/!#$this( {
whil!$susp!n#Flag( {
wait$(*
+
+
+
+ catch $6nt!rrupt!#3:c!ption !( {
%yst!m.out.println$nam! > ) int!rrupt!#.)(*
+
%yst!m.out.println$nam! > ) !:iting.)(*
+
voi# mysusp!n#$( {
susp!n#Flag 9 tru!*
+
synchroni/!# voi# myr!sum!$( {
susp!n#Flag 9 fals!*
notify$(*
+
+
class %usp!n#7!sum! {
public static voi# main$%tring args&'( {
=!wThr!a# obC 9 n!w =!wThr!a#$)?n!)(*
=!wThr!a# ob@ 9 n!w =!wThr!a#$)Two)(*
try {
Thr!a#.sl!!p$CEEE(*
obC.mysusp!n#$(*
%yst!m.out.println$)%usp!n#ing thr!a# ?n!)(*
Thr!a#.sl!!p$CEEE(*
obC.myr!sum!$(*
MAT SOFT
JAVA REFERENCE GUIDE
114
%yst!m.out.println$)7!suming thr!a# ?n!)(*
ob@.mysusp!n#$(*
%yst!m.out.println$)%usp!n#ing thr!a# Two)(*
Thr!a#.sl!!p$CEEE(*
ob@.myr!sum!$(*
%yst!m.out.println$)7!suming thr!a# Two)(*
+ catch $6nt!rrupt!#3:c!ption !( {
%yst!m.out.println$)Main thr!a# 6nt!rrupt!#)(*
+
// wait for thr!a#s to finish
try {
%yst!m.out.println$)"aiting for thr!a#s to finish.)(*
obC.t.join$(*
ob@.t.join$(*
+ catch $6nt!rrupt!#3:c!ption !( {
%yst!m.out.println$)Main thr!a# 6nt!rrupt!#)(*
+
%yst!m.out.println$)Main thr!a# !:iting.)(*
+
+
Here is the output produced by the above program:
=!w thr!a#- Thr!a#&?n!2H2main'
?n!- CH
=!w thr!a#- Thr!a#&Two2H2main'
Two- CH
?n!- CF
Two- CF
?n!- CD
Two- CD
?n!- C@
Two- C@
?n!- CC
Two- CC
%usp!n#ing thr!a# ?n!
Two- CE
Two- K
Two- J
Two- I
Two- M
7!suming thr!a# ?n!
%usp!n#ing thr!a# Two
?n!- CE
?n!- K
?n!- J
?n!- I
?n!- M
7!suming thr!a# Two
"aiting for thr!a#s to finish.
Two- H
?n!- H
Two- F
?n!- F
MAT SOFT
JAVA REFERENCE GUIDE
115
Two- D
?n!- D
Two- @
?n!- @
Two- C
?n!- C
Two !:iting.
?n! !:iting.
Main thr!a# !:iting.
Day 16: SYNCHRONIZATION
When two or more threads need access to a shared resource, they need some way to ensure that the
resource will be used by only one thread at a time.
The process by which this synchronization is achieved is called thread synchroni/ation.
The synchronized keyword in Java creates a block of code referred to as a critical section. Every Java
object with a critical section of code gets a lock associated with the object. To enter a critical section, a
thread needs to obtain the corresponding object's lock.
This is the general form of the synchronized statement:
synchroni/!#$obj!ct( {
// stat!m!nts to b! synchroni/!#
+
Here, object is a reference to the object being synchronized. A synchronized block ensures that a call
to a method that is a member of object occurs only after the current thread has successfully entered
object's monitor.
Here is an example, using a synchronized block within the run( ) method:
MAT SOFT
JAVA REFERENCE GUIDE
116
// Fil! =am! - ,allm!.java
// This program us!s a synchroni/!# bloc<.
class ,allm! {
voi# call$%tring msg( {
%yst!m.out.print$)&) > msg(*
try {
Thr!a#.sl!!p$CEEE(*
+ catch $6nt!rrupt!#3:c!ption !( {
%yst!m.out.println$)6nt!rrupt!#)(*
+
%yst!m.out.println$)')(*
+
+
// Fil! =am! - ,all!r.java
class ,all!r impl!m!nts 7unnabl! {
%tring msg*
,allm! targ!t*
Thr!a# t*
public ,all!r$,allm! targ2 %tring s( {
targ!t 9 targ*
msg 9 s*
t 9 n!w Thr!a#$this(*
t.start$(*
+

// synchroni/! calls to call$(
public voi# run$( {
synchroni/!#$targ!t( { // synchroni/!# bloc<
targ!t.call$msg(*
+
+
+
// Fil! =am! - %ynch.java
class %ynch {
public static voi# main$%tring args&'( {
,allm! targ!t 9 n!w ,allm!$(*
,all!r obC 9 n!w ,all!r$targ!t2 )!llo)(*
,all!r ob@ 9 n!w ,all!r$targ!t2 )%ynchroni/!#)(*
,all!r obD 9 n!w ,all!r$targ!t2 )"orl#)(*

// wait for thr!a#s to !n#
try {
obC.t.join$(*
ob@.t.join$(*
obD.t.join$(*
+ catch$6nt!rrupt!#3:c!ption !( {
%yst!m.out.println$)6nt!rrupt!#)(*
+
+
+
This would produce following result:
MAT SOFT
JAVA REFERENCE GUIDE
117
&!llo'
&"orl#'
&%ynchroni/!#'
INTERTHREAD COMMUNICATION
Consider the classic queuing problem, where one thread is producing some data and another is
consuming it. To make the problem more interesting, suppose that the producer has to wait until the
consumer is finished before it generates more data.
In a polling system, the consumer would waste many CPU cycles while it waited for the producer to
produce. Once the producer was finished, it would start polling, wasting more CPU cycles waiting for
the consumer to finish, and so on. Clearly, this situation is undesirable.
To avoid polling, Java includes an elegant interprocess communication mechanism via the following
methods:
3ait, /: This method tells the calling thread to give up the monitor and go to sleep until some
other thread enters the same monitor and calls notify( ).
notify, /: This method wakes up the first thread that called wait( ) on the same object.
notify%$$, /: This method wakes up all the threads that called wait( ) on the same object.c
The highest priority thread will run first.
These methods are implemented as fina$ methods in Object, so all classes have them. All three
methods can be called only from within a synchroni2ed context.
These methods are declared within Object. Various forms of wait( ) exist that allow you to specify a
period of time to wait.
Example:
The following sample program consists of four classes: Q, the queue that you're trying to synchronize;
Producer, the threaded object that is producing queue entries; Consumer, the threaded object that is
consuming queue entries; and PC, the tiny class that creates the single Q, Producer, and Consumer.
The proper way to write this program in Java is to use wait( ) and notify( ) to signal in both directions,
as shown here:
class X {
int n*
bool!an valu!%!t 9 fals!*
synchroni/!# int g!t$( {
if$Gvalu!%!t(
try {
wait$(*
+ catch$6nt!rrupt!#3:c!ption !( {
MAT SOFT
JAVA REFERENCE GUIDE
118
%yst!m.out.println$)6nt!rrupt!#3:c!ption caught)(*
+
%yst!m.out.println$)8ot- ) > n(*
valu!%!t 9 fals!*
notify$(*
r!turn n*
+
synchroni/!# voi# put$int n( {
if$valu!%!t(
try {
wait$(*
+ catch$6nt!rrupt!#3:c!ption !( {
%yst!m.out.println$)6nt!rrupt!#3:c!ption caught)(*
+
this.n 9 n*
valu!%!t 9 tru!*
%yst!m.out.println$)Put- ) > n(*
notify$(*
+
+
class Pro#uc!r impl!m!nts 7unnabl! {
X P*
Pro#uc!r$X P( {
this.P 9 P*
n!w Thr!a#$this2 )Pro#uc!r)(.start$(*
+
public voi# run$( {
int i 9 E*
whil!$tru!( {
P.put$i>>(*
+
+
+
class ,onsum!r impl!m!nts 7unnabl! {
X P*
,onsum!r$X P( {
this.P 9 P*
n!w Thr!a#$this2 ),onsum!r)(.start$(*
+
public voi# run$( {
whil!$tru!( {
P.g!t$(*
+
+
+
class P,Fi:!# {
public static voi# main$%tring args&'( {
X P 9 n!w X$(*
n!w Pro#uc!r$P(*
n!w ,onsum!r$P(*
%yst!m.out.println$)Pr!ss ,ontrol;, to stop.)(*
MAT SOFT
JAVA REFERENCE GUIDE
119
+
+
Inside get( ), wait( ) is called. This causes its execution to suspend until the Producer notifies you that
some data is ready.
When this happens, execution inside get( ) resumes. After the data has been obtained, get( ) calls
notify( ). This tells Producer that it is okay to put more data in the queue.
Inside put( ), wait( ) suspends execution until the Consumer has removed the item from the queue.
When execution resumes, the next item of data is put in the queue, and notify( ) is called. This tells
the Consumer that it should now remove it.
Here is some output from this program, which shows the clean synchronous behavior:
Put- C
8ot- C
Put- @
8ot- @
Put- D
8ot- D
Put- F
8ot- F
Put- H
8ot- H
DEADLOCK
A special type of error that you need to avoid that relates specifically to multitasking is deadlock,
which occurs when two threads have a circular dependency on a pair of synchronized objects.
For example, suppose one thread enters the monitor on object X and another thread enters the
monitor on object Y. If the thread in X tries to call any synchronized method on Y, it will block as
expected. However, if the thread in Y, in turn, tries to call any synchronized method on X, the thread
waits forever, because to access X, it would have to release its own lock on Y so that the first thread
could complete.
Example:
To understand deadlock fully, it is useful to see it in action. The next example creates two classes, A
and B, with methods foo( ) and bar( ), respectively, which pause briefly before trying to call a method
in the other class.
The main class, named Deadlock, creates an A and a B instance, and then starts a second thread to
set up the deadlock condition. The foo( ) and bar( ) methods use sleep( ) as a way to force the
deadlock condition to occur.
class 0 {
synchroni/!# voi# foo$L b( {
MAT SOFT
JAVA REFERENCE GUIDE
120
%tring nam! 9 Thr!a#.curr!ntThr!a#$(.g!t=am!$(*
%yst!m.out.println$nam! > ) !nt!r!# 0.foo)(*
try {
Thr!a#.sl!!p$CEEE(*
+ catch$3:c!ption !( {
%yst!m.out.println$)0 6nt!rrupt!#)(*
+
%yst!m.out.println$nam! > ) trying to call L.last$()(*
b.last$(*
+
synchroni/!# voi# last$( {
%yst!m.out.println$)6nsi#! 0.last)(*
+
+
class L {
synchroni/!# voi# bar$0 a( {
%tring nam! 9 Thr!a#.curr!ntThr!a#$(.g!t=am!$(*
%yst!m.out.println$nam! > ) !nt!r!# L.bar)(*
try {
Thr!a#.sl!!p$CEEE(*
+ catch$3:c!ption !( {
%yst!m.out.println$)L 6nt!rrupt!#)(*
+
%yst!m.out.println$nam! > ) trying to call 0.last$()(*
a.last$(*
+
synchroni/!# voi# last$( {
%yst!m.out.println$)6nsi#! 0.last)(*
+
+
class 4!a#loc< impl!m!nts 7unnabl! {
0 a 9 n!w 0$(*
L b 9 n!w L$(*
4!a#loc<$( {
Thr!a#.curr!ntThr!a#$(.s!t=am!$)MainThr!a#)(*
Thr!a# t 9 n!w Thr!a#$this2 )7acingThr!a#)(*
t.start$(*
a.foo$b(* // g!t loc< on a in this thr!a#.
%yst!m.out.println$)Lac< in main thr!a#)(*
+
public voi# run$( {
b.bar$a(* // g!t loc< on b in oth!r thr!a#.
%yst!m.out.println$)Lac< in oth!r thr!a#)(*
+
public static voi# main$%tring args&'( {
n!w 4!a#loc<$(*
+
+
Here is some output from this program:
MainThr!a# !nt!r!# 0.foo
7acingThr!a# !nt!r!# L.bar
MainThr!a# trying to call L.last$(
MAT SOFT
JAVA REFERENCE GUIDE
121
7acingThr!a# trying to call 0.last$(
Because the program has deadlocked, you need to press CTRL-C to end the program. You can see a
full thread and monitor cache dump by pressing CTRL-BREAK on a PC .
You will see that RacingThread owns the monitor on ", while it is waiting for the monitor on a. At the
same time, MainThread owns a and is waiting to get ". This program will never complete.
As this example illustrates, if your multithreaded program locks up occasionally, deadlock is one of the
first conditions that you should check for.
Using Multithreading:
The key to utilizing multithreading support effectively is to think concurrently rather than serially. For
example, when you have two subsystems within a program that can execute concurrently, make them
individual threads.
With the careful use of multithreading, you can create very efficient programs. A word of caution is in
order, however: If you create too many threads, you can actually degrade the performance of your
program rather than enhance it.
Remember, some overhead is associated with context switching. If you create too many threads, more
CPU time will be spent changing contexts than executing your program!
Day )7: JAVA-U(I, PAC.AGE
DATA STR?CT?RES IN JAVA
The data structures provided by the Java utility package are very powerful and perform a wide range
of functions. These data structures consist of the following interface and classes:
BitSet
Vector
Enumeration
Stack
Dictionary
Hashtable
Properties
All these classes are now legacy and Java-2 has introduced a new framework called Collections
Framework which is discussed in next material:
MAT SOFT
JAVA REFERENCE GUIDE
122
The BitSet
The BitSet class implements a group of bits, or flags, that can be set and cleared individually.
This class is very useful in cases where you need to keep up with a set of boolean values; you just
assign a bit to each value and set or clear it as appropriate.
A BitSet class creates a special type of array that holds bit values. The BitSet array can increase in
size as needed. This makes it similar to a vector of bits.
This is a legacy class but it has been completely re-engineered in Java 2, version 1.4
The BitSet defines two constructors. The first version creates a default object:
Lit%!t$ (
The second version allows you to specify its initial size i.e. the number of bits that it can hold. All bits
are initialized to zero.
Lit%!t$int si/!(
BitSet implements the Cloneable interface and defines the methods listed in table below:
SN Methods 3ith )escription
1 void and,BitSet "itSet/
ANDs the contents of the invoking BitSet object with those specified by bitSet. The result is
placed into the invoking object.
1 void andNot,BitSet "itSet/
For each 1 bit in bitSet, the corresponding bit in the invoking BitSet is cleared.
1 int cardina$ity, /
Returns the number of set bits in the invoking object.
1 void c$ear, /
Zeros all bits.
1 void c$ear,int index/
Zeros the bit specified by index.
1 void c$ear,int startIndex< int endIndex/
Zeros the bits from startIndex to endIndex.1.
1 !"#ect c$one, /
MAT SOFT
JAVA REFERENCE GUIDE
123
Duplicates the invoking BitSet object.
1 "oo$ean e;a$s,!"#ect "itSet/
Returns true if the invoking bit set is equivalent to the one passed in bitSet. Otherwise, the
method returns false.
1 void f$ip,int index/
Reverses the bit specified by index. (
1 void f$ip,int startIndex< int endIndex/
Reverses the bits from startIndex to endIndex.1.
1 "oo$ean get,int index/
Returns the current state of the bit at the specified index.
1 BitSet get,int startIndex< int endIndex/
Returns a BitSet that consists of the bits from startIndex to endIndex.1. The invoking object is
not changed.
1 int hashCode, /
Returns the hash code for the invoking object.
1 "oo$ean intersects,BitSet "itSet/
Returns true if at least one pair of corresponding bits within the invoking object and bitSet are 1.
1 "oo$ean is7mpty, /
Returns true if all bits in the invoking object are zero.
1 int $ength, /
Returns the number of bits required to hold the contents of the invoking BitSet. This value is
determined by the location of the last 1 bit.
1 int nextC$earBit,int startIndex/
Returns the index of the next cleared bit, (that is, the next zero bit), starting from the index
specified by startIndex
1 int nextSetBit,int startIndex/
Returns the index of the next set bit (that is, the next 1 bit), starting from the index specified by
startIndex. If no bit is set, .1 is returned.
1 void or,BitSet "itSet/
ORs the contents of the invoking BitSet object with that specified by bitSet. The result is placed
into the invoking object.
1 void set,int index/
MAT SOFT
JAVA REFERENCE GUIDE
124
Sets the bit specified by index.
1 void set,int index< "oo$ean v/
Sets the bit specified by index to the value passed in v. true sets the bit, false clears the bit.
1 void set,int startIndex< int endIndex/
Sets the bits from startIndex to endIndex.1.
1 void set,int startIndex< int endIndex< "oo$ean v/
Sets the bits from startIndex to endIndex.1, to the value passed in v. true sets the bits, false
clears the bits.
1 int si2e, /
Returns the number of bits in the invoking BitSet object.
1 String toString, /
Returns the string equivalent of the invoking BitSet object.
1 void xor,BitSet "itSet/
XORs the contents of the invoking BitSet object with that specified by bitSet. The result is placed
into the invoking object
Example:
The following program illustrates several of the methods supported by this data structure:
import java.util.Lit%!t*
class Lit%!t4!mo {
public static voi# main$%tring args&'( {
Lit%!t bitsC 9 n!w Lit%!t$CM(*
Lit%!t bits@ 9 n!w Lit%!t$CM(*

// s!t som! bits
for$int i9E* iNCM* i>>( {
if$$iW@( 99 E( bitsC.s!t$i(*
if$$iWH( G9 E( bits@.s!t$i(*
+
%yst!m.out.println$)6nitial patt!rn in bitsC- )(*
%yst!m.out.println$bitsC(*
%yst!m.out.println$)On6nitial patt!rn in bits@- )(*
%yst!m.out.println$bits@(*
// 0=4 bits
bits@.an#$bitsC(*
%yst!m.out.println$)Onbits@ 0=4 bitsC- )(*
%yst!m.out.println$bits@(*
MAT SOFT
JAVA REFERENCE GUIDE
125
// ?7 bits
bits@.or$bitsC(*
%yst!m.out.println$)Onbits@ ?7 bitsC- )(*
%yst!m.out.println$bits@(*
// R?7 bits
bits@.:or$bitsC(*
%yst!m.out.println$)Onbits@ R?7 bitsC- )(*
%yst!m.out.println$bits@(*
+
+
This would produce following result:
6nitial patt!rn in bitsC-
{E2 @2 F2 M2 J2 CE2 C@2 CF+
6nitial patt!rn in bits@-
{C2 @2 D2 F2 M2 I2 J2 K2 CC2 C@2 CD2 CF+
bits@ 0=4 bitsC-
{@2 F2 M2 J2 C@2 CF+
bits@ ?7 bitsC-
{E2 @2 F2 M2 J2 CE2 C@2 CF+
bits@ R?7 bitsC-
{+
The Vector
The Vector class is similar to a traditional Java array, except that it can grow as necessary to
accommodate new elements.
Like an array, elements of a Vector object can be accessed via an index into the vector.
The nice thing about using the Vector class is that you don't have to worry about setting it to a specific
size upon creation; it shrinks and grows automatically when necessary.
Vector implements a dynamic array. It is similar to ArrayList, but with two differences:
Vector is synchronized.
Vector contains many legacy methods that are not part of the collections framework.
Vector proves to be very useful if you don't know the size of the array in advance, or you just need
one that can change sizes over the lifetime of a program.
MAT SOFT
JAVA REFERENCE GUIDE
126
The Vector class supports four constructors. The first form creates a default vector, which has an initial
size of 10:
B!ctor$ (
The second form creates a vector whose initial capacity is specified by size:
B!ctor$int si/!(
The third form creates a vector whose initial capacity is specified by size and whose increment is
specified by incr. The increment specifies the number of elements to allocate each time that a vector is
resized upward:
B!ctor$int si/!2 int incr(
The fourth form creates a vector that contains the elements of collection c:
B!ctor$,oll!ction c(
Apart from the methods inherited from its parent classes, Vector defines following methods:
SN Methods 3ith )escription
1 void add,int index< !"#ect e$ement/
Inserts the specified element at the specified position in this Vector.
2 "oo$ean add,!"#ect o/
Appends the specified element to the end of this Vector.
3 "oo$ean add%$$,Co$$ection c/
Appends all of the elements in the specified Collection to the end of this Vector, in the order that
they are returned by the specified Collection's Iterator.
4 "oo$ean add%$$,int index< Co$$ection c/
Inserts all of the elements in in the specified Collection into this Vector at the specified position.
5 void add7$ement,!"#ect o"#/
Adds the specified component to the end of this vector, increasing its size by one.
6 int capacity,/
Returns the current capacity of this vector.
7 void c$ear,/
Removes all of the elements from this Vector.
MAT SOFT
JAVA REFERENCE GUIDE
127
8 !"#ect c$one,/
Returns a clone of this vector.
9 "oo$ean contains,!"#ect e$em/
Tests if the specified object is a component in this vector.
10 "oo$ean contains%$$,Co$$ection c/
Returns true if this Vector contains all of the elements in the specified Collection.
11 void copyInto,!"#ect-. an%rray/
Copies the components of this vector into the specified array.
12 !"#ect e$ement%t,int index/
Returns the component at the specified index.
13 7nmeration e$ements,/
Returns an enumeration of the components of this vector.
14 void ensreCapacity,int minCapacity/
Increases the capacity of this vector, if necessary, to ensure that it can hold at least the number
of components specified by the minimum capacity argument.
15 "oo$ean e;a$s,!"#ect o/
Compares the specified Object with this Vector for equality.
16 !"#ect first7$ement,/
Returns the first component (the item at index 0) of this vector.
17 !"#ect get,int index/
Returns the element at the specified position in this Vector.
18 int hashCode,/
Returns the hash code value for this Vector.
19 int index!f,!"#ect e$em/
Searches for the first occurence of the given argument, testing for equality using the equals
method.
20 int index!f,!"#ect e$em< int index/
Searches for the first occurence of the given argument, beginning the search at index, and
testing for equality using the equals method.
21 void insert7$ement%t,!"#ect o"#< int index/
Inserts the specified object as a component in this vector at the specified index.
MAT SOFT
JAVA REFERENCE GUIDE
128
22 "oo$ean is7mpty,/
Tests if this vector has no components.
23 !"#ect $ast7$ement,/
Returns the last component of the vector.
24 int $astIndex!f,!"#ect e$em/
Returns the index of the last occurrence of the specified object in this vector.
25 int $astIndex!f,!"#ect e$em< int index/
Searches backwards for the specified object, starting from the specified index, and returns an
index to it.
26 !"#ect remove,int index/
Removes the element at the specified position in this Vector.
27 "oo$ean remove,!"#ect o/
Removes the first occurrence of the specified element in this Vector If the Vector does not contain
the element, it is unchanged.
28 "oo$ean remove%$$,Co$$ection c/
Removes from this Vector all of its elements that are contained in the specified Collection.
29 void remove%$$7$ements,/
Removes all components from this vector and sets its size to zero.
30 "oo$ean remove7$ement,!"#ect o"#/
Removes the first (lowest-indexed) occurrence of the argument from this vector.
31 void remove7$ement%t,int index/
removeElementAt(int index)
32 protected void remove'ange,int fromIndex< int toIndex/
Removes from this List all of the elements whose index is between fromIndex, inclusive and
toIndex, exclusive.
33 "oo$ean retain%$$,Co$$ection c/
Retains only the elements in this Vector that are contained in the specified Collection.
34 !"#ect set,int index< !"#ect e$ement/
Replaces the element at the specified position in this Vector with the specified element.
35 void set7$ement%t,!"#ect o"#< int index/
Sets the component at the specified index of this vector to be the specified object.
MAT SOFT
JAVA REFERENCE GUIDE
129
36 void setSi2e,int ne3Si2e/
Sets the size of this vector.
37 int si2e,/
Returns the number of components in this vector.
38 0ist s"0ist,int fromIndex< int toIndex/
Returns a view of the portion of this List between fromIndex, inclusive, and toIndex, exclusive.
39 !"#ect-. to%rray,/
Returns an array containing all of the elements in this Vector in the correct order.
40 !"#ect-. to%rray,!"#ect-. a/
Returns an array containing all of the elements in this Vector in the correct order; the runtime
type of the returned array is that of the specified array.
41 String toString,/
Returns a string representation of this Vector, containing the String representation of each
element.
42 void trimToSi2e,/
Trims the capacity of this vector to be the vector's current size.
Example:
The following program illustrates several of the methods supported by this collection:
import java.util.**
class B!ctor4!mo {
public static voi# main$%tring args&'( {
// initial si/! is D2 incr!m!nt is @
B!ctor v 9 n!w B!ctor$D2 @(*
%yst!m.out.println$)6nitial si/!- ) > v.si/!$((*
%yst!m.out.println$)6nitial capacity- ) >
v.capacity$((*
v.a##3l!m!nt$n!w 6nt!g!r$C((*
v.a##3l!m!nt$n!w 6nt!g!r$@((*
v.a##3l!m!nt$n!w 6nt!g!r$D((*
v.a##3l!m!nt$n!w 6nt!g!r$F((*
%yst!m.out.println$),apacity aft!r four a##itions- ) >
v.capacity$((*
v.a##3l!m!nt$n!w 4oubl!$H.FH((*
%yst!m.out.println$),urr!nt capacity- ) >
v.capacity$((*
v.a##3l!m!nt$n!w 4oubl!$M.EJ((*
v.a##3l!m!nt$n!w 6nt!g!r$I((*
%yst!m.out.println$),urr!nt capacity- ) >
MAT SOFT
JAVA REFERENCE GUIDE
130
v.capacity$((*
v.a##3l!m!nt$n!w Float$K.F((*
v.a##3l!m!nt$n!w 6nt!g!r$CE((*
%yst!m.out.println$),urr!nt capacity- ) >
v.capacity$((*
v.a##3l!m!nt$n!w 6nt!g!r$CC((*
v.a##3l!m!nt$n!w 6nt!g!r$C@((*
%yst!m.out.println$)First !l!m!nt- ) >
$6nt!g!r(v.first3l!m!nt$((*
%yst!m.out.println$)1ast !l!m!nt- ) >
$6nt!g!r(v.last3l!m!nt$((*
if$v.contains$n!w 6nt!g!r$D(((
%yst!m.out.println$)B!ctor contains D.)(*
// !num!rat! th! !l!m!nts in th! v!ctor.
3num!ration v3num 9 v.!l!m!nts$(*
%yst!m.out.println$)On3l!m!nts in v!ctor-)(*
whil!$v3num.hasMor!3l!m!nts$((
%yst!m.out.print$v3num.n!:t3l!m!nt$( > ) )(*
%yst!m.out.println$(*
+
+
This would produce following result:
6nitial si/!- E
6nitial capacity- D
,apacity aft!r four a##itions- H
,urr!nt capacity- H
,urr!nt capacity- I
,urr!nt capacity- K
First !l!m!nt- C
1ast !l!m!nt- C@
B!ctor contains D.
3l!m!nts in v!ctor-
C @ D F H.FH M.EJ I K.F CE CC C@
The Enumeration:
The Enumeration interface isn't itself a data structure, but it is very important within the context of
other data structures. The Enumeration interface defines a means to retrieve successive elements
from a data structure.
For example, Enumeration defines a method called nextElement that is used to get the next element
in a data structure that contains multiple elements.
The Enumeration interface defines the methods by which you can enumerate (obtain one at a time)
the elements in a collection of objects.
MAT SOFT
JAVA REFERENCE GUIDE
131
This legacy interface has been superceded by Iterator. Although not deprecated, Enumeration is
considered obsolete for new code. However, it is used by several methods defined by the legacy
classes such as Vector and Properties, is used by several other API classes, and is currently in
widespread use in application code.
The methods declared by Enumeration are summarized in the following table:
SN Methods 3ith )escription
1 "oo$ean hasMore7$ements, /
When implemented, it must return true while there are still more elements to extract, and false
when all the elements have been enumerated.
2 !"#ect next7$ement, /
This returns the next object in the enumeration as a generic Object reference.
Example:
Following is the example showing usage of Enumeration.
import java.util.B!ctor*
import java.util.3num!ration*
public class 3num!rationT!st!r {
public static voi# main$%tring args&'( {
3num!ration #ays*
B!ctor #ay=am!s 9 n!w B!ctor$(*
#ay=am!s.a##$)%un#ay)(*
#ay=am!s.a##$)Mon#ay)(*
#ay=am!s.a##$)Tu!s#ay)(*
#ay=am!s.a##$)"!#n!s#ay)(*
#ay=am!s.a##$)Thurs#ay)(*
#ay=am!s.a##$)Fri#ay)(*
#ay=am!s.a##$)%atur#ay)+*
#ays 9 #ay=am!s.!l!m!nts$(*
whil! $#ays.hasMor!3l!m!nts$(({
%yst!m.out.println$#ays.n!:t3l!m!nt$((*
+
+
+
This would produce following result:
%un#ay
Mon#ay
Tu!s#ay
"!#n!s#ay
Thurs#ay
Fri#ay
MAT SOFT
JAVA REFERENCE GUIDE
132
%atur#ay
The Stack
The Stack class implements a last-in-first-out (LIFO) stack of elements.
You can think of a stack literally as a vertical stack of objects; when you add a new element, it gets
stacked on top of the others.
When you pull an element off the stack, it comes off the top. In other words, the last element you
added to the stack is the first one to come back off.
Stack is a subclass of Vector that implements a standard last-in, first-out stack.
Stack only defines the default constructor, which creates an empty stack. Stack includes all the
methods defined by Vector, and adds several of its own.
%tac<$ (
Apart from the methods inherited from its parent class Vector, Stack defines following methods:
SN Methods 3ith )escription
1 "oo$ean empty,/
Tests if this stack is empty. Returns true if the stack is empty, and returns false if the stack
contains elements.
2 !"#ect pee=, /
Returns the element on the top of the stack, but does not remove it.
3 !"#ect pop, /
Returns the element on the top of the stack, removing it in the process.
4 !"#ect psh,!"#ect e$ement/
Pushes element onto the stack. element is also returned.
5 int search,!"#ect e$ement/
Searches for element in the stack. If found, its offset from the top of the stack is returned.
Otherwise, .1 is returned.
Example:
The following program illustrates several of the methods supported by this collection:
MAT SOFT
JAVA REFERENCE GUIDE
133
import java.util.**
class %tac<4!mo {
static voi# showpush$%tac< st2 int a( {
st.push$n!w 6nt!g!r$a((*
%yst!m.out.println$)push$) > a > )()(*
%yst!m.out.println$)stac<- ) > st(*
+
static voi# showpop$%tac< st( {
%yst!m.out.print$)pop ;. )(*
6nt!g!r a 9 $6nt!g!r( st.pop$(*
%yst!m.out.println$a(*
%yst!m.out.println$)stac<- ) > st(*
+
public static voi# main$%tring args&'( {
%tac< st 9 n!w %tac<$(*
%yst!m.out.println$)stac<- ) > st(*
showpush$st2 F@(*
showpush$st2 MM(*
showpush$st2 KK(*
showpop$st(*
showpop$st(*
showpop$st(*
try {
showpop$st(*
+ catch $3mpty%tac<3:c!ption !( {
%yst!m.out.println$)!mpty stac<)(*
+
+
+
This would produce following result:
stac<- & '
push$F@(
stac<- &F@'
push$MM(
stac<- &F@2 MM'
push$KK(
stac<- &F@2 MM2 KK'
pop ;. KK
stac<- &F@2 MM'
pop ;. MM
stac<- &F@'
pop ;. F@
stac<- & '
pop ;. !mpty stac<
MAT SOFT
JAVA REFERENCE GUIDE
134
The Dictionary
The Dictionary class is an abstract class that defines a data structure for mapping keys to values.
This is useful in cases where you want to be able to access data via a particular key rather than an
integer index.
Since the Dictionary class is abstract, it provides only the framework for a key-mapped data structure
rather than a specific implementation.
Dictionary is an abstract class that represents a key/value storage repository and operates much like
Map.
Given a key and value, you can store the value in a Dictionary object. Once the value is stored, you
can retrieve it by using its key. Thus, like a map, a dictionary can be thought of as a list of key/value
pairs.
The abstract methods defined by Dictionary are listed below:
SN Methods 3ith )escription
1 7nmeration e$ements, /
Returns an enumeration of the values contained in the dictionary.
2 !"#ect get,!"#ect =ey/
Returns the object that contains the value associated with key. If key is not in the dictionary, a
null object is returned.
3 "oo$ean is7mpty, /
Returns true if the dictionary is empty, and returns false if it contains at least one key.
4 7nmeration =eys, /
Returns an enumeration of the keys contained in the dictionary.
5 !"#ect pt,!"#ect =ey< !"#ect va$e/
Inserts a key and its value into the dictionary. Returns null if key is not already in the dictionary;
returns the previous value associated with key if key is already in the dictionary.
6 !"#ect remove,!"#ect =ey/
Removes key and its value. Returns the value associated with key. If key is not in the dictionary,
a null is returned.
7 int si2e, /
Returns the number of entries in the dictionary.
The Dictionary class is obsolete. You should implement the Map interface to obtain key/value storage
functionality.
The Hashtable
The Hashtable class provides a means of organizing data based on some user-defined key structure.
For example, in an address list hash table you could store and sort data based on a key such as ZIP
code rather than on a person's name.
MAT SOFT
JAVA REFERENCE GUIDE
135
The specific meaning of keys in regard to hash tables is totally dependent on the usage of the hash
table and the data it contains.
Hashtable was part of the original java.util and is a concrete implementation of a Dictionary.
However, Java 2 reengineered Hashtable so that it also implements the Map interface. Thus, Hashtable
is now integrated into the collections framework. It is similar to HashMap, but is synchronized.
Like HashMap, Hashtable stores key/value pairs in a hash table. When using a Hashtable, you specify
an object that is used as a key, and the value that you want linked to that key. The key is then
hashed, and the resulting hash code is used as the index at which the value is stored within the table.
The Hashtable defines four constructors. The first version is the default constructor:
ashtabl!$ (
The second version creates a hash table that has an initial size specified by size:
ashtabl!$int si/!(
The third version creates a hash table that has an initial size specified by size and a fill ratio specified
by fillRatio.
This ratio must be between 0.0 and 1.0, and it determines how full the hash table can be before it is
resized upward.
ashtabl!$int si/!2 float fill7atio(
The fourth version creates a hash table that is initialized with the elements in m.
The capacity of the hash table is set to twice the number of elements in m. The default load factor of
0.75 is used.
ashtabl!$Map m(
Apart from the methods defined by Map interface, Hashtable defines following methods:
SN Methods 3ith )escription
1 void c$ear, /
Resets and empties the hash table.
2 !"#ect c$one, /
Returns a duplicate of the invoking object.
3 "oo$ean contains,!"#ect va$e/
Returns true if some value equal to value exists within the hash table. Returns false if the value
MAT SOFT
JAVA REFERENCE GUIDE
136
isn't found.
4 "oo$ean contains6ey,!"#ect =ey/
Returns true if some key equal to key exists within the hash table. Returns false if the key isn't
found.
5 "oo$ean contains*a$e,!"#ect va$e/
Returns true if some value equal to value exists within the hash table. Returns false if the value
isn't found.
6 7nmeration e$ements, /
Returns an enumeration of the values contained in the hash table.
7 !"#ect get,!"#ect =ey/
Returns the object that contains the value associated with key. If key is not in the hash table, a
null object is returned.
8 "oo$ean is7mpty, /
Returns true if the hash table is empty; returns false if it contains at least one key.
9 7nmeration =eys, /
Returns an enumeration of the keys contained in the hash table.
10 !"#ect pt,!"#ect =ey< !"#ect va$e/
Inserts a key and a value into the hash table. Returns null if key isn't already in the hash table;
returns the previous value associated with key if key is already in the hash table.
11 void rehash, /
Increases the size of the hash table and rehashes all of its keys.
12 !"#ect remove,!"#ect =ey/
Removes key and its value. Returns the value associated with key. If key is not in the hash table,
a null object is returned.
13 int si2e, /
Returns the number of entries in the hash table.
14 String toString, /
Returns the string equivalent of a hash table.
Example:
The following program illustrates several of the methods supported by this data structure:
MAT SOFT
JAVA REFERENCE GUIDE
137
import java.util.**
class ashTabl!4!mo {
public static voi# main$%tring args&'( {
// ,r!at! a hash map
ashtabl! balanc! 9 n!w ashtabl!$(*
3num!ration nam!s*
%tring str*
#oubl! bal*
balanc!.put$)Vara)2 n!w 4oubl!$DFDF.DF((*
balanc!.put$)Mahna/)2 n!w 4oubl!$C@D.@@((*
balanc!.put$)0yan)2 n!w 4oubl!$CDIJ.EE((*
balanc!.put$)4aisy)2 n!w 4oubl!$KK.@@((*
balanc!.put$)Xa#ir)2 n!w 4oubl!$;CK.EJ((*
// %how all balanc!s in hash tabl!.
nam!s 9 balanc!.<!ys$(*
whil!$nam!s.hasMor!3l!m!nts$(( {
str 9 $%tring( nam!s.n!:t3l!m!nt$(*
%yst!m.out.println$str > )- ) >
balanc!.g!t$str((*
+
%yst!m.out.println$(*
// 4!posit C2EEE into Vara's account
bal 9 $$4oubl!(balanc!.g!t$)Vara)((.#oubl!Balu!$(*
balanc!.put$)Vara)2 n!w 4oubl!$bal>CEEE((*
%yst!m.out.println$)Vara's n!w balanc!- ) >
balanc!.g!t$)Vara)((*
+
+
This would produce following result:
Xa#ir- ;CK.EJ
Vara- DFDF.DF
Mahna/- C@D.@@
4aisy- KK.@@
0yan- CDIJ.E
Vara's n!w balanc!- FFDF.DF
The Properties
Properties is a subclass of Hashtable. It is used to maintain lists of values in which the key is a String
and the value is also a String.
The Properties class is used by many other Java classes. For example, it is the type of object returned
by System.getProperties( ) when obtaining environmental values.
MAT SOFT
JAVA REFERENCE GUIDE
138
Properties is a subclass of Hashtable. It is used to maintain lists of values in which the key is a String
and the value is also a String.
The Properties class is used by many other Java classes. For example, it is the type of object returned
by System.getProperties( ) when obtaining environmental values.
Properties defines the following instance variable. This variable holds a default property list associated
with a Properties object.
Prop!rti!s #!faults*
The Properties defines two constructors. The first version creates a Properties object that has no
default values:
Prop!rti!s$ (
The second creates an object that uses propDefault for its default values. In both cases, the property
list is empty:
Prop!rti!s$Prop!rti!s prop4!fault(
Apart from the methods defined by Hashtable, Properties defines following methods:
SN Methods 3ith )escription
1 String getProperty,String =ey/
Returns the value associated with key. A null object is returned if key is neither in the list nor in
the default property list.
2 String getProperty,String =ey< String defa$tProperty/
Returns the value associated with key. defaultProperty is returned if key is neither in the list nor
in the default property list.
3 void $ist,PrintStream stream!t/
Sends the property list to the output stream linked to streamOut.
4 void $ist,Print9riter stream!t/
Sends the property list to the output stream linked to streamOut.
5 void $oad,InptStream streamIn/ thro3s I!7xception
Inputs a property list from the input stream linked to streamIn.
6 7nmeration propertyNames, /
Returns an enumeration of the keys. This includes those keys found in the default property list,
too.
MAT SOFT
JAVA REFERENCE GUIDE
139
7 !"#ect setProperty,String =ey< String va$e/
Associates value with key. Returns the previous value associated with key, or returns null if no
such association exists.
8 void store,!tptStream stream!t< String description/
After writing the string specified by description, the property list is written to the output stream
linked to streamOut.
Example:
The following program illustrates several of the methods supported by this data structure:
import java.util.**
class Prop4!mo {
public static voi# main$%tring args&'( {
Prop!rti!s capitals 9 n!w Prop!rti!s$(*
%!t stat!s*
%tring str*

capitals.put$)6llinois)2 )%pringfi!l#)(*
capitals.put$)Missouri)2 )J!ff!rson ,ity)(*
capitals.put$)"ashington)2 )?lympia)(*
capitals.put$),alifornia)2 )%acram!nto)(*
// %how all stat!s an# capitals in hashtabl!.
stat!s 9 capitals.<!y%!t$(* // g!t s!t;vi!w of <!ys
6t!rator itr 9 stat!s.it!rator$(*
whil!$itr.has=!:t$(( {
str 9 $%tring( itr.n!:t$(*
%yst!m.out.println$)Th! capital of ) >
str > ) is ) > capitals.g!tProp!rty$str( > ).)(*
+
%yst!m.out.println$(*
// loo< for stat! not in list ;; sp!cify #!fault
str 9 capitals.g!tProp!rty$)Flori#a)2 )=ot Foun#)(*
%yst!m.out.println$)Th! capital of Flori#a is )
> str > ).)(*
+
+
This would produce following result:
Th! capital of Missouri is J!ff!rson ,ity.
Th! capital of 6llinois is %pringfi!l#.
Th! capital of 6n#iana is 6n#ianapolis.
Th! capital of ,alifornia is %acram!nto.
Th! capital of "ashington is ?lympia.
Th! capital of Flori#a is =ot Foun#.
MAT SOFT
JAVA REFERENCE GUIDE
140
Day )8: Dat%/ Dat% 0ormat # Cal%"1%r
Java provides the )ate class available in #ava1ti$ package, this class encapsulates the current date and
time.
The Date class supports two constructors. The first constructor initializes the object with the current date
and time.
4at!$ (
The following constructor accepts one argument that equals the number of milliseconds that have elapsed
since midnight, January 1, 1970
4at!$long millis!c(
Once you have a Date object available, you can call any of the following support methods to play with dates:
SN Methods 3ith )escription
1 "oo$ean after,)ate date/
Returns true if the invoking Date object contains a date that is later than the one specified by date,
otherwise, it returns false.
2 "oo$ean "efore,)ate date/
Returns true if the invoking Date object contains a date that is earlier than the one specified by date,
otherwise, it returns false.
3 !"#ect c$one, /
Duplicates the invoking Date object.
4 int compareTo,)ate date/
Compares the value of the invoking object with that of date. Returns 0 if the values are equal. Returns
a negative value if the invoking object is earlier than date. Returns a positive value if the invoking
object is later than date.
5 int compareTo,!"#ect o"#/
Operates identically to compareTo(Date) if obj is of class Date. Otherwise, it throws a
ClassCastException.
6 "oo$ean e;a$s,!"#ect date/
Returns true if the invoking Date object contains the same time and date as the one specified by date,
otherwise, it returns false.
7 $ong getTime, /
Returns the number of milliseconds that have elapsed since January 1, 1970.
8 int hashCode, /
MAT SOFT
JAVA REFERENCE GUIDE
141
Returns a hash code for the invoking object.
9 void setTime,$ong time/
Sets the time and date as specified by time, which represents an elapsed time in milliseconds from
midnight, January 1, 1970
10 String toString, /
Converts the invoking Date object into a string and returns the result.
Getting Current Date & Time
This is very easy to get current date and time in Java. You can use a simple Date object
withto2tring() method to print current date and time as follows:
import java.util.4at!*

class 4at!4!mo {
public static voi# main$%tring args&'( {
// 6nstantiat! a 4at! obj!ct
4at! #at! 9 n!w 4at!$(*

// #isplay tim! an# #at! using to%tring$(
%yst!m.out.println$#at!.to%tring$((*
+
+
This would produce following result:
Mon May EF EK-HC-H@ ,4T @EEK
Date Comparison:
There are following three ways to compare two dates:
You can use getTime( ) to obtain the number of milliseconds that have elapsed since midnight,
January 1, 1970, for both objects and then compare these two values.
You can use the methods before( ), after( ), and equals( ). Because the 12th of the month comes
before the 18th, for example, new Date(99, 2, 12).before(new Date (99, 2, 18)) returns true.
You can use the compareTo( ) method, which is defined by the Comparable interface and
implemented by Date.
Date Formatting using SimpleDateFormat:
SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner.
SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting. For
example:
MAT SOFT
JAVA REFERENCE GUIDE
142
import java.util.**
import java.t!:t.**
class 4at!4!mo {
public static voi# main$%tring args&'( {
4at! #=ow 9 n!w 4at!$ (*
%impl!4at!Format ft 9
n!w %impl!4at!Format $)3 yyyy.MM.## 'at' hh-mm-ss a ///)(*
%yst!m.out.println$),urr!nt 4at!- ) > ft.format$#=ow((*
+
+
This would produce following result:
%un @EEF.EI.CJ at EF-CF-EK PM P4T
Simple DateFormat format codes:
To specify the time format use a time pattern string. In this pattern, all ASCII letters are reserved as pattern
letters, which are defined as the following:
Character )escription 7xamp$e
G Era designator AD
y Year in four digits 2001
M Month in year July or 07
d Day in month 10
h Hour in A.M./P.M. (1~12) 12
H Hour in day (0~23) 22
m Minute in hour 30
s Second in minute 55
S Millisecond 234
E Day in week Tuesday
D Day in year 360
F Day of week in month 2 (second Wed. in July)
MAT SOFT
JAVA REFERENCE GUIDE
143
w Week in year 40
W Week in month 1
a A.M./P.M. marker PM
k Hour in day (1~24) 24
K Hour in A.M./P.M. (0~11) 10
z Time zone Eastern Standard Time
' Escape for text Delimiter
" Single quote `
Date Formatting using printf:
Date and time formatting can be done very easily using printf method. You use a two-letter format, starting
with t and ending in one of the letters of the table given below. For example:
import java.util.4at!*

class 4at!4!mo {
public static voi# main$%tring args&'( {
// 6nstantiat! a 4at! obj!ct
4at! #at! 9 n!w 4at!$(*

// #isplay tim! an# #at! using to%tring$(
%yst!m.out.printf$)Wtc)2 ),urr!nt Tim! - )2 #at!(*
+
+
This would produce following result:
,urr!nt Tim!- Mon May EF EK-HC-H@ ,4T @EEK
It would be a bit silly if you had to supply the date multiple times to format each part. For that reason, a
format string can indicate the index of the argument to be formatted.
The index must immediately follow the %, and it must be terminated by a $. For example:
import java.util.4at!*

class 4at!4!mo {
MAT SOFT
JAVA REFERENCE GUIDE
144
public static voi# main$%tring args&'( {
// 6nstantiat! a 4at! obj!ct
4at! #at! 9 n!w 4at!$(*

// #isplay tim! an# #at! using to%tring$(
%yst!m.out.printf$)WCUs W@UtL W@Ut#2 W@UtA)2
)4u! #at!-)2 #at!(*
+
+
This would produce following result:
4u! #at!- F!bruary EK2 @EEF
Alternatively, you can use the < flag. It indicates that the same argument as in the preceding format
specification should be used again. For example:
import java.util.4at!*

class 4at!4!mo {
public static voi# main$%tring args&'( {
// 6nstantiat! a 4at! obj!ct
4at! #at! 9 n!w 4at!$(*

// #isplay formatt!# #at!
%yst!m.out.printf$)Ws WtL WNt!2 WNtA)2
)4u! #at!-)2 #at!(*
+
+
This would produce following result:
4u! #at!- F!bruary EK2 @EEF
Date and Time Conversion Characters:
Character )escription 7xamp$e
c Complete date and time Mon May 04 09:51:52 CDT 2009
F ISO 8601 date 2004-02-09
D U.S. formatted date (month/day/year) 02/09/2004
T 24-hour time 18:05:19
r 12-hour time 06:05:19 pm
R 24-hour time, no seconds 18:05
MAT SOFT
JAVA REFERENCE GUIDE
145
Y Four-digit year (with leading zeroes) 2004
y Last two digits of the year (with leading
zeroes)
04
C First two digits of the year (with leading
zeroes)
20
B Full month name February
b Abbreviated month name Feb
n Two-digit month (with leading zeroes) 02
d Two-digit day (with leading zeroes) 03
e Two-digit day (without leading zeroes) 9
A Full weekday name Monday
a Abbreviated weekday name Mon
j Three-digit day of year (with leading zeroes) 069
H Two-digit hour (with leading zeroes), between
00 and 23
18
k Two-digit hour (without leading zeroes),
between 0 and 23
18
I Two-digit hour (with leading zeroes), between
01 and 12
06
l Two-digit hour (without leading zeroes),
between 1 and 12
6
M Two-digit minutes (with leading zeroes) 05
S Two-digit seconds (with leading zeroes) 19
L Three-digit milliseconds (with leading zeroes) 047
N Nine-digit nanoseconds (with leading zeroes) 047000000
P Uppercase morning or afternoon marker PM
MAT SOFT
JAVA REFERENCE GUIDE
146
p Lowercase morning or afternoon marker pm
z RFC 822 numeric offset from GMT -0800
Z Time zone PST
s Seconds since 1970-01-01 00:00:00 GMT 1078884319
Q Milliseconds since 1970-01-01 00:00:00 GMT 1078884319047
There are other useful classes related to Date and time. For more detail you can refer to Java Standard
documentation.
Parsing Strings into Dates:
The SimpleDateFormat class has some additional methods, notably parse( ) , which tries to parse a string
according to the format stored in the given SimpleDateFormat object. For example:
import java.util.**
import java.t!:t.**

class 4at!4!mo {
public static voi# main$%tring args&'( {
%impl!4at!Format ft 9 n!w %impl!4at!Format $)yyyy;MM;##)(*
%tring input 9 args.l!ngth 99 E S )CJCJ;CC;CC) - args&E'*
%yst!m.out.print$input > ) Pars!s as )(*
4at! t*
try {
t 9 ft.pars!$input(*
%yst!m.out.println$t(*
+ catch $Pars!3:c!ption !( {
%yst!m.out.println$)5npars!abl! using ) > formatt!r(*
+
+
+
A sample run of the above program would produce following result:
U java 4at!4!mo
CJCJ;CC;CC Pars!s as "!# =ov CC EE-EE-EE 8MT CJCJ
U java 4at!4!mo @EEI;C@;EC
@EEI;C@;EC Pars!s as %at 4!c EC EE-EE-EE 8MT @EEI
MAT SOFT
JAVA REFERENCE GUIDE
147
Sleeping for a While:
You can sleep for any period of time from one millisecond up to the lifetime of your computer. For example,
following program would sleep for 10 seconds:
import java.util.**

class %l!!p4!mo {
public static voi# main$%tring args&'( {
try {
%yst!m.out.println$n!w 4at!$ ( > )On)(*
Thr!a#.sl!!p$H*ME*CE(*
%yst!m.out.println$n!w 4at!$ ( > )On)(*
+ catch $3:c!ption !( {
%yst!m.out.println$)8ot an !:c!ptionG)(*
+
+
+
This would produce following result:
%un May ED CJ-EF-FC 8MT @EEK
%un May ED CJ-EF-HC 8MT @EEK
Measuring Elapsed Time:
Sometime you may need to measure point in time in milliseconds. So let's re-write above example once
again:
import java.util.**

class 4iff4!mo {
public static voi# main$%tring args&'( {
try {
long start 9 %yst!m.curr!ntTim!Millis$ (*
%yst!m.out.println$n!w 4at!$ ( > )On)(*
Thr!a#.sl!!p$H*ME*CE(*
%yst!m.out.println$n!w 4at!$ ( > )On)(*
long !n# 9 %yst!m.curr!ntTim!Millis$ (*
long #iff 9 !n# ; start*
%yst!m.out.println$)4iff!r!nc! is - ) > #iff(*
+ catch $3:c!ption !( {
%yst!m.out.println$)8ot an !:c!ptionG)(*
+
+
+
This would produce following result:
%un May ED CJ-CM-HC 8MT @EEK
%un May ED CJ-CM-HI 8MT @EEK
MAT SOFT
JAVA REFERENCE GUIDE
148
4iff!r!nc! is - HKKD
GregorianCalendar Class:
GregorianCalendar is a concrete implementation of a Calendar class that implements the normal Gregorian
calendar with which you are familiar. I did not discuss Calender class in this tutorial, you can look standard
Java documentation for this.
The getInstance, / method of Calendar returns a GregorianCalendar initialized with the current date and
time in the default locale and time zone. GregorianCalendar defines two fields: AD and BC. These represent
the two eras defined by the Gregorian calendar.
There are also several constructors for GregorianCalendar objects:
SN Constrctor 3ith )escription
1 ?regorianCa$endar,/
Constructs a default GregorianCalendar using the current time in the default time zone with the default
locale.
2 ?regorianCa$endar,int year< int month< int date/
Constructs a GregorianCalendar with the given date set in the default time zone with the default locale.
3 ?regorianCa$endar,int year< int month< int date< int hor< int minte/
Constructs a GregorianCalendar with the given date and time set for the default time zone with the
default locale.
4 ?regorianCa$endar,int year< int month< int date< int hor< int minte< int second/
Constructs a GregorianCalendar with the given date and time set for the default time zone with the
default locale.
5 ?regorianCa$endar,0oca$e a0oca$e/
Constructs a GregorianCalendar based on the current time in the default time zone with the given
locale.
6 ?regorianCa$endar,Time@one 2one/
Constructs a GregorianCalendar based on the current time in the given time zone with the default
locale.
7 ?regorianCa$endar,Time@one 2one< 0oca$e a0oca$e/
Constructs a GregorianCalendar based on the current time in the given time zone with the given locale.
Here is the list of few useful support methods provided by GregorianCalendar class:
SN Medthos 3ith )escription
MAT SOFT
JAVA REFERENCE GUIDE
149
1 void add,int fie$d< int amont/
Adds the specified (signed) amount of time to the given time field, based on the calendar's rules.
2 protected void compte+ie$ds,/
Converts UTC as milliseconds to time field values.
3 protected void compteTime,/
Overrides Calendar Converts time field values to UTC as milliseconds.
4 "oo$ean e;a$s,!"#ect o"#/
Compares this GregorianCalendar to an object reference.
5 int get,int fie$d/
Gets the value for a given time field.
6 int get%cta$Maximm,int fie$d/
Return the maximum value that this field could have, given the current date.
7 int get%cta$Minimm,int fie$d/
Return the minimum value that this field could have, given the current date.
8 int get?reatestMinimm,int fie$d/
Returns highest minimum value for the given field if varies.
9 )ate get?regorianChange,/
Gets the Gregorian Calendar change date.
10 int get0eastMaximm,int fie$d/
Returns lowest maximum value for the given field if varies.
11 int getMaximm,int fie$d/
Returns maximum value for the given field.
12 )ate getTime,/
Gets this Calendar's current time.
13 $ong getTimeInMi$$is,/
Gets this Calendar's current time as a long.
14 Time@one getTime@one,/
Gets the time zone.
15 int getMinimm,int fie$d/
Returns minimum value for the given field.
16 int hashCode,/
MAT SOFT
JAVA REFERENCE GUIDE
150
Override hashCode.
17 "oo$ean is0eapAear,int year/
Determines if the given year is a leap year.
18 void ro$$,int fie$d< "oo$ean p/
Adds or subtracts (up/down) a single unit of time on the given time field without changing larger fields.
19 void set,int fie$d< int va$e/
Sets the time field with the given value.
20 void set,int year< int month< int date/
Sets the values for the fields year, month, and date.
21 void set,int year< int month< int date< int hor< int minte/
Sets the values for the fields year, month, date, hour, and minute.
22 void set,int year< int month< int date< int hor< int minte< int second/
Sets the values for the fields year, month, date, hour, minute, and second.
23 void set?regorianChange,)ate date/
Sets the GregorianCalendar change date.
24 void setTime,)ate date/
Sets this Calendar's current time with the given Date.
25 void setTimeInMi$$is,$ong mi$$is/
Sets this Calendar's current time from the given long value.
26 void setTime@one,Time@one va$e/
Sets the time zone with the given time zone value.
27 String toString,/
Return a string representation of this calendar.
Example:
import java.util.**

class 8r!gorian,al!n#ar4!mo {
public static voi# main$%tring args&'( {
%tring months&' 9 {
)Jan)2 )F!b)2 )Mar)2 )0pr)2
)May)2 )Jun)2 )Jul)2 )0ug)2
)%!p)2 )?ct)2 )=ov)2 )4!c)+*

int y!ar*
// ,r!at! a 8r!gorian cal!n#ar initiali/!#
MAT SOFT
JAVA REFERENCE GUIDE
151
// with th! curr!nt #at! an# tim! in th!
// #!fault local! an# tim!/on!.
8r!gorian,al!n#ar gcal!n#ar 9 n!w 8r!gorian,al!n#ar$(*
// 4isplay curr!nt tim! an# #at! information.
%yst!m.out.print$)4at!- )(*
%yst!m.out.print$months&gcal!n#ar.g!t$,al!n#ar.M?=T('(*
%yst!m.out.print$) ) > gcal!n#ar.g!t$,al!n#ar.40T3( > ) )(*
%yst!m.out.println$y!ar 9 gcal!n#ar.g!t$,al!n#ar.A307((*
%yst!m.out.print$)Tim!- )(*
%yst!m.out.print$gcal!n#ar.g!t$,al!n#ar.?57( > )-)(*
%yst!m.out.print$gcal!n#ar.g!t$,al!n#ar.M6=5T3( > )-)(*
%yst!m.out.println$gcal!n#ar.g!t$,al!n#ar.%3,?=4((*

// T!st if th! curr!nt y!ar is a l!ap y!ar
if$gcal!n#ar.is1!apA!ar$y!ar(( {
%yst!m.out.println$)Th! curr!nt y!ar is a l!ap y!ar)(*
+
!ls! {
%yst!m.out.println$)Th! curr!nt y!ar is not a l!ap y!ar)(*
+
+
+
This would produce following result:
4at!- 0pr @@ @EEK
Tim!- CC-@H-@I
Th! curr!nt y!ar is not a l!ap y!ar
Day )&: CO,,EC(IONS IN JAVA-U(I, PAC.AGE
Prior to Java 2, Java provided ad hoc classes such as )ictionary< *ector< Stac=, andProperties to
store and manipulate groups of objects. Although these classes were quite useful, they lacked a
central, unifying theme. Thus, the way that you used Vector was different from the way that you used
Properties.
The collections framework was designed to meet several goals.
1. The framework had to be high-performance. The implementations for the fundamental
collections (dynamic arrays, linked lists, trees, and hash tables) are highly efficient.
2. The framework had to allow different types of collections to work in a similar manner and with
a high degree of interoperability.
3. Extending and/or adapting a collection had to be easy.
Toward this end, the entire collections framework is designed around a set of standard interfaces.
Several standard implementations such as 0in=ed0ist< (ashSet< and TreeSet, of these interfaces
are provided that you may use as-is and you may also implement your own collection, if you choose.
A collections framework is a unified architecture for representing and manipulating collections. All
collections frameworks contain the following:
1. Interfaces: These are abstract data types that represent collections. Interfaces allow
collections to be manipulated independently of the details of their representation. In object-
oriented languages, interfaces generally form a hierarchy.
MAT SOFT
JAVA REFERENCE GUIDE
152
2. Imp$ementations i1e1 C$asses: These are the concrete implementations of the collection
interfaces. In essence, they are reusable data structures.
3. %$gorithms: These are the methods that perform useful computations, such as searching and
sorting, on objects that implement collection interfaces. The algorithms are said to be
polymorphic: that is, the same method can be used on many different implementations of the
appropriate collection interface.
In addition to collections, the framework defines several map interfaces and classes. Maps store
key/value pairs. Although maps are not collections in the proper use of the term, but they are fully
integrated with collections.
The Collection Interfaces:
The collections framework defines several interfaces. This section provides an overview of each
interface:
SN Interfaces 3ith )escription
1 The Collection Interface
This enables you to work with groups of objects; it is at the top of the collections hierarchy.
2 The List Interface
This extends Co$$ection and an instance of List stores an ordered collection of elements.
3 The Set
This extends Collection to handle sets, which must contain unique elements
4 The SortedSet
This extends Set to handle sorted sets
5 The Map
This maps unique keys to values.
6 The Map.Entry
This describes an element (a key/value pair) in a map. This is an inner class of Map.
7 The SortedMap
This extends Map so that the keys are maintained in ascending order.
8 The Enumeration
This is legacy interface and defines the methods by which you can enumerate (obtain one at a
time) the elements in a collection of objects. This legacy interface has been superceded by
Iterator.
COLLECTION INTERFACE
The Collection interface is the foundation upon which the collections framework is built. It declares the
core methods that all collections will have. These methods are summarized in the following table.
MAT SOFT
JAVA REFERENCE GUIDE
153
Because all collections implement Collection, familiarity with its methods is necessary for a clear
understanding of the framework. Several of these methods can throw
anBnspported!peration7xception.
SN Methods 3ith )escription
1 "oo$ean add,!"#ect o"#/
Adds obj to the invoking collection. Returns true if obj was added to the collection. Returns false
if obj is already a member of the collection, or if the collection does not allow duplicates.
2 "oo$ean add%$$,Co$$ection c/
Adds all the elements of c to the invoking collection. Returns true if the operation succeeded (i.e.,
the elements were added). Otherwise, returns false.
3 void c$ear, /
Removes all elements from the invoking collection.
4 "oo$ean contains,!"#ect o"#/
Returns true if obj is an element of the invoking collection. Otherwise, returns false.
5 "oo$ean contains%$$,Co$$ection c/
Returns true if the invoking collection contains all elements of c. Otherwise, returns false.
6 "oo$ean e;a$s,!"#ect o"#/
Returns true if the invoking collection and obj are equal. Otherwise, returns false.
7 int hashCode, /
Returns the hash code for the invoking collection.
8 "oo$ean is7mpty, /
Returns true if the invoking collection is empty. Otherwise, returns false.
9 Iterator iterator, /
Returns an iterator for the invoking collection.
10 "oo$ean remove,!"#ect o"#/
Removes one instance of obj from the invoking collection. Returns true if the element was
removed. Otherwise, returns false.
11 "oo$ean remove%$$,Co$$ection c/
Removes all elements of c from the invoking collection. Returns true if the collection changed
(i.e., elements were removed). Otherwise, returns false.
12 "oo$ean retain%$$,Co$$ection c/
Removes all elements from the invoking collection except those in c. Returns true if the collection
MAT SOFT
JAVA REFERENCE GUIDE
154
changed (i.e., elements were removed). Otherwise, returns false
13 int si2e, /
Returns the number of elements held in the invoking collection.
14 !"#ect- . to%rray, /
Returns an array that contains all the elements stored in the invoking collection. The array
elements are copies of the collection elements.
15 !"#ect- . to%rray,!"#ect array- ./
Returns an array containing only those collection elements whose type matches that of array.
THE LIST INTERFACE
The List interface extends Co$$ection and declares the behavior of a collection that stores a sequence
of elements.
Elements can be inserted or accessed by their position in the list, using a zero-based index.
A list may contain duplicate elements.
In addition to the methods defined by Co$$ection, List defines some of its own, which are
summarized in the following below Table.
Several of the list methods will throw an UnsupportedOperationException if the collection
cannot be modified, and a ClassCastException is generated when one object is incompatible
with another.
SN Methods 3ith )escription
1 void add,int index< !"#ect o"#/
Inserts obj into the invoking list at the index passed in index. Any preexisting elements at or
beyond the point of insertion are shifted up. Thus, no elements are overwritten.
2 "oo$ean add%$$,int index< Co$$ection c/
Inserts all elements of c into the invoking list at the index passed in index. Any preexisting
elements at or beyond the point of insertion are shifted up. Thus, no elements are overwritten.
Returns true if the invoking list changes and returns false otherwise.
3 !"#ect get,int index/
Returns the object stored at the specified index within the invoking collection.
4 int index!f,!"#ect o"#/
Returns the index of the first instance of obj in the invoking list. If obj is not an element of the
list, .1 is returned.
MAT SOFT
JAVA REFERENCE GUIDE
155
5 int $astIndex!f,!"#ect o"#/
Returns the index of the last instance of obj in the invoking list. If obj is not an element of the
list, .1 is returned.
6 0istIterator $istIterator, /
Returns an iterator to the start of the invoking list.
7 0istIterator $istIterator,int index/
Returns an iterator to the invoking list that begins at the specified index.
8 !"#ect remove,int index/
Removes the element at position index from the invoking list and returns the deleted element.
The resulting list is compacted. That is, the indexes of subsequent elements are decremented by
one
9 !"#ect set,int index< !"#ect o"#/
Assigns obj to the location specified by index within the invoking list.
10 0ist s"0ist,int start< int end/
Returns a list that includes elements from start to end.1 in the invoking list. Elements in the
returned list are also referenced by the invoking object.
The SortedSet interface extends Set and declares the behavior of a set sorted in ascending order. In addition
to those methods defined by Set, the SortedSet interface declares the methods summarized in below Table:
Several methods throw a NoSuchElementException when no items are contained in the invoking set. A
ClassCastException is thrown when an object is incompatible with the elements in a set.
A NullPointerException is thrown if an attempt is made to use a null object and null is not allowed in the set.
SN Methods 3ith )escription
1 Comparator comparator, /
Returns the invoking sorted set's comparator. If the natural ordering is used for this set, null is
returned.
2 !"#ect first, /
Returns the first element in the invoking sorted set.
3 SortedSet headSet,!"#ect end/
Returns a SortedSet containing those elements less than end that are contained in the invoking sorted
set. Elements in the returned sorted set are also referenced by the invoking sorted set.
4 !"#ect $ast, /
MAT SOFT
JAVA REFERENCE GUIDE
156
Returns the last element in the invoking sorted set.
5 SortedSet s"Set,!"#ect start< !"#ect end/
Returns a SortedSet that includes those elements between start and end.1. Elements in the returned
collection are also referenced by the invoking object.
6 SortedSet tai$Set,!"#ect start/
Returns a SortedSet that contains those elements greater than or equal to start that are contained in
the sorted set. Elements in the returned set are also referenced by the invoking object.
T@E MAP INTERFACE
The Map interface maps unique keys to values. A key is an object that you use to retrieve a value at a
later date.
Given a key and a value, you can store the value in a Map object. After the value is stored,
you can retrieve it by using its key.
Several methods throw a NoSuchElementException when no items exist in the invoking map.
A ClassCastException is thrown when an object is incompatible with the elements in a map.
A ClassCastException is thrown when an object is incompatible with the elements in a map.
A NullPointerException is thrown if an attempt is made to use a null object and null is not
allowed in the map.
An UnsupportedOperationException is thrown when an attempt is made to change an
unmodifiable map.
SN Methods 3ith )escription
1 void c$ear, /
Removes all key/value pairs from the invoking map.
2 "oo$ean contains6ey,!"#ect =/
Returns true if the invoking map contains k as a key. Otherwise, returns false.
3 "oo$ean contains*a$e,!"#ect v/
Returns true if the map contains v as a value. Otherwise, returns false.
4 Set entrySet, /
Returns a Set that contains the entries in the map. The set contains objects of type Map.Entry.
This method provides a set-view of the invoking map.
MAT SOFT
JAVA REFERENCE GUIDE
157
5 "oo$ean e;a$s,!"#ect o"#/
Returns true if obj is a Map and contains the same entries. Otherwise, returns false.
6 !"#ect get,!"#ect =/
Returns the value associated with the key k.
7 int hashCode, /
Returns the hash code for the invoking map.
8 "oo$ean is7mpty, /
Returns true if the invoking map is empty. Otherwise, returns false.
9 Set =eySet, /
Returns a Set that contains the keys in the invoking map. This method provides a set-view of the
keys in the invoking map.
10 !"#ect pt,!"#ect =< !"#ect v/
Puts an entry in the invoking map, overwriting any previous value associated with the key. The
key and value are k and v, respectively. Returns null if the key did not already exist. Otherwise,
the previous value linked to the key is returned.
11 void pt%$$,Map m/
Puts all the entries from m into this map.
12 !"#ect remove,!"#ect =/
Removes the entry whose key equals k.
13 int si2e, /
Returns the number of key/value pairs in the map.
14 Co$$ection va$es, /
Returns a collection containing the values in the map. This method provides a collection-view of
the values in the map.
T@E SORTED MAP INTERFACE
The SortedMap interface extends Map. It ensures that the entries are maintained in ascending key
order
Several methods throw a NoSuchElementException when no items are in the invoking map. A
ClassCastException is thrown when an object is incompatible with the elements in a map. A
NullPointerException is thrown if an attempt is made to use a null object when null is not allowed in
the map.
MAT SOFT
JAVA REFERENCE GUIDE
158
The methods declared by SortedMap are summarized in the following table:
SN Methods 3ith )escription
1 Comparator comparator, /
Returns the invoking sorted map's comparator. If the natural ordering is used for the invoking
map, null is returned.
2 !"#ect first6ey, /
Returns the first key in the invoking map.
3 SortedMap headMap,!"#ect end/
Returns a sorted map for those map entries with keys that are less than end.
4 !"#ect $ast6ey, /
Returns the last key in the invoking map.
5 SortedMap s"Map,!"#ect start< !"#ect end/
Returns a map containing those entries with keys that are greater than or equal to start and less
than end
6 SortedMap tai$Map,!"#ect start/
Returns a map containing those entries with keys that are greater than or equal to start.
The Enumeration interface defines the methods by which you can enumerate (obtain one at a time)
the elements in a collection of objects.
This legacy interface has been superceded by Iterator. Although not deprecated, Enumeration is
considered obsolete for new code. However, it is used by several methods defined by the legacy
classes such as Vector and Properties, is used by several other API classes, and is currently in
widespread use in application code.
The methods declared by Enumeration are summarized in the following table:
SN Methods 3ith )escription
1 "oo$ean hasMore7$ements, /
When implemented, it must return true while there are still more elements to extract, and false
when all the elements have been enumerated.
2 !"#ect next7$ement, /
This returns the next object in the enumeration as a generic Object reference.
MAT SOFT
JAVA REFERENCE GUIDE
159
T@E ITERATOR INTERFACE
Often, you will want to cycle through the elements in a collection. For example, you might want to
display each element.
The easiest way to do this is to employ an iterator, which is an object that implements either the
Iterator or the ListIterator interface.
Iterator enables you to cycle through a collection, obtaining or removing elements. ListIterator
extends Iterator to allow bidirectional traversal of a list, and the modification of elements.
Before you can access a collection through an iterator, you must obtain one. Each of the collection
classes provides an iterator( ) method that returns an iterator to the start of the collection. By using
this iterator object, you can access each element in the collection, one element at a time.
In general, to use an iterator to cycle through the contents of a collection, follow these steps:
1. Obtain an iterator to the start of the collection by calling the collection's iterator( ) method.
2. Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( )
returns true.
3. Within the loop, obtain each element by calling next( ).
For collections that implement List, you can also obtain an iterator by calling ListIterator.
The Methods Declared by Iterator:
SN Methods 3ith )escription
1 "oo$ean hasNext, /
Returns true if there are more elements. Otherwise, returns false.
2 !"#ect next, /
Returns the next element. Throws NoSuchElementException if there is not a next element.
3 void remove, /
Removes the current element. Throws IllegalStateException if an attempt is made to call remove(
) that is not preceded by a call to next( ).
The Methods Declared by ListIterator:
SN Methods 3ith )escription
1 void add,!"#ect o"#/
Inserts obj into the list in front of the element that will be returned by the next call to next( ).
MAT SOFT
JAVA REFERENCE GUIDE
160
2 "oo$ean hasNext, /
Returns true if there is a next element. Otherwise, returns false.
3 "oo$ean hasPrevios, /
Returns true if there is a previous element. Otherwise, returns false.
4 !"#ect next, /
Returns the next element. A NoSuchElementException is thrown if there is not a next element.
5 int nextIndex, /
Returns the index of the next element. If there is not a next element, returns the size of the list.
6 !"#ect previos, /
Returns the previous element. A NoSuchElementException is thrown if there is not a previous
element.
7 int previosIndex, /
Returns the index of the previous element. If there is not a previous element, returns -1.
8 void remove, /
Removes the current element from the list. An IllegalStateException is thrown if remove( ) is
called before next( ) or previous( ) is invoked.
1 void set,!"#ect o"#/
Assigns obj to the current element. This is the element last returned by a call to either next( ) or
previous( ).
T@E COMPARATOR INTERFACE
Both TreeSet and TreeMap store elements in sorted order. However, it is the comparator that defines
precisely what sorted order means.
This interface lets us sort a given collection any number of different ways. Also this interface can be
used to sort any instances of any class.(even classes we cannot modify).
The Comparator interface defines two methods: compare( ) and equals( ). The compare( ) method,
shown here, compares two elements for order:
The compare Method:
int compar!$?bj!ct objC2 ?bj!ct obj@(
MAT SOFT
JAVA REFERENCE GUIDE
161
obj1 and obj2 are the objects to be compared. This method returns zero if the objects are equal. It
returns a positive value if obj1 is greater than obj2. Otherwise, a negative value is returned.
By overriding compare( ), you can alter the way that objects are ordered. For example, to sort in
reverse order, you can create a comparator that reverses the outcome of a comparison.
The equals Method:
The equals( ) method, shown here, tests whether an object equals the invoking comparator:
bool!an !Puals$?bj!ct obj(
obj is the object to be tested for equality. The method returns true if obj and the invoking object are
both Comparator objects and use the same ordering. Otherwise, it returns false.
Overriding equals( ) is unnecessary, and most simple comparators will not do so.
The Collection Classes:
Java provides a set of standard collection classes that implement Collection interfaces. Some of the
classes provide full implementations that can be used as-is and others are abstract class, providing
skeletal implementations that are used as starting points for creating concrete collections.
The standard collection classes are summarized in the following table:
SN C$asses 3ith )escription
1 %"stractCo$$ection
Implements most of the Collection interface.
2 %"stract0ist
Extends AbstractCollection and implements most of the List interface.
3 %"stractSe;entia$0ist
Extends AbstractList for use by a collection that uses sequential rather than random access of its
elements.
4 LinkedList
Implements a linked list by extending AbstractSequentialList.
5 ArrayList
Implements a dynamic array by extending AbstractList.
6 %"stractSet
Extends AbstractCollection and implements most of the Set interface.
7 HashSet
Extends AbstractSet for use with a hash table.
8 LinkedHashSet
MAT SOFT
JAVA REFERENCE GUIDE
162
Extends HashSet to allow insertion-order iterations.
9 TreeSet
Implements a set stored in a tree. Extends AbstractSet.
10 %"stractMap
Implements most of the Map interface.
11 HashMap
Extends AbstractMap to use a hash table.
12 TreeMap
Extends AbstractMap to use a tree.
13 WeakHashMap
Extends AbstractMap to use a hash table with weak keys.
14 LinkedHashMap
Extends HashMap to allow insertion-order iterations.
15 IdentityHashMap
Extends AbstractMap and uses reference equality when comparing documents.
The -bstractCollection3 -bstract2et3 -bstractList3 -bstract2e4uentialList and -bstract#ap classes
provide skeletal implementations of the core collection interfaces, to minimize the effort required to
implement them.
The following legacy classes defined by java.util has been discussed in previous SECTION:
SN C$asses 3ith )escription
1 Vector
This implements a dynamic array. It is similar to ArrayList, but with some differences.
2 Stack
Stack is a subclass of Vector that implements a standard last-in, first-out stack.
3 Dictionary
Dictionary is an abstract class that represents a key/value storage repository and operates much
like Map.
4 Hashtable
Hashtable was part of the original java.util and is a concrete implementation of a Dictionary.
5 Properties
Properties is a subclass of Hashtable. It is used to maintain lists of values in which the key is a
String and the value is also a String.
6 BitSet
A BitSet class creates a special type of array that holds bit values. This array can increase in size
as needed.
MAT SOFT
JAVA REFERENCE GUIDE
163
Day 23: Coll%!tio" Class%s
T@E ARRA! LIST CLASS
The ArrayList class extends AbstractList and implements the List interface. ArrayList supports dynamic
arrays that can grow as needed.
Standard Java arrays are of a fixed length. After arrays are created, they cannot grow or shrink, which
means that you must know in advance how many elements an array will hold.
Array lists are created with an initial size. When this size is exceeded, the collection is automatically
enlarged. When objects are removed, the array may be shrunk.
The ArrayList class supports three constructors. The first constructor builds an empty array list.:
0rray1ist$ (
The following constructor builds an array list that is initialized with the elements of the collection c.
0rray1ist$,oll!ction c(
The following constructor builds an array list that has the specified initial capacity. The capacity is the
size of the underlying array that is used to store the elements.
The capacity grows automatically as elements are added to an array list.
0rray1ist$int capacity(
Apart from the methods inherited from its parent classes, ArrayList defines following methods:
SN Methods 3ith )escription
1 void add,int index< !"#ect e$ement/
MAT SOFT
JAVA REFERENCE GUIDE
164
Inserts the specified element at the specified position index in this list. Throws
IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index > size()).
2 "oo$ean add,!"#ect o/
Appends the specified element to the end of this list.
3 "oo$ean add%$$,Co$$ection c/
Appends all of the elements in the specified collection to the end of this list, in the order that they
are returned by the specified collection's iterator. Throws NullPointerException if the specified
collection is null.
4 "oo$ean add%$$,int index< Co$$ection c/
Inserts all of the elements in the specified collection into this list, starting at the specified
position. Throws NullPointerException if the specified collection is null.
5 void c$ear,/
Removes all of the elements from this list.
6 !"#ect c$one,/
Returns a shallow copy of this ArrayList.
7 "oo$ean contains,!"#ect o/
Returns true if this list contains the specified element. More formally, returns true if and only if
this list contains at least one element e such that (o==null ? e==null : o.equals(e)).
8 void ensreCapacity,int minCapacity/
Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least
the number of elements specified by the minimum capacity argument.
9 !"#ect get,int index/
Returns the element at the specified position in this list. Throws IndexOutOfBoundsException if
the specified index is is out of range (index < 0 || index >= size()).
10 int index!f,!"#ect o/
Returns the index in this list of the first occurrence of the specified element, or -1 if the List does
not contain this element.
11 int $astIndex!f,!"#ect o/
Returns the index in this list of the last occurrence of the specified element, or -1 if the list does
not contain this element.
12 !"#ect remove,int index/
Removes the element at the specified position in this list. Throws IndexOutOfBoundsException if
index out of range (index < 0 || index >= size()).
13 protected void remove'ange,int fromIndex< int toIndex/
MAT SOFT
JAVA REFERENCE GUIDE
165
Removes from this List all of the elements whose index is between fromIndex, inclusive and
toIndex, exclusive.
14 !"#ect set,int index< !"#ect e$ement/
Replaces the element at the specified position in this list with the specified element. Throws
IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index >=
size()).
15 int si2e,/
Returns the number of elements in this list.
16 !"#ect-. to%rray,/
Returns an array containing all of the elements in this list in the correct order. Throws
NullPointerException if the specified array is null.
17 !"#ect-. to%rray,!"#ect-. a/
Returns an array containing all of the elements in this list in the correct order; the runtime type
of the returned array is that of the specified array.
18 void trimToSi2e,/
Trims the capacity of this ArrayList instance to be the list's current size.
Example:
The following program illustrates several of the methods supported by ArrayList:
import java.util.**
class 0rray1ist4!mo {
public static voi# main$%tring args&'( {
// cr!at! an array list
0rray1ist al 9 n!w 0rray1ist$(*
%yst!m.out.println$)6nitial si/! of al- ) >
al.si/!$((*
// a## !l!m!nts to th! array list
al.a##$),)(*
al.a##$)0)(*
al.a##$)3)(*
al.a##$)L)(*
al.a##$)4)(*
al.a##$)F)(*
al.a##$C2 )0@)(*
%yst!m.out.println$)%i/! of al aft!r a##itions- ) >
al.si/!$((*
// #isplay th! array list
%yst!m.out.println$),ont!nts of al- ) > al(*
MAT SOFT
JAVA REFERENCE GUIDE
166
// 7!mov! !l!m!nts from th! array list
al.r!mov!$)F)(*
al.r!mov!$@(*
%yst!m.out.println$)%i/! of al aft!r #!l!tions- ) >
al.si/!$((*
%yst!m.out.println$),ont!nts of al- ) > al(*
+
+
This would produce following result:
6nitial si/! of al- E
%i/! of al aft!r a##itions- I
,ont!nts of al- &,2 0@2 02 32 L2 42 F'
%i/! of al aft!r #!l!tions- H
,ont!nts of al- &,2 0@2 32 L2 4'
T@E LINKED LIST CLASS
The LinkedList class extends AbstractSequentialList and implements the List interface. It provides a
linked-list data structure.
The LinkedList class supports two constructors. The first constructor builds an empty linked list:
1in<!#1ist$ (
The following constructor builds a linked list that is initialized with the elements of the collection c.
1in<!#1ist$,oll!ction c(
Apart from the methods inherited from its parent classes, LinkedList defines following methods:
SN Methods 3ith )escription
1 void add,int index< !"#ect e$ement/
Inserts the specified element at the specified position index in this list. Throws
IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index > size()).
2 "oo$ean add,!"#ect o/
Appends the specified element to the end of this list.
3 "oo$ean add%$$,Co$$ection c/
Appends all of the elements in the specified collection to the end of this list, in the order that they
are returned by the specified collection's iterator. Throws NullPointerException if the specified
collection is null.
MAT SOFT
JAVA REFERENCE GUIDE
167
4 "oo$ean add%$$,int index< Co$$ection c/
Inserts all of the elements in the specified collection into this list, starting at the specified
position. Throws NullPointerException if the specified collection is null.
5 void add+irst,!"#ect o/
Inserts the given element at the beginning of this list.
6 void add0ast,!"#ect o/
Appends the given element to the end of this list.
7 void c$ear,/
Removes all of the elements from this list.
8 !"#ect c$one,/
Returns a shallow copy of this LinkedList.
9 "oo$ean contains,!"#ect o/
Returns true if this list contains the specified element. More formally, returns true if and only if
this list contains at least one element e such that (o==null ? e==null : o.equals(e)).
10 !"#ect get,int index/
Returns the element at the specified position in this list. Throws IndexOutOfBoundsException if
the specified index is is out of range (index < 0 || index >= size()).
11 !"#ect get+irst,/
Returns the first element in this list. Throws NoSuchElementException if this list is empty.
12 !"#ect get0ast,/
Returns the last element in this list. Throws NoSuchElementException if this list is empty.
13 int index!f,!"#ect o/
Returns the index in this list of the first occurrence of the specified element, or -1 if the List does
not contain this element.
14 int $astIndex!f,!"#ect o/
Returns the index in this list of the last occurrence of the specified element, or -1 if the list does
not contain this element.
15 0istIterator $istIterator,int index/
Returns a list-iterator of the elements in this list (in proper sequence), starting at the specified
position in the list. Throws IndexOutOfBoundsException if the specified index is is out of range
(index < 0 || index >= size()).
16 !"#ect remove,int index/
Removes the element at the specified position in this list. Throws NoSuchElementException if this
MAT SOFT
JAVA REFERENCE GUIDE
168
list is empty.
17 "oo$ean remove,!"#ect o/
Removes the first occurrence of the specified element in this list. Throws
NoSuchElementException if this list is empty. Throws IndexOutOfBoundsException if the specified
index is is out of range (index < 0 || index >= size()).
18 !"#ect remove+irst,/
Removes and returns the first element from this list. Throws NoSuchElementException if this list
is empty.
19 !"#ect remove0ast,/
Removes and returns the last element from this list. Throws NoSuchElementException if this list
is empty.
20 !"#ect set,int index< !"#ect e$ement/
Replaces the element at the specified position in this list with the specified element. Throws
IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index >=
size()).
21 int si2e,/
Returns the number of elements in this list.
22 !"#ect-. to%rray,/
Returns an array containing all of the elements in this list in the correct order. Throws
NullPointerException if the specified array is null.
23 !"#ect-. to%rray,!"#ect-. a/
Returns an array containing all of the elements in this list in the correct order; the runtime type
of the returned array is that of the specified array.
Example:
The following program illustrates several of the methods supported by LinkedList:
import java.util.**
class 1in<!#1ist4!mo {
public static voi# main$%tring args&'( {
// cr!at! a lin<!# list
1in<!#1ist ll 9 n!w 1in<!#1ist$(*
// a## !l!m!nts to th! lin<!# list
ll.a##$)F)(*
ll.a##$)L)(*
ll.a##$)4)(*
ll.a##$)3)(*
ll.a##$),)(*
MAT SOFT
JAVA REFERENCE GUIDE
169
ll.a##1ast$)V)(*
ll.a##First$)0)(*
ll.a##$C2 )0@)(*
%yst!m.out.println$)?riginal cont!nts of ll- ) > ll(*
// r!mov! !l!m!nts from th! lin<!# list
ll.r!mov!$)F)(*
ll.r!mov!$@(*
%yst!m.out.println$),ont!nts of ll aft!r #!l!tion- )
> ll(*

// r!mov! first an# last !l!m!nts
ll.r!mov!First$(*
ll.r!mov!1ast$(*
%yst!m.out.println$)ll aft!r #!l!ting first an# last- )
> ll(*
// g!t an# s!t a valu!
?bj!ct val 9 ll.g!t$@(*
ll.s!t$@2 $%tring( val > ) ,hang!#)(*
%yst!m.out.println$)ll aft!r chang!- ) > ll(*
+
+
This would produce following result:
?riginal cont!nts of ll- &02 0@2 F2 L2 42 32 ,2 V'
,ont!nts of ll aft!r #!l!tion- &02 0@2 42 32 ,2 V'
ll aft!r #!l!ting first an# last- &0@2 42 32 ,'
ll aft!r chang!- &0@2 42 3 ,hang!#2 ,'
T@E @AS@SET CLASS
HashSet extends AbstractSet and implements the Set interface. It creates a collection that uses a
hash table for storage.
A hash table stores information by using a mechanism called hashing. In hashing, the informational
content of a key is used to determine a unique value, called its hash code.
The hash code is then used as the index at which the data associated with the key is stored. The
transformation of the key into its hash code is performed automatically.
The HashSet class supports four constructors. The first form constructs a default hash set:
ash%!t$ (
The following constructor form initializes the hash set by using the elements of c.
MAT SOFT
JAVA REFERENCE GUIDE
170
ash%!t$,oll!ction c(
The following constructor form initializes the capacity of the hash set to capacity.
The capacity grows automatically as elements are added to the Hash.
ash%!t$int capacity(
The fourth form initializes both the capacity and the fill ratio (also called load capacity) of the hash set
from its arguments:
ash%!t$int capacity2 float fill7atio(
Here the fill ratio must be between 0.0 and 1.0, and it determines how full the hash set can be before
it is resized upward. Specifically, when the number of elements is greater than the capacity of the
hash set multiplied by its fill ratio, the hash set is expanded
Apart from the methods inherited from its parent classes, HashSet defines following methods:
SN Methods 3ith )escription
1 "oo$ean add,!"#ect o/
Adds the specified element to this set if it is not already present.
2 void c$ear,/
Removes all of the elements from this set.
3 !"#ect c$one,/
Returns a shallow copy of this HashSet instance: the elements themselves are not cloned.
4 "oo$ean contains,!"#ect o/
Returns true if this set contains the specified element
5 "oo$ean is7mpty,/
Returns true if this set contains no elements.
6 Iterator iterator,/
Returns an iterator over the elements in this set.
7 "oo$ean remove,!"#ect o/
Removes the specified element from this set if it is present.
8 int si2e,/
Returns the number of elements in this set (its cardinality).
MAT SOFT
JAVA REFERENCE GUIDE
171
Example:
The following program illustrates several of the methods supported by HashSet:
import java.util.**
class ash%!t4!mo {
public static voi# main$%tring args&'( {
// cr!at! a hash s!t
ash%!t hs 9 n!w ash%!t$(*
// a## !l!m!nts to th! hash s!t
hs.a##$)L)(*
hs.a##$)0)(*
hs.a##$)4)(*
hs.a##$)3)(*
hs.a##$),)(*
hs.a##$)F)(*
%yst!m.out.println$hs(*
+
+
This would produce following result:
&02 F2 32 42 ,2 L'
T@E LINKED@AS@SET CLASS
This class extends HashSet, but adds no members of its own.
LinkedHashSet maintains a linked list of the entries in the set, in the order in which they were
inserted. This allows insertion-order iteration over the set.
That is, when cycling through a LinkedHashSet using an iterator, the elements will be returned in the
order in which they were inserted.
The hash code is then used as the index at which the data associated with the key is stored. The
transformation of the key into its hash code is performed automatically.
The LinkedHashSet class supports four constructors. The first form constructs a default hash set:
1in<!#ash%!t$ (
The following constructor form initializes the hash set by using the elements of c.
1in<!#ash%!t$,oll!ction c(
MAT SOFT
JAVA REFERENCE GUIDE
172
The following constructor form initializes the capacity of the hash set to capacity.
The capacity grows automatically as elements are added to the Hash.
1in<!#ash%!t$int capacity(
The fourth form initializes both the capacity and the fill ratio (also called load capacity) of the hash set
from its arguments:
1in<!#ash%!t$int capacity2 float fill7atio(
Example:
The following program illustrates several of the methods supported by LinkedHashSet:
import java.util.**
class ash%!t4!mo {
public static voi# main$%tring args&'( {
// cr!at! a hash s!t
1in<!#ash%!t hs 9 n!w 1in<!#ash%!t$(*
// a## !l!m!nts to th! hash s!t
hs.a##$)L)(*
hs.a##$)0)(*
hs.a##$)4)(*
hs.a##$)3)(*
hs.a##$),)(*
hs.a##$)F)(*
%yst!m.out.println$hs(*
+
+
This would produce following result:
&L2 02 42 32 ,2 F'
T@E TREESET CLASS
TreeSet provides an implementation of the Set interface that uses a tree for storage. Objects are
stored in sorted, ascending order.
MAT SOFT
JAVA REFERENCE GUIDE
173
Access and retrieval times are quite fast, which makes TreeSet an excellent choice when storing large
amounts of sorted information that must be found quickly.
The TreeSet class supports four constructors. The first form constructs an empty tree set that will be
sorted in ascending order according to the natural order of its elements:
Tr!!%!t$ (
The second form builds a tree set that contains the elements of c.
Tr!!%!t$,oll!ction c(
The third form constructs an empty tree set that will be sorted according to the comparator specified
by comp.
Tr!!%!t$,omparator comp(
The fourth form builds a tree set that contains the elements of ss:
Tr!!%!t$%ort!#%!t ss(
Apart from the methods inherited from its parent classes, TreeSet defines following methods:
SN Methods 3ith )escription
1 void add,!"#ect o/
Adds the specified element to this set if it is not already present.
2 "oo$ean add%$$,Co$$ection c/
Adds all of the elements in the specified collection to this set.
3 void c$ear,/
Removes all of the elements from this set.
4 !"#ect c$one,/
Returns a shallow copy of this TreeSet instance.
5 Comparator comparator,/
Returns the comparator used to order this sorted set, or null if this tree set uses its elements
natural ordering.
6 "oo$ean contains,!"#ect o/
Returns true if this set contains the specified element.
7 !"#ect first,/
MAT SOFT
JAVA REFERENCE GUIDE
174
Returns the first (lowest) element currently in this sorted set.
8 SortedSet headSet,!"#ect to7$ement/
Returns a view of the portion of this set whose elements are strictly less than toElement.
9 "oo$ean is7mpty,/
Returns true if this set contains no elements.
10 Iterator iterator,/
Returns an iterator over the elements in this set.
11 !"#ect $ast,/
Returns the last (highest) element currently in this sorted set.
12 "oo$ean remove,!"#ect o/
Removes the specified element from this set if it is present.
13 int si2e,/
Returns the number of elements in this set (its cardinality).
14 SortedSet s"Set,!"#ect from7$ement< !"#ect to7$ement/
Returns a view of the portion of this set whose elements range from fromElement, inclusive, to
toElement, exclusive.
15 SortedSet tai$Set,!"#ect from7$ement/
Returns a view of the portion of this set whose elements are greater than or equal to
fromElement.
Example:
The following program illustrates several of the methods supported by this collection:
import java.util.**
class Tr!!%!t4!mo {
public static voi# main$%tring args&'( {
// ,r!at! a tr!! s!t
Tr!!%!t ts 9 n!w Tr!!%!t$(*
// 0## !l!m!nts to th! tr!! s!t
ts.a##$),)(*
ts.a##$)0)(*
ts.a##$)L)(*
ts.a##$)3)(*
ts.a##$)F)(*
ts.a##$)4)(*
%yst!m.out.println$ts(*
+
MAT SOFT
JAVA REFERENCE GUIDE
175
+
This would produce following result:
&02 L2 ,2 42 32 F'
Day 2): ('E 'AS'+AP C,ASS
The HashMap class uses a hash table to implement the Map interface. This allows the execution time
of basic operations, such as get( ) and put( ), to remain constant even for large sets.
The HashMap class supports four constructors. The first form constructs a default hash map:
ashMap$ (
The second form initializes the hash map by using the elements of m:
ashMap$Map m(
MAT SOFT
JAVA REFERENCE GUIDE
176
The third form initializes the capacity of the hash map to capacity:
ashMap$int capacity(
The fourth form initializes both the capacity and fill ratio of the hash map by using its arguments:
ashMap$int capacity2 float fill7atio(
Apart from the methods inherited from its parent classes, HashMap defines following methods:
SN Methods 3ith )escription
1 void c$ear,/
Removes all mappings from this map.
2 !"#ect c$one,/
Returns a shallow copy of this HashMap instance: the keys and values themselves are not cloned.
3 "oo$ean contains6ey,!"#ect =ey/
Returns true if this map contains a mapping for the specified key.
4 "oo$ean contains*a$e,!"#ect va$e/
Returns true if this map maps one or more keys to the specified value.
5 Set entrySet,/
Returns a collection view of the mappings contained in this map.
6 !"#ect get,!"#ect =ey/
Returns the value to which the specified key is mapped in this identity hash map, or null if the
map contains no mapping for this key.
7 "oo$ean is7mpty,/
Returns true if this map contains no key-value mappings.
8 Set =eySet,/
Returns a set view of the keys contained in this map.
9 !"#ect pt,!"#ect =ey< !"#ect va$e/
Associates the specified value with the specified key in this map.
10 pt%$$,Map m/
Copies all of the mappings from the specified map to this map These mappings will replace any
mappings that this map had for any of the keys currently in the specified map.
11 !"#ect remove,!"#ect =ey/
MAT SOFT
JAVA REFERENCE GUIDE
177
Removes the mapping for this key from this map if present.
12 int si2e,/
Returns the number of key-value mappings in this map.
13 Co$$ection va$es,/
Returns a collection view of the values contained in this map.
Example:
The following program illustrates several of the methods supported by this collection:
import java.util.**
class ashMap4!mo {
public static voi# main$%tring args&'( {
// ,r!at! a hash map
ashMap hm 9 n!w ashMap$(*
// Put !l!m!nts to th! map
hm.put$)Vara)2 n!w 4oubl!$DFDF.DF((*
hm.put$)Mahna/)2 n!w 4oubl!$C@D.@@((*
hm.put$)0yan)2 n!w 4oubl!$CDIJ.EE((*
hm.put$)4aisy)2 n!w 4oubl!$KK.@@((*
hm.put$)Xa#ir)2 n!w 4oubl!$;CK.EJ((*

// 8!t a s!t of th! !ntri!s
%!t s!t 9 hm.!ntry%!t$(*
// 8!t an it!rator
6t!rator i 9 s!t.it!rator$(*
// 4isplay !l!m!nts
whil!$i.has=!:t$(( {
Map.3ntry m! 9 $Map.3ntry(i.n!:t$(*
%yst!m.out.print$m!.g!tY!y$( > )- )(*
%yst!m.out.println$m!.g!tBalu!$((*
+
%yst!m.out.println$(*
// 4!posit CEEE into Vara's account
#oubl! balanc! 9 $$4oubl!(hm.g!t$)Vara)((.#oubl!Balu!$(*
hm.put$)Vara)2 n!w 4oubl!$balanc! > CEEE((*
%yst!m.out.println$)Vara's n!w balanc!- ) >
hm.g!t$)Vara)((*
+
+
This would produce following result:
4aisy KK.@@
Xa#ir- ;CK.EJ
Vara- DFDF.DF
0yan- CDIJ.E
Mahna/- C@D.@@
MAT SOFT
JAVA REFERENCE GUIDE
178
Vara's curr!nt balanc!- FFDF.DF
T@E TREEMAP CLASS
The TreeMap class implements the Map interface by using a tree. A TreeMap provides an efficient
means of storing key/value pairs in sorted order, and allows rapid retrieval.
You should note that, unlike a hash map, a tree map guarantees that its elements will be sorted in
ascending key order.
The TreeMap class supports four constructors. The first form constructs an empty tree map that will be
sorted by using the natural order of its keys:
Tr!!Map$ (
The second form constructs an empty tree-based map that will be sorted by using the Comparator
comp:
Tr!!Map$,omparator comp(
The third form initializes a tree map with the entries from m, which will be sorted by using the natural
order of the keys:
Tr!!Map$Map m(
The fourth form initializes a tree map with the entries from sm, which will be sorted in the same order
as sm:
Tr!!Map$%ort!#Map sm(
Apart from the methods inherited from its parent classes, TreeMap defines following methods:
SN Methods 3ith )escription
1 void c$ear,/
Removes all mappings from this TreeMap.
2 !"#ect c$one,/
Returns a shallow copy of this TreeMap instance.
3 Comparator comparator,/
Returns the comparator used to order this map, or null if this map uses its keys' natural order.
MAT SOFT
JAVA REFERENCE GUIDE
179
4 "oo$ean contains6ey,!"#ect =ey/
Returns true if this map contains a mapping for the specified key.
5 "oo$ean contains*a$e,!"#ect va$e/
Returns true if this map maps one or more keys to the specified value.
6 Set entrySet,/
Returns a set view of the mappings contained in this map.
7 !"#ect first6ey,/
Returns the first (lowest) key currently in this sorted map.
8 !"#ect get,!"#ect =ey/
Returns the value to which this map maps the specified key.
9 SortedMap headMap,!"#ect to6ey/
Returns a view of the portion of this map whose keys are strictly less than toKey.
10 Set =eySet,/
Returns a Set view of the keys contained in this map.
11 !"#ect $ast6ey,/
Returns the last (highest) key currently in this sorted map.
12 !"#ect pt,!"#ect =ey< !"#ect va$e/
Associates the specified value with the specified key in this map.
13 void pt%$$,Map map/
Copies all of the mappings from the specified map to this map.
14 !"#ect remove,!"#ect =ey/
Removes the mapping for this key from this TreeMap if present.
15 int si2e,/
Returns the number of key-value mappings in this map.
16 SortedMap s"Map,!"#ect from6ey< !"#ect to6ey/
Returns a view of the portion of this map whose keys range from fromKey, inclusive, to toKey,
exclusive.
17 SortedMap tai$Map,!"#ect from6ey/
Returns a view of the portion of this map whose keys are greater than or equal to fromKey.
18 Co$$ection va$es,/
MAT SOFT
JAVA REFERENCE GUIDE
180
Returns a collection view of the values contained in this map.
Example:
The following program illustrates several of the methods supported by this collection:
import java.util.**
class Tr!!Map4!mo {
public static voi# main$%tring args&'( {
// ,r!at! a hash map
Tr!!Map tm 9 n!w Tr!!Map$(*
// Put !l!m!nts to th! map
tm.put$)Vara)2 n!w 4oubl!$DFDF.DF((*
tm.put$)Mahna/)2 n!w 4oubl!$C@D.@@((*
tm.put$)0yan)2 n!w 4oubl!$CDIJ.EE((*
tm.put$)4aisy)2 n!w 4oubl!$KK.@@((*
tm.put$)Xa#ir)2 n!w 4oubl!$;CK.EJ((*

// 8!t a s!t of th! !ntri!s
%!t s!t 9 tm.!ntry%!t$(*
// 8!t an it!rator
6t!rator i 9 s!t.it!rator$(*
// 4isplay !l!m!nts
whil!$i.has=!:t$(( {
Map.3ntry m! 9 $Map.3ntry(i.n!:t$(*
%yst!m.out.print$m!.g!tY!y$( > )- )(*
%yst!m.out.println$m!.g!tBalu!$((*
+
%yst!m.out.println$(*
// 4!posit CEEE into Vara's account
#oubl! balanc! 9 $$4oubl!(tm.g!t$)Vara)((.#oubl!Balu!$(*
tm.put$)Vara)2 n!w 4oubl!$balanc! > CEEE((*
%yst!m.out.println$)Vara's n!w balanc!- ) >
tm.g!t$)Vara)((*
+
+
This would produce following result:
0yan- CDIJ.E
4aisy KK.@@
Mahna/- C@D.@@
Xa#ir- ;CK.EJ
Vara- DFDF.DF
Vara's curr!nt balanc!- FFDF.DF
ENERICS
MAT SOFT
JAVA REFERENCE GUIDE
181
It would be nice if we could write a single sort method that could sort the elements in an Integer
array, a String array or an array of any type that supports ordering.
Java ?eneric methods and generic classes enable programmers to specify, with a single method
declaration, a set of related methods or, with a single class declaration, a set of related types,
respectively.
Generics also provide compile-time type safety that allows programmers to catch invalid types at
compile time.
Using Java Generic concept we might write a generic method for sorting an array of objects, then
invoke the generic method with Integer arrays, Double arrays, String arrays and so on, to sort the
array elements.
Generic Methods:
You can write a single generic method declaration that can be called with arguments of different types.
Based on the types of the arguments passed to the generic method, the compiler handles each
method call appropriately. Following are the rules to define Generic Methods:
All generic method declarations have a type parameter section delimited by angle brackets (<
and >) that precedes the method's return type ( < E > in the next example).
Each type parameter section contains one or more type parameters separated by commas. A
type parameter, also known as a type variable, is an identifier that specifies a generic type
name.
The type parameters can be used to declare the return type and act as placeholders for the
types of the arguments passed to the generic method, which are known as actual type
arguments.
A generic method's body is declared like that of any other method. Note that type parameters
can represent only reference types not primitive types (like int, double and char).
Example:
Following example illustrate how we can print array of different type using a single Generic method:
public class 8!n!ricM!tho#T!st
{
// g!n!ric m!tho# print0rray
public static N 3 . voi# print0rray$ 3&' input0rray (
{
// 4isplay array !l!m!nts
for $ 3 !l!m!nt - input0rray ({
%yst!m.out.printf$ )Ws )2 !l!m!nt (*
+
%yst!m.out.println$(*
+
public static voi# main$ %tring args&' (
{
MAT SOFT
JAVA REFERENCE GUIDE
182
// ,r!at! arrays of 6nt!g!r2 4oubl! an# ,haract!r
6nt!g!r&' int0rray 9 { C2 @2 D2 F2 H +*
4oubl!&' #oubl!0rray 9 { C.C2 @.@2 D.D2 F.F +*
,haract!r&' char0rray 9 { ''2 '3'2 '1'2 '1'2 '?' +*
%yst!m.out.println$ )0rray int!g!r0rray contains-) (*
print0rray$ int0rray (* // pass an 6nt!g!r array
%yst!m.out.println$ )On0rray #oubl!0rray contains-) (*
print0rray$ #oubl!0rray (* // pass a 4oubl! array
%yst!m.out.println$ )On0rray charact!r0rray contains-) (*
print0rray$ char0rray (* // pass a ,haract!r array
+
+
This would produce following result:
0rray int!g!r0rray contains-
C @ D F H M
0rray #oubl!0rray contains-
C.C @.@ D.D F.F
0rray charact!r0rray contains-
3 1 1 ?
Bounded Type Parameters:
There may be times when you'll want to restrict the kinds of types that are allowed to be passed to a
type parameter. For example, a method that operates on numbers might only want to accept instances
of Number or its subclasses. This is what bounded type parameters are for.
To declare a bounded type parameter, list the type parameter's name, followed by the extends
keyword, followed by its upper bound.
Example:
Following example illustrate how extends is used in a general sense to mean either "extends" (as in
classes) or "implements" (as in interfaces). This example is Generic method to return the largest of
three Comparable objects:
public class Ma:imumT!st
{
// #!t!rmin!s th! larg!st of thr!! ,omparabl! obj!cts
public static NT !:t!n#s ,omparabl!NT.. T ma:imum$T :2 T y2 T /(
{
T ma: 9 :* // assum! : is initially th! larg!st
if $ y.compar!To$ ma: ( . E ({
ma: 9 y* // y is th! larg!st so far
MAT SOFT
JAVA REFERENCE GUIDE
183
+
if $ /.compar!To$ ma: ( . E ({
ma: 9 /* // / is th! larg!st now
+
r!turn ma:* // r!turns th! larg!st obj!ct
+
public static voi# main$ %tring args&' (
{
%yst!m.out.printf$ )Ma: of W#2 W# an# W# is W#OnOn)2
D2 F2 H2 ma:imum$ D2 F2 H ( (*
%yst!m.out.printf$ )Ma:m of W.Cf2W.Cf an# W.Cf is W.CfOnOn)2
M.M2 J.J2 I.I2 ma:imum$ M.M2 J.J2 I.I ( (*
%yst!m.out.printf$ )Ma: of Ws2 Ws an# Ws is WsOn)2)p!ar)2
)appl!)2 )orang!)2 ma:imum$ )p!ar)2 )appl!)2 )orang!) ( (*
+
+
This would produce following result:
Ma:imum of D2 F an# H is H
Ma:imum of M.M2 J.J an# I.I is J.J
Ma:imum of p!ar2 appl! an# orang! is p!ar
Generic Classes:
A generic class declaration looks like a non-generic class declaration, except that the class name is
followed by a type parameter section.
As with generic methods, the type parameter section of a generic class can have one or more type
parameters separated by commas. These classes are known as parameterized classes or
parameterized types because they accept one or more parameters.
Example:
Following example illustrate how we can define a generic class:
public class Lo:NT. {
privat! T t*
public voi# a##$T t( {
this.t 9 t*
+
public T g!t$( {
r!turn t*
MAT SOFT
JAVA REFERENCE GUIDE
184
+
public static voi# main$%tring&' args( {
Lo:N6nt!g!r. int!g!rLo: 9 n!w Lo:N6nt!g!r.$(*
Lo:N%tring. stringLo: 9 n!w Lo:N%tring.$(*

int!g!rLo:.a##$n!w 6nt!g!r$CE((*
stringLo:.a##$n!w %tring$)!llo "orl#)((*
%yst!m.out.printf$)6nt!g!r Balu! -W#OnOn)2 int!g!rLo:.g!t$((*
%yst!m.out.printf$)%tring Balu! -WsOn)2 stringLo:.g!t$((*
+
+
This would produce following result:
6nt!g!r Balu! -CE
%tring Balu! -!llo "orl#
Day 22: IO Str%ams
The java.io package contains nearly every class you might ever need to perform input and output
(I/O) in Java. All these streams represent an input source and an output destination. The stream in
the java.io package supports many data such as primitives, Object, localized characters etc.
A stream can be defined as a sequence of data. The InputStream is used to read data from a source
and the OutputStream is used for writing data to a destination.
Java does provide strong, flexible support for I/O as it relates to files and networks but this material
covers very basic functionlity related to streams and I/O. We would see most commonly used example
one by one:
Reading Console Input:
Java input console is accomplished by reading from System1in. To obtain a character-based stream
that is attached to the console, you wrap System1in in a Bffered'eader object, to create a
character stream. Here is most common syntax to obtain BufferedReader:
Luff!r!#7!a#!r br 9 n!w Luff!r!#7!a#!r$n!w
6nput%tr!am7!a#!r$%yst!m.in((*
Once BufferedReader is obtained, we can use read( ) method to reach a character or readLine( )
method to read a string from the console.
MAT SOFT
JAVA REFERENCE GUIDE
185
Reading Characters from Console:
To read a character from a BufferedReader, we would read( ) method whose sytax is as follows:
int r!a#$ ( throws 6?3:c!ption
Each time that read( ) is called, it reads a character from the input stream and returns it as an integer
value. It returns .1 when the end of the stream is encountered. As you can see, it can throw an
IOException.
The following program demonstrates read( ) by reading characters from the console until the user
types a "q":
// 5s! a Luff!r!#7!a#!r to r!a# charact!rs from th! consol!.
import java.io.**
class L77!a# {
public static voi# main$%tring args&'( throws 6?3:c!ption
{
char c*
// ,r!at! a Luff!r!#7!a#!r using %yst!m.in
Luff!r!#7!a#!r br 9 n!w Luff!r!#7!a#!r$n!w
6nput%tr!am7!a#!r$%yst!m.in((*
%yst!m.out.println$)3nt!r charact!rs2 'P' to Puit.)(*
// r!a# charact!rs
#o {
c 9 $char( br.r!a#$(*
%yst!m.out.println$c(*
+ whil!$c G9 'P'(*
+
+
Here is a sample run:
3nt!r charact!rs2 'P' to Puit.
C@DabcP
C
@
D
a
b
c
P
Reading Strings from Console:
To read a string from the keyboard, use the version of readLine( ) that is a member of the
BufferedReader class. Its general form is shown here:
MAT SOFT
JAVA REFERENCE GUIDE
186
%tring r!a#1in!$ ( throws 6?3:c!ption
The following program demonstrates BufferedReader and the readLine( ) method. The program reads
and displays lines of text until you enter the word "end":
// 7!a# a string from consol! using a Luff!r!#7!a#!r.
import java.io.**
class L77!a#1in!s {
public static voi# main$%tring args&'( throws 6?3:c!ption
{
// ,r!at! a Luff!r!#7!a#!r using %yst!m.in
Luff!r!#7!a#!r br 9 n!w Luff!r!#7!a#!r$n!w
6nput%tr!am7!a#!r$%yst!m.in((*
%tring str*
%yst!m.out.println$)3nt!r lin!s of t!:t.)(*
%yst!m.out.println$)3nt!r '!n#' to Puit.)(*
#o {
str 9 br.r!a#1in!$(*
%yst!m.out.println$str(*
+ whil!$Gstr.!Puals$)!n#)((*
+
+
Here is a sample run:
3nt!r lin!s of t!:t.
3nt!r '!n#' to Puit.
This is lin! on!
This is lin! on!
This is lin! two
This is lin! two
!n#
!n#
Writing Console Output:
Console output is most easily accomplished with print, / and print$n, /, described earlier. These
methods are defined by the class PrintStream which is the type of the object referenced
by System1ot. Even though System.out is a byte stream, using it for simple program output is still
acceptable.
Because PrintStream is an output stream derived from OutputStream, it also implements the low-level
method write( ). Thus, write( ) can be used to write to the console. The simplest form of write( )
defined by PrintStream is shown here:
voi# writ!$int byt!val(
This method writes to the stream the byte specified by byteval. Although byteval is declared as an
integer, only the low-order eight bits are written.
MAT SOFT
JAVA REFERENCE GUIDE
187
Example:
Here is a short example that uses write( ) to output the character "A" followed by a newline to the
screen:
import java.io.**
// 4!monstrat! %yst!m.out.writ!$(.
class "rit!4!mo {
public static voi# main$%tring args&'( {
int b*
b 9 '0'*
%yst!m.out.writ!$b(*
%yst!m.out.writ!$'On'(*
+
+
This would produce simply 'A' character on the output screen.
0
Note: You will not often use write( ) to perform console output because print( ) and println( ) are
substantially easier to use.
Reading and Writing Files:
As described earlier, A stream can be defined as a sequence of data. The InputStream is used to read
data from a source and the OutputStream is used for writing data to a destination.
Here is a hierarchy of classes to deal with Input and Output streams.
MAT SOFT
JAVA REFERENCE GUIDE
188
The two important streams are FileInputStream and FileOutputStream which would be discussed in
this material:
FileInputStream:
This stream is used for reading data from the files. Objects can be created using the keyword new and
there are several types of constructors available.
Following constructor takes a file name as a string to create an input stream object to read the file.:
6nput%tr!am f 9 n!w Fil!6nput%tr!am$),-/java/h!llo)(*
Following constructor takes a file object to create an input stream object to read the file. First we
create a file object using File() method as follows:
Fil! f 9 n!w Fil!$),-/java/h!llo)(*
6nput%tr!am f 9 n!w Fil!6nput%tr!am$f(*
Once you have 5nput2tream object in hand then there is a list of helper methods which can be used to
read to stream or to do other operations on the stream.
SN Methods 3ith )escription
1 p"$ic void c$ose,/ thro3s I!7xceptionCD
This method closes the file output stream. Releases any system resources associated with the
file. Throws an IOException.
2 protected void fina$i2e,/thro3s I!7xception CD
This method cleans up the connection to the file. Ensures that the close method of this file output
stream is called when there are no more references to this stream. Throws an IOException.
3 p"$ic int read,int r/thro3s I!7xceptionCD
This method reads the specified byte of data from the InputStream. Returns an int. Returns the
next byte of data and -1 will be returned if it's end of file.
4 p"$ic int read,"yte-. r/ thro3s I!7xceptionCD
This method reads r.length bytes from the input stream into an array. Returns the total number
of bytes read. If end of file -1 will be returned.
5 p"$ic int avai$a"$e,/ thro3s I!7xceptionCD
Gives the number of bytes that can be read from this file input stream. Returns an int.
FileOutputStream:
MAT SOFT
JAVA REFERENCE GUIDE
189
FileOutputStream is used to create a file and write data into it.The stream would create a file, if it
doesn't already exist, before opening it for output.
Here are two constructors which can be used to create a FileOutputStream object.
Following constructor takes a file name as a string to create an input stream object to write the file.:
?utput%tr!am f 9 n!w Fil!?utput%tr!am$),-/java/h!llo)(
Following constructor takes a file object to create an output stream object to write the file. First we
create a file object using File() method as follows:
Fil! f 9 n!w Fil!$),-/java/h!llo)(*
?utput%tr!am f 9 n!w Fil!?utput%tr!am$f(*
Once you have Output2tream object in hand then there is a list of helper methods which can be used
to write to stream or to do other operations on the stream.
SN Methods 3ith )escription
1 p"$ic void c$ose,/ thro3s I!7xceptionCD
This method closes the file output stream. Releases any system resources associated with the
file. Throws an IOException.
2 protected void fina$i2e,/thro3s I!7xception CD
This method cleans up the connection to the file. Ensures that the close method of this file output
stream is called when there are no more references to this stream. Throws an IOException.
3 p"$ic void 3rite,int 3/thro3s I!7xceptionCD
This methods writes the specified byte to the output stream.
4 p"$ic void 3rite,"yte-. 3/
Writes w.length bytes from the mentioned byte array to the OutputStream.
Example:
Following is the example to demonstrate InputStream and OutputStream:
import java.io.**
public class fil!%tr!amT!st{
public static voi# main$%tring args&'({

try{
byt! b"rit! &' 9 {CC2@C2D2FE2H+*
MAT SOFT
JAVA REFERENCE GUIDE
190
?utput%tr!am os 9 n!w Fil!?utput%tr!am$),-/t!st.t:t)(*
for$int :9E* : N b"rit!.l!ngth * :>>({
os.writ!$ b"rit!&:' (* // writ!s th! byt!s
+
os.clos!$(*

6nput%tr!am is 9 n!w Fil!6nput%tr!am$),-/t!st.t:t)(*
int si/! 9 is.availabl!$(*
for$int i9E* iN si/!* i>>({
%yst!m.out.print$$char(is.r!a#$( > ) )(*
+
is.clos!$(*
+catch$6?3:c!ption !({
%yst!m.out.print$)3:c!ption)(*
+
+
+
The above code would create file test.txt and would write given numbers in binary format. Same
would be output on the stdout screen.
ByteArrayInputStream class
The ByteArrayInputStream class allows a buffer in the memory to be used as an InputStream. The
input source is a byte array. There are following forms of constructors to create ByteArrayInputStream
objects
Takes a byte array as the parameter:
Lyt!0rray6nput%tr!am b0rray 9 n!w Lyt!0rray6nput%tr!am$byt! &' a(*
Another form takes an array of bytes, and two ints, where off is the first byte to be read and $enis the
number of bytes to be read.
Lyt!0rray6nput%tr!am b0rray 9 n!w Lyt!0rray6nput%tr!am$byt! &'a2
int off2
int l!n(
Once you have Byte-rray5nput2tream object in hand then there is a list of helper methods which can
be used to read the stream or to do other operations on the stream.
SN Methods 3ith )escription
1 p"$ic int read,/
This method reads the next byte of data from the InputStream. Returns an int as the next byte of
data. If it is end of file then it returns -1.
2 p"$ic int read,"yte-. r< int off< int $en/
MAT SOFT
JAVA REFERENCE GUIDE
191
This method reads upto $en number of bytes starting from off from the input stream into an
array. Returns the total number of bytes read. If end of file -1 will be returned.
3 p"$ic int avai$a"$e,/
Gives the number of bytes that can be read from this file input stream. Returns an int that gives
the number of bytes to be read.
4 p"$ic void mar=,int read/
This sets the current marked position in the stream. The parameter gives the maximum limit of
bytes that can be read before the marked position becomes invalid.
5 p"$ic $ong s=ip,$ong n/
Skips n number of bytes from the stream. This returns the actual number of bytes skipped.
Example:
Following is the example to demonstrate ByteArrayInputStream and ByteArrayOutputStream
import java.io.**
class Lyt!%tr!amT!st{
public static voi# main$%tring args&'(throws 6?3:c!ption{
Lyt!0rray?utput%tr!am b?utput 9 n!w Lyt!0rray?utput%tr!am$C@(*
whil!$ b?utput.si/!$(G9 CE ({
// 8!ts th! inputs from th! us!r
b?utput.writ!$%yst!m.in.r!a#$((*
+
byt! b &' 9 b?utput.toLyt!0rray$(*
%yst!m.out.println$)Print th! cont!nt)(*
for$int :9 E * : N b.l!ngth* :>>({
//printing th! charact!rs
%yst!m.out.print$$char(b&:' > ) )(*
+
%yst!m.out.println$) )(*
int c*
Lyt!0rray6nput%tr!am b6nput 9 n!w Lyt!0rray6nput%tr!am$b(*
%yst!m.out.println$),onv!rting charact!rs to 5pp!r cas! ) (*
for$int y 9 E * y N C* y>> ({
whil!$$ c9 b6nput.r!a#$((G9 ;C({
%yst!m.out.println$,haract!r.to5pp!r,as!$$char(c((*
+
b6nput.r!s!t$(*
+
MAT SOFT
JAVA REFERENCE GUIDE
192
+
+
Here is the sample run of the above program:
as#fghj<ly
Print th! cont!nt
a s # f g h j < l y
,onv!rting charact!rs to 5pp!r cas!
0
%
4
F
8

J
Y
1
A
ByteArrayOutputStream
The ByteArrayOutputStream class stream creates a buffer in memory and all the data sent to the
stream is stored in the buffer. There are following forms of constructors to create
ByteArrayOutputStream objects
Following constructor creates a buffer of 32 byte:
?utput%tr!am b?ut 9 n!w Lyt!0rray?utput%tr!am$(
Following constructor creates a buffer of size int a:
?utput%tr!m b?ut 9 n!w Lyt!0rray?utput%tr!am$int a(
Once you have Byte-rrayOutput2tream object in hand then there is a list of helper methods which can
be used to write the stream or to do other operations on the stream.
SN Methods 3ith )escription
1 p"$ic void reset,/
This method resets the number of valid bytes of the byte array output stream to zero, so all the
accumulated output in the stream will be discarded.
2 p"$ic "yte-. toByte%rray,/
MAT SOFT
JAVA REFERENCE GUIDE
193
This method creates a newly allocated Byte array. Its size would be the current size of the output
stream and the contents of the buffer will be copied into it. Returns the current contents of the
output stream as a byte array.
3 p"$ic String toString,/
Converts the buffer content into a string. Translation will be done according to the default
character encoding. Returns the String translated from the buffer.s content.
4 p"$ic void 3rite,int 3/
Writes the specified array to the output stream.
5 p"$ic void 3rite,"yte -."< int of< int $en/
Writes len number of bytes starting from offset off to the stream.
6 p"$ic void 3riteTo,!tptStream otSt/
Writes the entire content of this Stream to the specified stream argument.
Example:
Following is the example to demonstrate ByteArrayOutputStream and ByteArrayOutputStream
import java.io.**
class Lyt!%tr!amT!st{
public static voi# main$%tring args&'(throws 6?3:c!ption{
Lyt!0rray?utput%tr!am b?utput 9 n!w Lyt!0rray?utput%tr!am$C@(*
whil!$ b?utput.si/!$(G9 CE ({
// 8!ts th! inputs from th! us!r
b?utput.writ!$%yst!m.in.r!a#$((*
+
byt! b &' 9 b?utput.toLyt!0rray$(*
%yst!m.out.println$)Print th! cont!nt)(*
for$int :9 E * : N b.l!ngth* :>>({
//printing th! charact!rs
%yst!m.out.print$$char(b&:' > ) )(*
+
%yst!m.out.println$) )(*
int c*
Lyt!0rray?utput%tr!am b6nput 9 n!w Lyt!0rray?utput%tr!am$b(*
%yst!m.out.println$),onv!rting charact!rs to 5pp!r cas! ) (*
for$int y 9 E * y N C* y>> ({
whil!$$ c9 b6nput.r!a#$((G9 ;C({
MAT SOFT
JAVA REFERENCE GUIDE
194
%yst!m.out.println$,haract!r.to5pp!r,as!$$char(c((*
+
b6nput.r!s!t$(*
+
+
+
Here is the sample run of the above program:
as#fghj<ly
Print th! cont!nt
a s # f g h j < l y
,onv!rting charact!rs to 5pp!r cas!
0
%
4
F
8

J
Y
1
A
DataInputStream class
The DataInputStream is used in the context of DataOutputStream and can be used to read primitives.
Following is the constructor to create an InputStream:
6nput%tr!am in 9 4ata6nput%tr!am$6nput%tr!am in(*
Once you have 6ata5nput2tream object in hand then there is a list of helper methods which can be
used to read the stream or to do other operations on the stream.
SN Methods 3ith )escription
1 p"$ic fina$ int read,"yte-. r< int off< int $en/thro3s I!7xception
Reads up to len bytes of data from the input stream into an array of bytes. Returns the total
number of bytes read into the buffer otherwise -1 if it is end of file.
2 P"$ic fina$ int read,"yte -. "/thro3s I!7xception
Reads some bytes from the inputstream an stores in to the byte array. Returns the total number
of bytes read into the buffer otherwise -1 if it is end of file.
3 ,a/ p"$ic fina$ Boo$ean readBooo$ean,/thro3s I!7xception<
,"/ p"$ic fina$ "yte readByte,/thro3s I!7xception<
,c/ p"$ic fina$ short readShort,/thro3s I!7xception
MAT SOFT
JAVA REFERENCE GUIDE
195
,d/ p"$ic fina$ Int readInt,/thro3s I!7xception
These methods will read the bytes from the contained InputStream. Returns the next two bytes
of the InputStream as the specific primitive type.
4 p"$ic String read0ine,/ thro3s I!7xception
Reads the next line of text from the input stream. It reads successive bytes, converting each byte
separately into a character, until it encounters a line terminator or end of file; the characters read
are then returned as a String.
Example:
Following is the example to demonstrate DataInputStream and DataInputStream. This example reads
5 lines given in a file test.txt and convert those lines into capital letters and finally copies them into
another file test1.txt.
import java.io.**
public class T!st{
public static voi# main$%tring args&'(throws 6?3:c!ption{
4ata6nput%tr!am # 9 n!w 4ata6nput%tr!am$n!w
Fil!6nput%tr!am$)t!st.t:t)((*
4ata?utput%tr!am out 9 n!w 4ata?utput%tr!am$n!w
Fil!?utput%tr!am$)t!stC.t:t)((*
%tring count*
whil!$$count 9 #.r!a#1in!$(( G9 null({
%tring u 9 count.to5pp!r,as!$(*
%yst!m.out.println$u(*
out.writ!Lyt!s$u > ) 2)(*
+
#.clos!$(*
out.clos!$(*
+
+
Here is the sample run of the above program:
T6% 6% T3%T C 2
T6% 6% T3%T @ 2
T6% 6% T3%T D 2
T6% 6% T3%T F 2
T6% 6% T3%T H 2
DataOutputStream class
MAT SOFT
JAVA REFERENCE GUIDE
196
The DataInputStream stream let you write the primitives to an output source.
Following is the constructor to create an DataOutputStream.
4ata?utput%tr!am out 9 4ata?utput%tr!am$?utput%tr!am out(*
Once you have 6ataOutput2tream object in hand then there is a list of helper methods which can be
used to write the stream or to do other operations on the stream.
SN Methods 3ith )escription
1 p"$ic fina$ void 3rite,"yte-. 3< int off< int $en/thro3s I!7xception
Writes len bytes from the specified byte array starting at point off , to the underlying stream.
2 P"$ic fina$ int 3rite,"yte -. "/thro3s I!7xception
Writes the current number of bytes written to this data output stream. Returns the total number
of bytes write into the buffer.
3 ,a/ p"$ic fina$ void 3riteBooo$ean,/thro3s I!7xception<
,"/ p"$ic fina$ void 3riteByte,/thro3s I!7xception<
,c/ p"$ic fina$ void 3riteShort,/thro3s I!7xception
,d/ p"$ic fina$ void 3riteInt,/thro3s I!7xception
These methods will write the specific primitive type data into the output stream as bytes.
4 P"$ic void f$sh,/thro3s I!7xception
Flushes the data output stream.
5 p"$ic fina$ void 3riteBytes,String s/ thro3s I!7xception
Writes out the string to the underlying output stream as a sequence of bytes. Each character in
the string is written out, in sequence, by discarding its high eight bits.
Example:
Following is the example to demonstrate DataInputStream and DataInputStream. This example reads
5 lines given in a file test.txt and convert those lines into capital letters and finally copies them into
another file test1.txt.
import java.io.**
public class T!st{
public static voi# main$%tring args&'(throws 6?3:c!ption{
4ata6nput%tr!am # 9 n!w 4ata6nput%tr!am$n!w
Fil!6nput%tr!am$)t!st.t:t)((*
4ata?utput%tr!am out 9 n!w 4ata?utput%tr!am$n!w
Fil!?utput%tr!am$)t!stC.t:t)((*
MAT SOFT
JAVA REFERENCE GUIDE
197
%tring count*
whil!$$count 9 #.r!a#1in!$(( G9 null({
%tring u 9 count.to5pp!r,as!$(*
%yst!m.out.println$u(*
out.writ!Lyt!s$u > ) 2)(*
+
#.clos!$(*
out.clos!$(*
+
+
Here is the sample run of the above program:
T6% 6% T3%T C 2
T6% 6% T3%T @ 2
T6% 6% T3%T D 2
T6% 6% T3%T F 2
T6% 6% T3%T H 2
File Navigation and I/O:
There are several other classes that we would be going through to get to know the basics of File
Navigation and I/O.
File class
Java File class represents the files and directory pathnames in an abstract manner. This class is used
for creation of files and directories, file searching, file deletion etc.
The File object represents the actual file/directory on the disk. There are following constructors to
create a File object:
Following syntax creates a new File instance from a parent abstract pathname and a child pathname
string.
Fil!$Fil! par!nt2 %tring chil#(*
Following syntax creates a new File instance by converting the given pathname string into an abstract
pathname.
Fil!$%tring pathnam!(
Following syntax creates a new File instance from a parent pathname string and a child pathname
string.
MAT SOFT
JAVA REFERENCE GUIDE
198
Fil!$%tring par!nt2 %tring chil#(
Following syntax creates a new File instance by converting the given file: URI into an abstract
pathname.
Fil!$576 uri(
Once you have 'ile object in hand then there is a list of helper methods which can be used manipulate
the files.
SN Methods 3ith )escription
1 p"$ic String getName,/
Returns the name of the file or directory denoted by this abstract pathname.
2 p"$ic String getParent,/
Returns the pathname string of this abstract pathname's parent, or null if this pathname does not
name a parent directory.
3 p"$ic +i$e getParent+i$e,/
Returns the abstract pathname of this abstract pathname's parent, or null if this pathname does
not name a parent directory.
4 p"$ic String getPath,/
Converts this abstract pathname into a pathname string.
5 p"$ic "oo$ean is%"so$te,/
Tests whether this abstract pathname is absolute. Returns true if this abstract pathname is
absolute, false otherwise
6 p"$ic String get%"so$tePath,/
Returns the absolute pathname string of this abstract pathname.
7 p"$ic "oo$ean can'ead,/
Tests whether the application can read the file denoted by this abstract pathname. Returns true if
and only if the file specified by this abstract pathname exists and can be read by the application;
false otherwise.
8 p"$ic "oo$ean can9rite,/
Tests whether the application can modify to the file denoted by this abstract pathname. Returns
true if and only if the file system actually contains a file denoted by this abstract pathname and
the application is allowed to write to the file; false otherwise.
9 p"$ic "oo$ean exists,/
Tests whether the file or directory denoted by this abstract pathname exists. Returns true if and
MAT SOFT
JAVA REFERENCE GUIDE
199
only if the file or directory denoted by this abstract pathname exists; false otherwise
10 p"$ic "oo$ean is)irectory,/
Tests whether the file denoted by this abstract pathname is a directory. Returns true if and only if
the file denoted by this abstract pathname exists and is a directory; false otherwise.
11 p"$ic "oo$ean is+i$e,/
Tests whether the file denoted by this abstract pathname is a normal file. A file is normal if it is
not a directory and, in addition, satisfies other system-dependent criteria. Any non-directory file
created by a Java application is guaranteed to be a normal file. Returns true if and only if the file
denoted by this abstract pathname exists and is a normal file; false otherwise
12 p"$ic $ong $astModified,/
Returns the time that the file denoted by this abstract pathname was last modified. Returns a
long value representing the time the file was last modified, measured in milliseconds since the
epoch (00:00:00 GMT, January 1, 1970), or 0L if the file does not exist or if an I/O error occurs.
13 p"$ic $ong $ength,/
Returns the length of the file denoted by this abstract pathname. The return value is unspecified
if this pathname denotes a directory.
14 p"$ic "oo$ean createNe3+i$e,/ thro3s I!7xception
Atomically creates a new, empty file named by this abstract pathname if and only if a file with
this name does not yet exist. Returns true if the named file does not exist and was successfully
created; false if the named file already exists.
15 p"$ic "oo$ean de$ete,/
Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a
directory, then the directory must be empty in order to be deleted. Returns true if and only if the
file or directory is successfully deleted; false otherwise.
16 p"$ic void de$ete!n7xit,/
Requests that the file or directory denoted by this abstract pathname be deleted when the virtual
machine terminates.
17 p"$ic String-. $ist,/
Returns an array of strings naming the files and directories in the directory denoted by this
abstract pathname.
18 p"$ic String-. $ist,+i$ename+i$ter fi$ter/
Returns an array of strings naming the files and directories in the directory denoted by this
abstract pathname that satisfy the specified filter.
20 p"$ic +i$e-. $ist+i$es,/
Returns an array of abstract pathnames denoting the files in the directory denoted by this
abstract pathname.
MAT SOFT
JAVA REFERENCE GUIDE
200
21 p"$ic +i$e-. $ist+i$es,+i$e+i$ter fi$ter/
Returns an array of abstract pathnames denoting the files and directories in the directory
denoted by this abstract pathname that satisfy the specified filter.
22 p"$ic "oo$ean m=dir,/
Creates the directory named by this abstract pathname. Returns true if and only if the directory
was created; false otherwise
23 p"$ic "oo$ean m=dirs,/
Creates the directory named by this abstract pathname, including any necessary but nonexistent
parent directories. Returns true if and only if the directory was created, along with all necessary
parent directories; false otherwise.
24 p"$ic "oo$ean renameTo,+i$e dest/
Renames the file denoted by this abstract pathname. Returns true if and only if the renaming
succeeded; false otherwise
25 p"$ic "oo$ean set0astModified,$ong time/
Sets the last-modified time of the file or directory named by this abstract pathname. Returns true
if and only if the operation succeeded; false otherwise .
26 p"$ic "oo$ean set'ead!n$y,/
Marks the file or directory named by this abstract pathname so that only read operations are
allowed. Returns true if and only if the operation succeeded; false otherwise.
27 p"$ic static +i$e createTemp+i$e,String prefix< String sffix< +i$e directory/ thro3s
I!7xception
Creates a new empty file in the specified directory, using the given prefix and suffix strings to
generate its name. Returns an abstract pathname denoting a newly-created empty file.
28 p"$ic static +i$e createTemp+i$e,String prefix< String sffix/ thro3s I!7xception
Creates an empty file in the default temporary-file directory, using the given prefix and suffix to
generate its name. Invoking this method is equivalent to invoking createTempFile(prefix, suffix,
null). Returns abstract pathname denoting a newly-created empty file.
29 p"$ic int compareTo,+i$e pathname/
Compares two abstract pathnames lexicographically. Returns zero if the argument is equal to this
abstract pathname, a value less than zero if this abstract pathname is lexicographically less than
the argument, or a value greater than zero if this abstract pathname is lexicographically greater
than the argument.
30 p"$ic int compareTo,!"#ect o/
Compares this abstract pathname to another object. Returns returns zero if the argument is
equal to this abstract pathname, a value less than zero if this abstract pathname is
lexicographically less than the argument, or a value greater than zero if this abstract pathname is
lexicographically greater than the argument.
MAT SOFT
JAVA REFERENCE GUIDE
201
31 p"$ic "oo$ean e;a$s,!"#ect o"#/
Tests this abstract pathname for equality with the given object. Returns true if and only if the
argument is not null and is an abstract pathname that denotes the same file or directory as this
abstract pathname.
32 p"$ic String toString,/
Returns the pathname string of this abstract pathname. This is just the string returned by the
getPath() method.
Example:
Following is the example to demonstrate File object:
import java.io.Fil!*
class 4ir1ist {
public static voi# main$%tring args&'( {
%tring #irnam! 9 )/java)*
Fil! fC 9 n!w Fil!$#irnam!(*
if $fC.is4ir!ctory$(( {
%yst!m.out.println$ )4ir!ctory of ) > #irnam!(*
%tring s&' 9 fC.list$(*
for $int i9E* i N s.l!ngth* i>>( {
Fil! f 9 n!w Fil!$#irnam! > )/) > s&i'(*
if $f.is4ir!ctory$(( {
%yst!m.out.println$s&i' > ) is a #ir!ctory)(*
+ !ls! {
%yst!m.out.println$s&i' > ) is a fil!)(*
+
+
+ !ls! {
%yst!m.out.println$#irnam! > ) is not a #ir!ctory)(*
+
+
+
This would produce following result:
4ir!ctory of /mysPl
bin is a #ir!ctory
lib is a #ir!ctory
#!mo is a #ir!ctory
t!st.t:t is a fil!
7304M3 is a fil!
in#!:.html is a fil!
inclu#! is a #ir!ctory
MAT SOFT
JAVA REFERENCE GUIDE
202
Creating Directories:
There are two useful +i$e utility methods which can be used to create directories:
The m=dir, / method creates a directory, returning true on success and false on failure.
Failure indicates that the path specified in the File object already exists, or that the directory
cannot be created because the entire path does not exist yet.
The m=dirs,/ method creates both a directory and all the parents of the directory.
Following example creates "/tmp/user/java/bin" directory:
import java.io.Fil!*
class ,r!at!4ir {
public static voi# main$%tring args&'( {
%tring #irnam! 9 )/tmp/us!r/java/bin)*
Fil! # 9 n!w Fil!$#irnam!(*
// ,r!at! #ir!ctory now.
#.m<#irs$(*
+
+
Compile and execute above code to create "/tmp/user/java/bin".
Note: Java automatically takes care of path separators on UNIX and Windows as per conventions. If
you use a forward slash (/) on a Windows version of Java, the path will still resolve correctly.
MAT SOFT
JAVA REFERENCE GUIDE
203
)ay 5E: +I07 '7%)7'
This class inherits from the InputStreamReader class. FileReader is used for reading streams of
characters.
This class has several constructors to create required objects.
Following syntax creates a new FileReader, given the File to read from.
Fil!7!a#!r$Fil! fil!(
Following syntax creates a new FileReader, given the FileDescriptor to read from.
Fil!7!a#!r$Fil!4!scriptor f#(
Following syntax creates a new FileReader, given the name of the file to read from.
Fil!7!a#!r$%tring fil!=am!(
Once you have 'ile.eader object in hand then there is a list of helper methods which can be used
manipulate the files.
SN Methods 3ith )escription
1 p"$ic int read,/ thro3s I!7xception
Reads a single character. Returns an int, which represents the character read.
2 p"$ic int read,char -. c< int offset< int $en/
Reads characters into an array. Returns the number of characters read.
Example:
Following is the example to demonstrate class:
import java.io.**
public class Fil!7!a#{
public static voi# main$%tring args&'(throws 6?3:c!ption{
Fil! fil! 9 n!w Fil!$)!lloC.t:t)(*
// cr!at!s th! fil!
fil!.cr!at!=!wFil!$(*
// cr!at!s a Fil!"rit!r ?bj!ct
Fil!"rit!r writ!r 9 n!w Fil!"rit!r$fil!(*
// "rit!s th! cont!nt to th! fil!
MAT SOFT
JAVA REFERENCE GUIDE
204
writ!r.writ!$)ThisOn isOn anOn !:ampl!On)(*
writ!r.flush$(*
writ!r.clos!$(*
//,r!at!s a Fil!7!a#!r ?bj!ct
Fil!7!a#!r fr 9 n!w Fil!7!a#!r$fil!(*
char &' a 9 n!w char&HE'*
fr.r!a#$a(* // r!a#s th! cont!nt to th! array
for$char c - a(
%yst!m.out.print$c(* //prints th! charact!rs on! by on!
fr.clos!$(*
+
+
This would produce following result:
This
is
an
!:ampl!
FILE WRITER
This class inherits from the OutputStreamWriter class. The class is used for writing streams of
characters.
This class has several constructors to create required objects.
Following syntax creates a FileWriter object given a File object.
Fil!"rit!r$Fil! fil!(
Following syntax creates a FileWriter object given a File object.
Fil!"rit!r$Fil! fil!2 bool!an app!n#(
Following syntax creates a FileWriter object associated with a file descriptor.
Fil!"rit!r$Fil!4!scriptor f#(
Following syntax creates a FileWriter object given a file name.
Fil!"rit!r$%tring fil!=am!(
MAT SOFT
JAVA REFERENCE GUIDE
205
Following syntax creates a FileWriter object given a file name with a boolean indicating whether or not
to append the data written.
Fil!"rit!r$%tring fil!=am!2 bool!an app!n#(
Once you have 'ile*riter object in hand then there is a list of helper methods which can be used
manipulate the files.
SN Methods 3ith )escription
1 p"$ic void 3rite,int c/ thro3s I!7xception
Writes a single character.
2 p"$ic void 3rite,char -. c< int offset< int $en/
Writes a portion of an array of characters starting from offset and with a length of len.
3 p"$ic void 3rite,String s< int offset< int $en/
Write a portion of a String starting from offset and with a length of len.
Example:
Following is the example to demonstrate class:
import java.io.**
public class Fil!7!a#{
public static voi# main$%tring args&'(throws 6?3:c!ption{
Fil! fil! 9 n!w Fil!$)!lloC.t:t)(*
// cr!at!s th! fil!
fil!.cr!at!=!wFil!$(*
// cr!at!s a Fil!"rit!r ?bj!ct
Fil!"rit!r writ!r 9 n!w Fil!"rit!r$fil!(*
// "rit!s th! cont!nt to th! fil!
writ!r.writ!$)ThisOn isOn anOn !:ampl!On)(*
writ!r.flush$(*
writ!r.clos!$(*
//,r!at!s a Fil!7!a#!r ?bj!ct
Fil!7!a#!r fr 9 n!w Fil!7!a#!r$fil!(*
char &' a 9 n!w char&HE'*
fr.r!a#$a(* // r!a#s th! cont!nt to th! array
for$char c - a(
%yst!m.out.print$c(* //prints th! charact!rs on! by on!
fr.clos!$(*
+
+
MAT SOFT
JAVA REFERENCE GUIDE
206
This would produce following result:
This
is
an
!:ampl!
SERIALIZATION
Java provides a mechanism, called object serialization where an object can be represented as a
sequence of bytes that includes the object's data as well as information about the object's type and
the types of data stored in the object.
After a serialized object has been written into a file, it can be read from the file and deserialized that
is, the type information and bytes that represent the object and its data can be used to recreate the
object in memory.
Most impressive is that the entire process is JVM independent, meaning an object can be serialized on
one platform and deserialized on an entirely different platform.
Classes !"#ectInptStream and !"#ect!tptStream are high-level streams that contain the
methods for serializing and deserializing an object.
The ObjectOutputStream class contains many write methods for writing various data types, but one
method in particular stands out:
public final voi# writ!?bj!ct$?bj!ct :( throws 6?3:c!ption
The above method serializes an Object and sends it to the output stream. Similarly, the
ObjectInputStream class contains the following method for deserializing an object:
public final ?bj!ct r!a#?bj!ct$( throws 6?3:c!ption2
,lass=otFoun#3:c!ption
This method retrieves the next Object out of the stream and deserializes it. The return value is Object,
so you will need to cast it to its appropriate data type.
To demonstrate how serialization works in Java, I am going to use the Employee class that we
discussed early on in the book. Suppose that we have the following Employee class, which implements
the Serializable interface:
public class 3mploy!! impl!m!nts java.io.%!riali/abl!
{
public %tring nam!*
public %tring a##r!ss*
public int transi!nt %%=*
public int numb!r*
MAT SOFT
JAVA REFERENCE GUIDE
207
public voi# mail,h!c<$(
{
%yst!m.out.println$)Mailing a ch!c< to ) > nam!
> ) ) > a##r!ss(*
+
+
Notice that for a class to be serialized successfully, two conditions must be met:
The class must implement the java.io.Serializable interface.
All of the fields in the class must be serializable. If a field is not serializable, it must be marked
transient.
If you are curious to know if a Java Satandard Class is serializable or not, check the documentation for
the class. The test is simple: If the class implements java.io.Serializable, then it is serializable;
otherwise, it's not.
Serializing an Object:
The ObjectOutputStream class is used to serialize an Object. The following SerializeDemo program
instantiates an Employee object and serializes it to a file.
When the program is done executing, a file named employee.ser is created. The program does not
generate any output, but study the code and try to determine what the program is doing.
Note: When serializing an object to a file, the standard convention in Java is to give the file
a1ser extension.
import java.io.**
public class %!riali/!4!mo
{
public static voi# main$%tring &' args(
{
3mploy!! ! 9 n!w 3mploy!!$(*
!.nam! 9 )7!yan 0li)*
!.a##r!ss 9 )Pho<<a Yuan2 0mb!hta P!!r)*
!.%%= 9 CCC@@DDD*
!.numb!r 9 CEC*
try
{
Fil!?utput%tr!am fil!?ut 9
n!w Fil!?utput%tr!am$)!mploy!!.s!r)(*
?bj!ct?utput%tr!am out 9
n!w ?bj!ct?utput%tr!am$fil!?ut(*
out.writ!?bj!ct$!(*
out.clos!$(*
fil!?ut.clos!$(*
+catch$6?3:c!ption i(
{
i.print%tac<Trac!$(*
MAT SOFT
JAVA REFERENCE GUIDE
208
+
+
+
Deserializing an Object:
The following DeserializeDemo program deserializes the Employee object created in the SerializeDemo
program. Study the program and try to determine its output:
import java.io.**
public class 4!s!riali/!4!mo
{
public static voi# main$%tring &' args(
{
3mploy!! ! 9 null*
try
{
Fil!6nput%tr!am fil!6n 9
n!w Fil!6nput%tr!am$)!mploy!!.s!r)(*
?bj!ct6nput%tr!am in 9 n!w ?bj!ct6nput%tr!am$fil!6n(*
! 9 $3mploy!!( in.r!a#?bj!ct$(*
in.clos!$(*
fil!6n.clos!$(*
+catch$6?3:c!ption i(
{
i.print%tac<Trac!$(*
r!turn*
+catch$,lass=otFoun#3:c!ption c(
{
%yst!m.out.println$.3mploy!! class not foun#.(*
c.print%tac<Trac!$(*
r!turn*
+
%yst!m.out.println$)4!s!riali/!# 3mploy!!...)(*
%yst!m.out.println$)=am!- ) > !.nam!(*
%yst!m.out.println$)0##r!ss- ) > !.a##r!ss(*
%yst!m.out.println$)%%=- ) > !.%%=(*
%yst!m.out.println$)=umb!r- ) > !.numb!r(*
+
+
This would produce following result:
4!s!riali/!# 3mploy!!...
=am!- 7!yan 0li
0##r!ss-Pho<<a Yuan2 0mb!hta P!!r
%%=- E
=umb!r-CEC
Here are following important points to be noted:
MAT SOFT
JAVA REFERENCE GUIDE
209
The try/catch block tries to catch a ClassNotFoundException, which is declared by the
readObject() method. For a JVM to be able to deserialize an object, it must be able to find the
bytecode for the class. If the JVM can't find a class during the deserialization of an object, it
throws a ClassNotFoundException.
Notice that the return value of readObject() is cast to an Employee reference.
The value of the SSN field was 11122333 when the object was serialized, but because the field
is transient, this value was not sent to the output stream. The SSN field of the deserialized
Employee object is 0.
)ay 5F: J%*%1N7T
The term net0or( programming refers to writing programs that execute across multiple devices
(computers), in which the devices are all connected to each other using a network.
MAT SOFT
JAVA REFERENCE GUIDE
210
The java.net package of the J2SE APIs contains a collection of classes and interfaces that provide the
low-level communication details, allowing you to write programs that focus on solving the problem at
hand.
The java.net package provides support for the two common network protocols:
TCP: TCP stands for Transmission Control Protocol, which allows for reliable communication
between two applications. TCP is typically used over the Internet Protocol, which is referred to
as TCP/IP.
B)P: UDP stands for User Datagram Protocol, a connection-less protocol that allows for
packets of data to be transmitted between applications.
Below are the Commonly used classed in java networking programming
Inet%ddress
static InetAddress getByName(String hostname) thorws UnKnownHostException
static IntAddress getLocalHost()
static InetAddress[] getAllByName()
byte[] getAddress()
String getHostAddress()
String getHostName()
boolean isMulticastAddress()
boolean equals(Object Inetaddress)
Below example shows the use of InetAddress Class:
import java.net.*;
class InetTest
{
public static void main(String args[])
{
try
{
MAT SOFT
JAVA REFERENCE GUIDE
211
InetAddress iaddr=InetAddress.getByName("www.sribharadwaj.org");
System.out.println(iaddr);
System.out.println("Address: "+iaddr.getHostAddress());
System.out.println("Host Name: "+iaddr.getHostName());
boolean flag=iaddr.isMulticastAddress();
if(flag==true)
System.out.println("This is a multicast address");
else
System.out.println("This is a not multicast address");
InetAddress iadrs[]=InetAddress.getAllByName("www.nba.com");
for(int i=0;i<iadrs.length;i++)
{
System.out.println(iadrs[i]);
}
}catch(Exception e){}
}
}
B'0
URL(string protocol, String hostname, int port, String path) throws MalformedURLException
URL(String protocol, String hostname, String path) throws MalformedURLException
URL(URL urlobj, String urlspecifier) throws MalformedURLException
MAT SOFT
JAVA REFERENCE GUIDE
212
String getProtocol()
int getPort()
String getHost()
String getFile()
String toExternalForm()
URLconnection openConnection()
(HttpConnection)URLConnection openConnection()
Below examples shows us the use of URL Class:
import java.net.*;
class URLDemo
{
public static void main(String args[])
{
try
{
URL url=new URL("http://www.oracle.com");
System.out.println("Protocol "+ url.getProtocol());
System.out.println("Port "+url.getPort());
System.out.println("Host "+url.getHost());
System.out.println("File "+url.getFile());
System.out.println("External form "+url.toExternalForm());
}catch(MalformedURLException e){e.printStackTrace();}
MAT SOFT
JAVA REFERENCE GUIDE
213
}
}
B'0Connection
int getContentLength()
String getContentType()
long getDate()
long getExpiration()
String getHeaderField(int index)
String getHeaderField(String fieldname)
String getHeaderFieldKey(int index)
Map<String,List<String>> getHeaderFields()
long getLastModified()
InputStream getInputStream() throws IOException
(TTPB'0Connection
static boolean getFollowRedirects()
String getRequestMethod()
int getResponseCode()throws IOException
String getResponseMessage() throws IOException
static void setFollowRedirects(boolean how)
void setRequestMethod(String how)throws PorotocolException
Below is the example for URLConnection class:
MAT SOFT
JAVA REFERENCE GUIDE
214
import java.net.*;
import java.io.*;
import java.util.Date;
class UCDemo
{
public static void main(String args[])
{
try
{
URL url=new URL("http://www.internic.net");
URLConnection uc=url.openConnection();
long d=uc.getDate();
if(d==0) System.out.println("No date info");
else System.out.println("Date: "+new Date(d));
System.out.println("Content-Type:"+uc.getContentType());
d=uc.getLastModified();
if(d==0) System.out.println("No last modified information");
else System.out.println("Last Modified on: "+new Date(d));
int length=uc.getContentLength();
if(length==-1)System.out.println("Content Length unavailable");
else
MAT SOFT
JAVA REFERENCE GUIDE
215
{
System.out.println("Content Length: "+length);
InputStream ip=uc.getInputStream();
int c=0;
while((c=(int)ip.read())!=-1)
{
System.out.print((char)c);
}
ip.close();
}
}catch(Exception e){}
}
}
Day 25: Socket Programming:
Sockets provide the communication mechanism between two computers using TCP. A client program
creates a socket on its end of the communication and attempts to connect that socket to a server.
When the connection is made, the server creates a socket object on its end of the communication. The
client and server can now communicate by writing to and reading from the socket.
The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a
mechanism for the server program to listen for clients and establish connections with them.
The following steps occur when establishing a TCP connection between two computers using sockets:
MAT SOFT
JAVA REFERENCE GUIDE
216
1. The server instantiates a ServerSocket object, denoting which port number communication is
to occur on.
2. The server invokes the accept() method of the ServerSocket class. This method waits until a
client connects to the server on the given port.
3. After the server is waiting, a client instantiates a Socket object, specifying the server name
and port number to connect to.
4. The constructor of the Socket class attempts to connect the client to the specified server and
port number. If communication is established, the client now has a Socket object capable of
communicating with the server.
5. On the server side, the accept() method returns a reference to a new socket on the server
that is connected to the client's socket.
After the connections are established, communication can occur using I/O streams. Each socket has
both an OutputStream and an InputStream. The client's OutputStream is connected to the server's
InputStream, and the client's InputStream is connected to the server's OutputStream.
TCP is a twoway communication protocol, so data can be sent across both streams at the same time.
There are following usefull classes providing complete set of methods to implement sockets.
ServerSocket Class Methods:
The #ava1net1ServerSoc=et class is used by server applications to obtain a port and listen for client
requests
The ServerSocket class has four constructors:
SN Methods 3ith )escription
1 p"$ic ServerSoc=et,int port/ thro3s I!7xception
Attempts to create a server socket bound to the specified port. An exception occurs if the port is
already bound by another application.
2 p"$ic ServerSoc=et,int port< int "ac=$og/ thro3s I!7xception
Similar to the previous constructor, the backlog parameter specifies how many incoming clients to
store in a wait queue.
3 p"$ic ServerSoc=et,int port< int "ac=$og< Inet%ddress address/ thro3s I!7xception
Similar to the previous constructor, the InetAddress parameter specifies the local IP address to
bind to. The InetAddress is used for servers that may have multiple IP addresses, allowing the
server to specify which of its IP addresses to accept client requests on
4 p"$ic ServerSoc=et,/ thro3s I!7xception
Creates an unbound server socket. When using this constructor, use the bind() method when you
are ready to bind the server socket
MAT SOFT
JAVA REFERENCE GUIDE
217
If the ServerSocket constructor does not throw an exception, it means that your application has
successfully bound to the specified port and is ready for client requests.
Here are some of the common methods of the ServerSocket class:
SN Methods 3ith )escription
1 p"$ic int get0oca$Port,/
Returns the port that the server socket is listening on. This method is useful if you passed in 0 as
the port number in a constructor and let the server find a port for you.
2 p"$ic Soc=et accept,/ thro3s I!7xception
Waits for an incoming client. This method blocks until either a client connects to the server on the
specified port or the socket times out, assuming that the time-out value has been set using the
setSoTimeout() method. Otherwise, this method blocks indefinitely
3 p"$ic void setSoTimeot,int timeot/
Sets the time-out value for how long the server socket waits for a client during the accept().
4 p"$ic void "ind,Soc=et%ddress host< int "ac=$og/
Binds the socket to the specified server and port in the SocketAddress object. Use this method if
you instantiated the ServerSocket using the no-argument constructor.
When the ServerSocket invokes accept(), the method does not return until a client connects. After a
client does connect, the ServerSocket creates a new Socket on an unspecified port and returns a
reference to this new Socket. A TCP connection now exists between the client and server, and
communication can begin.
Socket Class Methods:
The #ava1net1Soc=et class represents the socket that both the client and server use to communicate
with each other. The client obtains a Socket object by instantiating one, whereas the server obtains a
Socket object from the return value of the accept() method.
The Socket class has five constructors that a client uses to connect to a server:
SN Methods 3ith )escription
1 p"$ic Soc=et,String host< int port/ thro3s Bn=no3n(ost7xception< I!7xception1
This method attempts to connect to the specified server at the specified port. If this constructor
does not throw an exception, the connection is successful and the client is connected to the
server.
2 p"$ic Soc=et,Inet%ddress host< int port/ thro3s I!7xception
This method is identical to the previous constructor, except that the host is denoted by an
MAT SOFT
JAVA REFERENCE GUIDE
218
InetAddress object.
3 p"$ic Soc=et,String host< int port< Inet%ddress $oca$%ddress< int $oca$Port/ thro3s
I!7xception1
Connects to the specified host and port, creating a socket on the local host at the specified
address and port.
4 p"$ic Soc=et,Inet%ddress host< int port< Inet%ddress $oca$%ddress< int $oca$Port/
thro3s I!7xception1
This method is identical to the previous constructor, except that the host is denoted by an
InetAddress object instead of a String
5 p"$ic Soc=et,/
Creates an unconnected socket. Use the connect() method to connect this socket to a server.
When the Socket constructor returns, it does not simply instantiate a Socket object but it actually
attempts to connect to the specified server and port.
Some methods of interest in the Socket class are listed here. Notice that both the client and server
have a Socket object, so these methods can be invoked by both the client and server.
SN Methods 3ith )escription
1 p"$ic void connect,Soc=et%ddress host< int timeot/ thro3s I!7xception
This method connects the socket to the specified host. This method is needed only when you
instantiated the Socket using the no-argument constructor.
2 p"$ic Inet%ddress getInet%ddress,/
This method returns the address of the other computer that this socket is connected to.
3 p"$ic int getPort,/
Returns the port the socket is bound to on the remote machine.
4 p"$ic int get0oca$Port,/
Returns the port the socket is bound to on the local machine.
5 p"$ic Soc=et%ddress get'emoteSoc=et%ddress,/
Returns the address of the remote socket.
6 p"$ic InptStream getInptStream,/ thro3s I!7xception
Returns the input stream of the socket. The input stream is connected to the output stream of
the remote socket.
7 p"$ic !tptStream get!tptStream,/ thro3s I!7xception
Returns the output stream of the socket. The output stream is connected to the input stream of
MAT SOFT
JAVA REFERENCE GUIDE
219
the remote socket
8 p"$ic void c$ose,/ thro3s I!7xception
Closes the socket, which makes this Socket object no longer capable of connecting again to any
server
InetAddress Class Methods:
This class represents an Internet Protocol (IP) address. Here are following usefull methods which you
would need while doing socket programming:
SN Methods 3ith )escription
1 static Inet%ddress getBy%ddress,"yte-. addr/
Returns an InetAddress object given the raw IP address .
2 static Inet%ddress getBy%ddress,String host< "yte-. addr/
Create an InetAddress based on the provided host name and IP address.
3 static Inet%ddress getByName,String host/
Determines the IP address of a host, given the host's name.
4 String get(ost%ddress,/
Returns the IP address string in textual presentation.
5 String get(ostName,/
Gets the host name for this IP address.
6 static Inet%ddress Inet%ddress get0oca$(ost,/
Returns the local host.
7 String toString,/
Converts this IP address to a String.
Socket Client Example:
The following GreetingClient is a client program that connects to a server by using a socket and sends
a greeting, and then waits for a response.
// Fil! =am! 8r!!ting,li!nt.java
import java.n!t.**
import java.io.**
MAT SOFT
JAVA REFERENCE GUIDE
220
public class 8r!!ting,li!nt
{
public static voi# main$%tring &' args(
{
%tring s!rv!r=am! 9 args&E'*
int port 9 6nt!g!r.pars!6nt$args&C'(*
try
{
%yst!m.out.println$),onn!cting to ) > s!rv!r=am!
> ) on port ) > port(*
%oc<!t cli!nt 9 n!w %oc<!t$s!rv!r=am!2 port(*
%yst!m.out.println$)Just conn!ct!# to )
> cli!nt.g!t7!mot!%oc<!t0##r!ss$((*
?utput%tr!am outTo%!rv!r 9 cli!nt.g!t?utput%tr!am$(*
4ata?utput%tr!am out 9
n!w 4ata?utput%tr!am$outTo%!rv!r(*
out.writ!5TF$)!llo from )
> cli!nt.g!t1ocal%oc<!t0##r!ss$((*
6nput%tr!am inFrom%!rv!r 9 cli!nt.g!t6nput%tr!am$(*
4ata6nput%tr!am in 9
n!w 4ata6nput%tr!am$inFrom%!rv!r(*
%yst!m.out.println$)%!rv!r says ) > in.r!a#5TF$((*
cli!nt.clos!$(*
+catch$6?3:c!ption !(
{
!.print%tac<Trac!$(*
+
+
+
Socket Server Example:
The following GreetingServer program is an example of a server application that uses the Socket class
to listen for clients on a port number specified by a command-line argument:
// Fil! =am! 8r!!ting%!rv!r.java
import java.n!t.**
import java.io.**
public class 8r!!ting%!rv!r !:t!n#s Thr!a#
{
privat! %!rv!r%oc<!t s!rv!r%oc<!t*

public 8r!!ting%!rv!r$int port( throws 6?3:c!ption
{
s!rv!r%oc<!t 9 n!w %!rv!r%oc<!t$port(*
s!rv!r%oc<!t.s!t%oTim!out$CEEEE(*
MAT SOFT
JAVA REFERENCE GUIDE
221
+
public voi# run$(
{
whil!$tru!(
{
try
{
%yst!m.out.println$)"aiting for cli!nt on port ) >
s!rv!r%oc<!t.g!t1ocalPort$( > )...)(*
%oc<!t s!rv!r 9 s!rv!r%oc<!t.acc!pt$(*
%yst!m.out.println$)Just conn!ct!# to )
> s!rv!r.g!t7!mot!%oc<!t0##r!ss$((*
4ata6nput%tr!am in 9
n!w 4ata6nput%tr!am$s!rv!r.g!t6nput%tr!am$((*
%yst!m.out.println$in.r!a#5TF$((*
4ata?utput%tr!am out 9
n!w 4ata?utput%tr!am$s!rv!r.g!t?utput%tr!am$((*
out.writ!5TF$)Than< you for conn!cting to )
> s!rv!r.g!t1ocal%oc<!t0##r!ss$( > )On8oo#by!G)(*
s!rv!r.clos!$(*
+catch$%oc<!tTim!out3:c!ption s(
{
%yst!m.out.println$)%oc<!t tim!# outG)(*
br!a<*
+catch$6?3:c!ption !(
{
!.print%tac<Trac!$(*
br!a<*
+
+
+
public static voi# main$%tring &' args(
{
int port 9 6nt!g!r.pars!6nt$args&E'(*
try
{
Thr!a# t 9 n!w 8r!!ting%!rv!r$port(*
t.start$(*
+catch$6?3:c!ption !(
{
!.print%tac<Trac!$(*
+
+
+
Compile client and server and then start server as follows:
U java 8r!!ting%!rv!r MEMM
"aiting for cli!nt on port MEMM...
Check client program as follows:
MAT SOFT
JAVA REFERENCE GUIDE
222
U java 8r!!ting,li!nt localhost MEMM
,onn!cting to localhost on port MEMM
Just conn!ct!# to localhost/C@I.E.E.C-MEMM
%!rv!r says Than< you for conn!cting to /C@I.E.E.C-MEMM
8oo#by!G
)%A 58: An Oerie! of "MI Applications
23I applications often comprise two separate programs, a server and a client. "
typical server program creates some remote ob%ects, makes references to these ob%ects
accessible, and waits for clients to invoke methods on these ob%ects. " typical client
program obtains a remote reference to one or more remote ob%ects on a server and
then invokes methods on them. 23I provides the mechanism by which the server and
the client communicate and pass information back and forth. &uch an application is
sometimes referred to as a distributed object application.
4istributed ob%ect applications need to do the following:
,o!at% r%mot% o4%!ts- A//*#,%"#(0$ ,%0 .$1 <%-#(.$
61,2%0#$6$ "( (5"%#0 -1)1-10,1$ "( -16("1 (591,"$4 F(-
1A%6/*1> %0 %//*#,%"#(0 ,%0 -1+#$"1- #"$ -16("1 (591,"$ &#"2
MAT SOFT
JAVA REFERENCE GUIDE
223
RMIB$ $#6/*1 0%6#0+ )%,#*#"'> "21 RMI -1+#$"-'4 A*"1-0%"#<1*'> %0
%//*#,%"#(0 ,%0 /%$$ %03 -1".-0 -16("1 (591," -1)1-10,1$ %$
/%-" () ("21- -16("1 #0<(,%"#(0$4
Comm$"i!at% 5ith r%mot% o4%!ts- D1"%#*$ ()
,(66.0#,%"#(0 51"&110 -16("1 (591,"$ %-1 2%03*13 5' RMI4 T(
"21 /-(+-%661-> -16("1 ,(66.0#,%"#(0 *((:$ $#6#*%- "(
-1+.*%- J%<% 61"2(3 #0<(,%"#(0$4
,oa1 !lass 1%6"itio"s 0or o4%!ts that ar% pass%1
aro$"1- B1,%.$1 RMI 10%5*1$ (591,"$ "( 51 /%$$13 5%,: %03
)(-"2> #" /-(<#31$ 61,2%0#$6$ )(- *(%3#0+ %0 (591,"B$ ,*%$$
31C0#"#(0$ %$ &1** %$ )(- "-%0$6#""#0+ %0 (591,"B$ 3%"%4
The following illustration depicts an 23I distributed application that uses the 23I
registry to obtain a reference to a remote ob%ect. The server calls the registry to
associate +or bind, a name with a remote ob%ect. The client looks up the remote ob%ect
by its name in the server$s registry and then invokes a method on it. The illustration
also shows that the 23I system uses an e(isting web server to load class definitions,
from server to client and from client to server, for ob%ects when needed.
Adanta#es of $ynamic Code Loadin#
)ne of the central and uni5ue features of 23I is its ability to download the definition
of an ob%ect$s class if the class is not defined in the receiver$s *ava virtual machine. "ll
of the types and behavior of an ob%ect, previously available only in a single *ava
virtual machine, can be transmitted to another, possibly remote, *ava virtual machine.
23I passes ob%ects by their actual classes, so the behavior of the ob%ects is not
changed when they are sent to another *ava virtual machine. This capability enables
new types and behaviors to be introduced into a remote *ava virtual machine, thus
dynamically e(tending the behavior of an application. The compute engine e(ample in
this trail uses this capability to introduce new behavior to a distributed program.
MAT SOFT
JAVA REFERENCE GUIDE
224
"emote Interfaces% O&'ects% and Methods
6ike any other *ava application, a distributed application built by using *ava 23I is
made up of interfaces and classes. The interfaces declare methods. The classes
implement the methods declared in the interfaces and, perhaps, declare additional
methods as well. In a distributed application, some implementations might reside in
some *ava virtual machines but not others. )b%ects with methods that can be invoked
across *ava virtual machines are called remote objects.
"n ob%ect becomes remote by implementing a remote interface, which has the
following characteristics:
A -16("1 #0"1-)%,1 1A"103$ "21 #0"1-)%,1 java.rmi.7!mot!4
E%,2 61"2(3 () "21 #0"1-)%,1 31,*%-1$ java.rmi.7!mot!3:c!ption #0
#"$ throws ,*%.$1> #0 %33#"#(0 "( %0' %//*#,%"#(0;$/1,#C,
1A,1/"#(0$4
23I treats a remote ob%ect differently from a non!remote ob%ect when the ob%ect is
passed from one *ava virtual machine to another *ava virtual machine. 2ather than
making a copy of the implementation ob%ect in the receiving *ava virtual machine,
23I passes a remote stub for a remote ob%ect. The stub acts as the local
representative, or pro(y, for the remote ob%ect and basically is, to the client, the
remote reference. The client invokes a method on the local stub, which is responsible
for carrying out the method invocation on the remote ob%ect.
" stub for a remote ob%ect implements the same set of remote interfaces that the
remote ob%ect implements. This property enables a stub to be cast to any of the
interfaces that the remote ob%ect implements. 7owever, only those methods defined in
a remote interface are available to be called from the receiving *ava virtual machine.
Creatin# $istri&uted Applications &y Usin# "MI
8sing 23I to develop a distributed application involves these general steps:
14 D1$#+0#0+ %03 #6/*1610"#0+ "21 ,(6/(010"$ () '(.-
3#$"-#5."13 %//*#,%"#(04
24 C(6/#*#0+ $(.-,1$4
34 M%:#0+ ,*%$$1$ 01"&(-: %,,1$$#5*14
44 S"%-"#0+ "21 %//*#,%"#(04
MAT SOFT
JAVA REFERENCE GUIDE
225
$esi#nin# and Implementin# the Application Components
'irst, determine your application architecture, including which components are local
ob%ects and which components are remotely accessible. This step includes:
D%6"i"7 th% r%mot% i"t%r0a!%s- A -16("1 #0"1-)%,1
$/1,#C1$ "21 61"2(3$ "2%" ,%0 51 #0<(:13 -16("1*' 5' % ,*#10"4
C*#10"$ /-(+-%6 "( -16("1 #0"1-)%,1$> 0(" "( "21
#6/*1610"%"#(0 ,*%$$1$ () "2($1 #0"1-)%,1$4 T21 31$#+0 () $.,2
#0"1-)%,1$ #0,*.31$ "21 31"1-6#0%"#(0 () "21 "'/1$ () (591,"$
"2%" &#** 51 .$13 %$ "21 /%-%61"1-$ %03 -1".-0 <%*.1$ )(- "21$1
61"2(3$4 I) %0' () "21$1 #0"1-)%,1$ (- ,*%$$1$ 3( 0(" '1" 1A#$">
'(. 0113 "( 31C01 "216 %$ &1**4
Impl%m%"ti"7 th% r%mot% o4%!ts- R16("1 (591,"$ 6.$"
#6/*1610" (01 (- 6(-1 -16("1 #0"1-)%,1$4 T21 -16("1 (591,"
,*%$$ 6%' #0,*.31 #6/*1610"%"#(0$ () ("21- #0"1-)%,1$ %03
61"2(3$ "2%" %-1 %<%#*%5*1 (0*' *(,%**'4 I) %0' *(,%* ,*%$$1$ %-1
"( 51 .$13 )(- /%-%61"1-$ (- -1".-0 <%*.1$ () %0' () "21$1
61"2(3$> "21' 6.$" 51 #6/*1610"13 %$ &1**4
Impl%m%"ti"7 th% !li%"ts- C*#10"$ "2%" .$1 -16("1 (591,"$
,%0 51 #6/*1610"13 %" %0' "#61 %)"1- "21 -16("1 #0"1-)%,1$
%-1 31C013> #0,*.3#0+ %)"1- "21 -16("1 (591,"$ 2%<1 5110
31/*('134
Compilin# Sources
"s with any *ava program, you use the javac compiler to compile the source files. The
source files contain the declarations of the remote interfaces, their implementations,
any other server classes, and the client classes.
Not%: W#"2 <1-$#(0$ /-#(- "( J%<% P*%")(-6> S"%03%-3 E3#"#(0 540> %0
%33#"#(0%* $"1/ &%$ -1D.#-13 "( 5.#*3 $".5 ,*%$$1$> 5' .$#0+
"21 rmic ,(6/#*1-4 @(&1<1-> "2#$ $"1/ #$ 0( *(0+1- 01,1$$%-'4
MAT SOFT
JAVA REFERENCE GUIDE
226
Ma(in# Classes Net!or( Accessi&le
In this step, you make certain class definitions network accessible, such as the
definitions for the remote interfaces and their associated types, and the definitions for
classes that need to be downloaded to the clients or servers. lasses definitions are
typically made network accessible through a web server.
Startin# the Application
&tarting the application includes running the 23I remote ob%ect registry, the server,
and the client.
The rest of this section walks through the steps used to create a compute engine.
)uildin# a *eneric Compute En#ine
This trail focuses on a simple, yet powerful, distributed application called a compute
engine. The compute engine is a remote ob%ect on the server that takes tasks from
clients, runs the tasks, and returns any results. The tasks are run on the machine where
the server is running. This type of distributed application can enable a number of
client machines to make use of a particularly powerful machine or a machine that has
speciali9ed hardware.
The novel aspect of the compute engine is that the tasks it runs do not need to be
defined when the compute engine is written or started. New kinds of tasks can be
created at any time and then given to the compute engine to be run. The only
re5uirement of a task is that its class implement a particular interface. The code
needed to accomplish the task can be downloaded by the 23I system to the compute
engine. Then, the compute engine runs the task, using the resources on the machine on
which the compute engine is running.
The ability to perform arbitrary tasks is enabled by the dynamic nature of the *ava
platform, which is e(tended to the network by 23I. 23I dynamically loads the task
code into the compute engine$s *ava virtual machine and runs the task without prior
knowledge of the class that implements the task. &uch an application, which has the
ability to download code dynamically, is often called a behavior-based application.
&uch applications usually re5uire full agent!enabled infrastructures. :ith 23I, such
applications are part of the basic mechanisms for distributed computing on the *ava
platform.
$esi#nin# a "emote Interface
MAT SOFT
JAVA REFERENCE GUIDE
227
"t the core of the compute engine is a protocol that enables tasks to be submitted to
the compute engine, the compute engine to run those tasks, and the results of those
tasks to be returned to the client. This protocol is e(pressed in the interfaces that are
supported by the compute engine. The remote communication for this protocol is
illustrated in the following figure.
;ach interface contains a single method. The compute engine$s remote
interface, ,omput!, enables tasks to be submitted to the engine. The client
interface, Tas<2 defines how the compute engine e(ecutes a submitted task.
The comput!.,omput! interface defines the remotely accessible part, the compute
engine itself. 7ere is the source code for the ,omput! interface:
pac<ag! comput!*
import java.rmi.7!mot!*
import java.rmi.7!mot!3:c!ption*
public int!rfac! ,omput! !:t!n#s 7!mot! {
NT. T !:!cut!Tas<$Tas<NT. t( throws 7!mot!3:c!ption*
+
#y e(tending the interface java.rmi.7!mot!, the ,omput! interface identifies itself as
an interface whose methods can be invoked from another *ava virtual machine. "ny
ob%ect that implements this interface can be a remote ob%ect.
"s a member of a remote interface, the !:!cut!Tas< method is a remote method.
Therefore, this method must be defined as being capable of throwing
ajava.rmi.7!mot!3:c!ption. This e(ception is thrown by the 23I system from a
remote method invocation to indicate that either a communication failure or a protocol
error has occurred. " 7!mot!3:c!ption is a checked e(ception, so any code invoking a
remote method needs to handle this e(ception by either catching it or declaring it in
itsthrows clause.
The second interface needed for the compute engine is the Tas< interface, which is the
type of the parameter to the !:!cut!Tas< method in the ,omput! interface.
Thecomput!.Tas< interface defines the interface between the compute engine and the
work that it needs to do, providing the way to start the work. 7ere is the source code
for theTas< interface:
MAT SOFT
JAVA REFERENCE GUIDE
228
pac<ag! comput!*
public int!rfac! Tas<NT. {
T !:!cut!$(*
+
The Tas< interface defines a single method, !:!cut!, which has no parameters and
throws no e(ceptions. #ecause the interface does not e(tend 7!mot!, the method in
this interface doesn$t need to list java.rmi.7!mot!3:c!ption in its throws clause.
The Tas< interface has a type parameter, T, which represents the result type of the
task$s computation. This interface$s !:!cut! method returns the result of the
computation and thus its return type is T.
The ,omput! interface$s !:!cut!Tas< method, in turn, returns the result of the
e(ecution of the Tas< instance passed to it. Thus, the !:!cut!Tas< method has its own
type parameter, T, that associates its own return type with the result type of the
passed Tas< instance.
23I uses the *ava ob%ect seriali9ation mechanism to transport ob%ects by value
between *ava virtual machines. 'or an ob%ect to be considered seriali9able, its class
must implement the java.io.%!riali/abl! marker interface. Therefore, classes that
implement the Tas< interface must also implement %!riali/abl!, as must the classes
of ob%ects used for task results.
4ifferent kinds of tasks can be run by a ,omput! ob%ect as long as they are
implementations of the Tas< type. The classes that implement this interface can
contain any data needed for the computation of the task and any other methods needed
for the computation.
7ere is how 23I makes this simple compute engine possible. #ecause 23I can
assume that the Tas< ob%ects are written in the *ava programming language,
implementations of the Tas< ob%ect that were previously unknown to the compute
engine are downloaded by 23I into the compute engine$s *ava virtual machine as
needed. This capability enables clients of the compute engine to define new kinds of
tasks to be run on the server machine without needing the code to be e(plicitly
installed on that machine.
The compute engine, implemented by the ,omput!3ngin! class, implements
the ,omput! interface, enabling different tasks to be submitted to it by calls to
its !:!cut!Tas<method. These tasks are run using the task$s implementation of
the !:!cut! method and the results, are returned to the remote client.
MAT SOFT
JAVA REFERENCE GUIDE
229
Implementin# a "emote Interface
This section discusses the task of implementing a class for the compute engine. In
general, a class that implements a remote interface should at least do the following:
D1,*%-1 "21 -16("1 #0"1-)%,1$ 51#0+ #6/*1610"13
D1C01 "21 ,(0$"-.,"(- )(- 1%,2 -16("1 (591,"
P-(<#31 %0 #6/*1610"%"#(0 )(- 1%,2 -16("1 61"2(3 #0 "21
-16("1 #0"1-)%,1$
"n 23I server program needs to create the initial remote ob%ects and export them to
the 23I runtime, which makes them available to receive incoming remote
invocations. This setup procedure can be either encapsulated in a method of the
remote ob%ect implementation class itself or included in another class entirely. The
setup procedure should do the following:
C-1%"1 %03 #0$"%** % $1,.-#"' 6%0%+1-
C-1%"1 %03 1A/(-" (01 (- 6(-1 -16("1 (591,"$
R1+#$"1- %" *1%$" (01 -16("1 (591," &#"2 "21 RMI -1+#$"-' 7(-
&#"2 %0("21- 0%6#0+ $1-<#,1> $.,2 %$ % $1-<#,1 %,,1$$#5*1
"2-(.+2 "21 J%<% N%6#0+ %03 D#-1,"(-' I0"1-)%,18 )(-
5(("$"-%//#0+ /.-/($1$
The complete implementation of the compute engine follows.
The !ngin!.,omput!3ngin! class implements the remote interface ,omput! and also
includes the main method for setting up the compute engine. 7ere is the source code
for the ,omput!3ngin! class:
pac<ag! !ngin!*
import java.rmi.7!mot!3:c!ption*
import java.rmi.r!gistry.1ocat!7!gistry*
import java.rmi.r!gistry.7!gistry*
import java.rmi.s!rv!r.5nicast7!mot!?bj!ct*
import comput!.,omput!*
import comput!.Tas<*
public class ,omput!3ngin! impl!m!nts ,omput! {
public ,omput!3ngin!$( {
sup!r$(*
+
public NT. T !:!cut!Tas<$Tas<NT. t( {
MAT SOFT
JAVA REFERENCE GUIDE
230
r!turn t.!:!cut!$(*
+
public static voi# main$%tring&' args( {
if $%yst!m.g!t%!curityManag!r$( 99 null( {
%yst!m.s!t%!curityManag!r$n!w %!curityManag!r$((*
+
try {
%tring nam! 9 ),omput!)*
,omput! !ngin! 9 n!w ,omput!3ngin!$(*
,omput! stub 9
$,omput!( 5nicast7!mot!?bj!ct.!:port?bj!ct$!ngin!2 E(*
7!gistry r!gistry 9 1ocat!7!gistry.g!t7!gistry$(*
r!gistry.r!bin#$nam!2 stub(*
%yst!m.out.println$),omput!3ngin! boun#)(*
+ catch $3:c!ption !( {
%yst!m.!rr.println$),omput!3ngin! !:c!ption-)(*
!.print%tac<Trac!$(*
+
+
+
The following sections discuss each component of the compute engine
implementation.
$eclarin# the "emote Interfaces )ein# Implemented
The implementation class for the compute engine is declared as follows:
public class ,omput!3ngin! impl!m!nts ,omput!
This declaration states that the class implements the ,omput! remote interface and
therefore can be used for a remote ob%ect.
The ,omput!3ngin! class defines a remote ob%ect implementation class that
implements a single remote interface and no other interfaces. The ,omput!3ngin! class
also contains two e(ecutable program elements that can only be invoked locally. The
first of these elements is a constructor for ,omput!3ngin! instances. The second of
these elements is a main method that is used to create a ,omput!3ngin! instance and
make it available to clients.
$efinin# the Constructor for the "emote O&'ect
The ,omput!3ngin! class has a single constructor that takes no arguments. The code
for the constructor is as follows:
public ,omput!3ngin!$( {
MAT SOFT
JAVA REFERENCE GUIDE
231
sup!r$(*
+
This constructor %ust invokes the superclass constructor, which is the no!argument
constructor of the ?bj!ct class. "lthough the superclass constructor gets invoked even
if omitted from the ,omput!3ngin! constructor, it is included for clarity.
+roidin# Implementations for Each "emote Method
The class for a remote ob%ect provides implementations for each remote method
specified in the remote interfaces. The ,omput! interface contains a single remote
method,!:!cut!Tas<, which is implemented as follows:
public NT. T !:!cut!Tas<$Tas<NT. t( {
r!turn t.!:!cut!$(*
+
This method implements the protocol between the ,omput!3ngin! remote ob%ect and
its clients. ;ach client provides the ,omput!3ngin! with a Tas< ob%ect that has a
particular implementation of the Tas< interface$s !:!cut! method.
The ,omput!3ngin! e(ecutes each client$s task and returns the result of the
task$s !:!cut! method directly to the client.
+assin# O&'ects in "MI
"rguments to or return values from remote methods can be of almost any type,
including local ob%ects, remote ob%ects, and primitive data types. 3ore precisely, any
entity of any type can be passed to or from a remote method as long as the entity is an
instance of a type that is a primitive data type, a remote ob%ect, or
a serializable ob%ect, which means that it implements the
interface java.io.%!riali/abl!.
&ome ob%ect types do not meet any of these criteria and thus cannot be passed to or
returned from a remote method. 3ost of these ob%ects, such as threads or file
descriptors, encapsulate information that makes sense only within a single address
space. 3any of the core classes, including the classes in the
packages java.lang and java.util, implement the %!riali/abl! interface.
The rules governing how arguments and return values are passed are as follows:
R16("1 (591,"$ %-1 1$$10"#%**' /%$$13 5' -1)1-10,14 A remote
object reference #$ % $".5> &2#,2 #$ % ,*#10";$#31 /-(A' "2%"
MAT SOFT
JAVA REFERENCE GUIDE
232
#6/*1610"$ "21 ,(6/*1"1 $1" () -16("1 #0"1-)%,1$ "2%" "21
-16("1 (591," #6/*1610"$4
L(,%* (591,"$ %-1 /%$$13 5' ,(/'> .$#0+ (591," $1-#%*#E%"#(04 B'
31)%.*"> %** C1*3$ %-1 ,(/#13 1A,1/" C1*3$ "2%" %-1
6%-:13 static (- transi!nt4 D1)%.*" $1-#%*#E%"#(0 512%<#(- ,%0 51
(<1--#3310 (0 % ,*%$$;5';,*%$$ 5%$#$4
<assing a remote ob%ect by reference means that any changes made to the state of the
ob%ect by remote method invocations are reflected in the original remote ob%ect. :hen
a remote ob%ect is passed, only those interfaces that are remote interfaces are available
to the receiver. "ny methods defined in the implementation class or defined in non!
remote interfaces implemented by the class are not available to that receiver.
'or e(ample, if you were to pass a reference to an instance of the ,omput!3ngin! class,
the receiver would have access only to the compute engine$s !:!cut!Tas< method.
That receiver would not see the ,omput!3ngin! constructor, its main method, or its
implementation of any methods of java.lang.?bj!ct.
In the parameters and return values of remote method invocations, ob%ects that are not
remote ob%ects are passed by value. Thus, a copy of the ob%ect is created in the
receiving *ava virtual machine. "ny changes to the ob%ect$s state by the receiver are
reflected only in the receiver$s copy, not in the sender$s original instance. "ny changes
to the ob%ect$s state by the sender are reflected only in the sender$s original instance,
not in the receiver$s copy.
Implementin# the Serer,s main Method
The most comple( method of the ,omput!3ngin! implementation is the main method.
The main method is used to start the ,omput!3ngin! and therefore needs to do the
necessary initiali9ation and housekeeping to prepare the server to accept calls from
clients. This method is not a remote method, which means that it cannot be invoked
from a different *ava virtual machine. #ecause the main method is declared static, the
method is not associated with an ob%ect at all but rather with the class ,omput!3ngin!.
Creatin# and Installin# a Security Mana#er
The main method$s first task is to create and install a security manager, which protects
access to system resources from untrusted downloaded code running within the *ava
virtual machine. " security manager determines whether downloaded code has access
to the local file system or can perform any other privileged operations.
MAT SOFT
JAVA REFERENCE GUIDE
233
If an 23I program does not install a security manager, 23I will not download classes
+other than from the local class path, for ob%ects received as arguments or return
values of remote method invocations. This restriction ensures that the operations
performed by downloaded code are sub%ect to a security policy.
7ere$s the code that creates and installs a security manager:
if $%yst!m.g!t%!curityManag!r$( 99 null( {
%yst!m.s!t%!curityManag!r$n!w %!curityManag!r$((*
+
Ma(in# the "emote O&'ect Aaila&le to Clients
Ne(t, the main method creates an instance of ,omput!3ngin! and e(ports it to the 23I
runtime with the following statements:
,omput! !ngin! 9 n!w ,omput!3ngin!$(*
,omput! stub 9
$,omput!( 5nicast7!mot!?bj!ct.!:port?bj!ct$!ngin!2 E(*
The static 5nicast7!mot!?bj!ct.!:port?bj!ct method e(ports the supplied remote
ob%ect so that it can receive invocations of its remote methods from remote clients.
The second argument, an int, specifies which T< port to use to listen for incoming
remote invocation re5uests for the ob%ect. It is common to use the value 9ero, which
specifies the use of an anonymous port. The actual port will then be chosen at runtime
by 23I or the underlying operating system. 7owever, a non!9ero value can also be
used to specify a specific port to use for listening. )nce the !:port?bj!ct invocation
has returned successfully, the ,omput!3ngin! remote ob%ect is ready to process
incoming remote invocations.
The !:port?bj!ct method returns a stub for the e(ported remote ob%ect. Note that the
type of the variable stub must be ,omput!, not ,omput!3ngin!, because the stub for a
remote ob%ect only implements the remote interfaces that the e(ported remote ob%ect
implements.
The !:port?bj!ct method declares that it can throw a 7!mot!3:c!ption, which is a
checked e(ception type. The main method handles this e(ception with
its try=catchblock. If the e(ception were not handled in this
way, 7!mot!3:c!ption would have to be declared in the throws clause of
the main method. "n attempt to e(port a remote ob%ect can throw a 7!mot!3:c!ption if
the necessary communication resources are not available, such as if the re5uested port
is bound for some other purpose.
MAT SOFT
JAVA REFERENCE GUIDE
234
#efore a client can invoke a method on a remote ob%ect, it must first obtain a reference
to the remote ob%ect. )btaining a reference can be done in the same way that any other
ob%ect reference is obtained in a program, such as by getting the reference as part of
the return value of a method or as part of a data structure that contains such a
reference.
The system provides a particular type of remote ob%ect, the 23I registry, for finding
references to other remote ob%ects. The 23I registry is a simple remote ob%ect naming
service that enables clients to obtain a reference to a remote ob%ect by name. The
registry is typically only used to locate the first remote ob%ect that an 23I client needs
to use. That first remote ob%ect might then provide support for finding other ob%ects.
The java.rmi.r!gistry.7!gistry remote interface is the "<I for binding +or
registering, and looking up remote ob%ects in the registry.
Thejava.rmi.r!gistry.1ocat!7!gistry class provides static methods for synthesi9ing
a remote reference to a registry at a particular network address +host and port,. These
methods create the remote reference ob%ect containing the specified network address
without performing any remote communication. 1ocat!7!gistry also provides static
methods for creating a new registry in the current *ava virtual machine, although this
e(ample does not use those methods. )nce a remote ob%ect is registered with an 23I
registry on the local host, clients on any host can look up the remote ob%ect by name,
obtain its reference, and then invoke remote methods on the ob%ect. The registry can
be shared by all servers running on a host, or an individual server process can create
and use its own registry.
The ,omput!3ngin! class creates a name for the ob%ect with the following statement:
%tring nam! 9 ),omput!)*
The code then adds the name to the 23I registry running on the server. This step is
done later with the following statements:
7!gistry r!gistry 9 1ocat!7!gistry.g!t7!gistry$(*
r!gistry.r!bin#$nam!2 stub(*
This r!bin# invocation makes a remote call to the 23I registry on the local host. 6ike
any remote call, this call can result in a 7!mot!3:c!ption being thrown, which is
handled by the catch block at the end of the main method.
Note the following about the 7!gistry.r!bin# invocation:
MAT SOFT
JAVA REFERENCE GUIDE
235
T21 0(;%-+.610" (<1-*(%3
() 1ocat!7!gistry.g!t7!gistry $'0"21$#E1$ % -1)1-10,1 "( % -1+#$"-'
(0 "21 *(,%* 2($" %03 (0 "21 31)%.*" -1+#$"-' /(-"> 10994 !(.
6.$" .$1 %0 (<1-*(%3 "2%" 2%$ %0 int /%-%61"1- #) "21 -1+#$"-'
#$ ,-1%"13 (0 % /(-" ("21- "2%0 10994
W210 % -16("1 #0<(,%"#(0 (0 "21 -1+#$"-' #$ 6%31> % $".5 )(-
"21 -16("1 (591," #$ /%$$13 #0$"1%3 () % ,(/' () "21 -16("1
(591," #"$1*)4 R16("1 #6/*1610"%"#(0 (591,"$> $.,2 %$ #0$"%0,1$
() ,omput!3ngin!> 01<1- *1%<1 "21 J%<% <#-".%* 6%,2#01 #0 &2#,2
"21' &1-1 ,-1%"134 T2.$> &210 % ,*#10" /1-)(-6$ % *((:./ #0 %
$1-<1-B$ -16("1 (591," -1+#$"-'> % ,(/' () "21 $".5 #$ -1".-0134
R16("1 (591,"$ #0 $.,2 ,%$1$ %-1 "2.$ 1=1,"#<1*' /%$$13 5'
7-16("18 -1)1-10,1 -%"21- "2%0 5' <%*.14
F(- $1,.-#"' -1%$(0$> %0 %//*#,%"#(0 ,%0 (0*' bin#> unbin#>
(- r!bin# -16("1 (591," -1)1-10,1$ &#"2 % -1+#$"-' -.00#0+ (0
"21 $%61 2($"4 T2#$ -1$"-#,"#(0 /-1<10"$ % -16("1 ,*#10" )-(6
-16(<#0+ (- (<1-&-#"#0+ %0' () "21 10"-#1$ #0 % $1-<1-B$
-1+#$"-'4 A loo<up> 2(&1<1-> ,%0 51 -1D.1$"13 )-(6 %0' 2($">
*(,%* (- -16("14
)nce the server has registered with the local 23I registry, it prints a message
indicating that it is ready to start handling calls. Then, the main method completes. It is
not necessary to have a thread wait to keep the server alive. "s long as there is a
reference to the ,omput!3ngin! ob%ect in another *ava virtual machine, local or remote,
the,omput!3ngin! ob%ect will not be shut down or garbage collected. #ecause the
program binds a reference to the ,omput!3ngin! in the registry, it is reachable from a
remote client, the registry itself. The 23I system keeps the ,omput!3ngin!$s process
running. The ,omput!3ngin! is available to accept calls and won$t be reclaimed until its
binding is removed from the registry and no remote clients hold a remote reference to
the ,omput!3ngin! ob%ect.
The final piece of code in the ,omput!3ngin!.main method handles any e(ception that
might arise. The only checked e(ception type that could be thrown in the code
is7!mot!3:c!ption, either by the 5nicast7!mot!?bj!ct.!:port?bj!ct invocation or by
the registry r!bin# invocation. In either case, the program cannot do much more than
e(it after printing an error message. In some distributed applications, recovering from
the failure to make a remote invocation is possible. 'or e(ample, the application could
attempt to retry the operation or choose another server to continue the operation.
MAT SOFT
JAVA REFERENCE GUIDE
236
Creatin# a Client +ro#ram
The compute engine is a relatively simple program: it runs tasks that are handed to it.
The clients for the compute engine are more comple(. " client needs to call the
compute engine, but it also has to define the task to be performed by the compute
engine.
Two separate classes make up the client in our e(ample. The first class, ,omput!Pi,
looks up and invokes a ,omput! ob%ect. The second class, Pi, implements
the Tas<interface and defines the work to be done by the compute engine. The %ob of
the Pi class is to compute the value of to some number of decimal places.
The non!remote Tas< interface is defined as follows:
pac<ag! comput!*
public int!rfac! Tas<NT. {
T !:!cut!$(*
+
The code that invokes a ,omput! ob%ect$s methods must obtain a reference to that
ob%ect, create a Tas< ob%ect, and then re5uest that the task be e(ecuted. The definition
of the task class Pi is shown later. " Pi ob%ect is constructed with a single argument,
the desired precision of the result. The result of the task e(ecution is
ajava.math.Lig4!cimal representing calculated to the specified precision.
7ere is the source code for cli!nt.,omput!Pi, the main client class:
pac<ag! cli!nt*
import java.rmi.r!gistry.1ocat!7!gistry*
import java.rmi.r!gistry.7!gistry*
import java.math.Lig4!cimal*
import comput!.,omput!*
public class ,omput!Pi {
public static voi# main$%tring args&'( {
if $%yst!m.g!t%!curityManag!r$( 99 null( {
%yst!m.s!t%!curityManag!r$n!w %!curityManag!r$((*
+
try {
%tring nam! 9 ),omput!)*
7!gistry r!gistry 9 1ocat!7!gistry.g!t7!gistry$args&E'(*
,omput! comp 9 $,omput!( r!gistry.loo<up$nam!(*
Pi tas< 9 n!w Pi$6nt!g!r.pars!6nt$args&C'((*
Lig4!cimal pi 9 comp.!:!cut!Tas<$tas<(*
%yst!m.out.println$pi(*
+ catch $3:c!ption !( {
MAT SOFT
JAVA REFERENCE GUIDE
237
%yst!m.!rr.println$),omput!Pi !:c!ption-)(*
!.print%tac<Trac!$(*
+
+
+
6ike the ,omput!3ngin! server, the client begins by installing a security manager. This
step is necessary because the process of receiving the server remote ob%ect$s stub
could re5uire downloading class definitions from the server. 'or 23I to download
classes, a security manager must be in force.
"fter installing a security manager, the client constructs a name to use to look up
a ,omput! remote ob%ect, using the same name used by ,omput!3ngin! to bind its
remote ob%ect. "lso, the client uses the 1ocat!7!gistry.g!t7!gistry "<I to synthesi9e
a remote reference to the registry on the server$s host. The value of the first command!
line argument, args&E', is the name of the remote host on which the ,omput! ob%ect
runs. The client then invokes the loo<up method on the registry to look up the remote
ob%ect by name in the server host$s registry. The particular overload
of 1ocat!7!gistry.g!t7!gistry used, which has a single %tring parameter, returns a
reference to a registry at the named host and the default registry port, .->>. 1ou must
use an overload that has an int parameter if the registry is created on a port other than
.->>.
Ne(t, the client creates a new Pi ob%ect, passing to the Pi constructor the value of the
second command!line argument, args&C', parsed as an integer. This argument
indicates the number of decimal places to use in the calculation. 'inally, the client
invokes the !:!cut!Tas< method of the ,omput! remote ob%ect. The ob%ect passed into
the!:!cut!Tas< invocation returns an ob%ect of type Lig4!cimal, which the program
stores in the variable r!sult. 'inally, the program prints the result. The following
figure depicts the flow of messages among the ,omput!Pi client, the rmir!gistry, and
the ,omput!3ngin!.
The Pi class implements the Tas< interface and computes the value of to a specified
number of decimal places. 'or this e(ample, the actual algorithm is unimportant.
:hat is important is that the algorithm is computationally e(pensive, meaning that
you would want to have it e(ecuted on a capable server.
MAT SOFT
JAVA REFERENCE GUIDE
238
7ere is the source code for cli!nt.Pi, the class that implements the Tas< interface:
pac<ag! cli!nt*
import comput!.Tas<*
import java.io.%!riali/abl!*
import java.math.Lig4!cimal*
public class Pi impl!m!nts Tas<NLig4!cimal.2 %!riali/abl! {
privat! static final long s!rialB!rsion564 9 @@I1*
/** constants us!# in pi computation */
privat! static final Lig4!cimal F?57 9
Lig4!cimal.valu!?f$F(*
/** roun#ing mo#! to us! #uring pi computation */
privat! static final int roun#ingMo#! 9
Lig4!cimal.7?5=4T01FT3B3=*
/** #igits of pr!cision aft!r th! #!cimal point */
privat! final int #igits*

/**
* ,onstruct a tas< to calculat! pi to th! sp!cifi!#
* pr!cision.
*/
public Pi$int #igits( {
this.#igits 9 #igits*
+
/**
* ,alculat! pi.
*/
public Lig4!cimal !:!cut!$( {
r!turn comput!Pi$#igits(*
+
/**
* ,omput! th! valu! of pi to th! sp!cifi!# numb!r of
* #igits aft!r th! #!cimal point. Th! valu! is
* comput!# using Machin's formula-
*
* pi/F 9 F*arctan$C/H( ; arctan$C/@DK(
*
* an# a pow!r s!ri!s !:pansion of arctan$:( to
* suffici!nt pr!cision.
*/
public static Lig4!cimal comput!Pi$int #igits( {
int scal! 9 #igits > H*
Lig4!cimal arctanCTH 9 arctan$H2 scal!(*
Lig4!cimal arctanCT@DK 9 arctan$@DK2 scal!(*
Lig4!cimal pi 9 arctanCTH.multiply$F?57(.subtract$
arctanCT@DK(.multiply$F?57(*
r!turn pi.s!t%cal!$#igits2
MAT SOFT
JAVA REFERENCE GUIDE
239
Lig4!cimal.7?5=4T01FT5P(*
+
/**
* ,omput! th! valu!2 in ra#ians2 of th! arctang!nt of
* th! inv!rs! of th! suppli!# int!g!r to th! sp!cifi!#
* numb!r of #igits aft!r th! #!cimal point. Th! valu!
* is comput!# using th! pow!r s!ri!s !:pansion for th!
* arc tang!nt-
*
* arctan$:( 9 : ; $:QD(/D > $:QH(/H ; $:QI(/I >
* $:QK(/K ...
*/
public static Lig4!cimal arctan$int inv!rs!R2
int scal!(
{
Lig4!cimal r!sult2 num!r2 t!rm*
Lig4!cimal invR 9 Lig4!cimal.valu!?f$inv!rs!R(*
Lig4!cimal invR@ 9
Lig4!cimal.valu!?f$inv!rs!R * inv!rs!R(*
num!r 9 Lig4!cimal.?=3.#ivi#!$invR2
scal!2 roun#ingMo#!(*
r!sult 9 num!r*
int i 9 C*
#o {
num!r 9
num!r.#ivi#!$invR@2 scal!2 roun#ingMo#!(*
int #!nom 9 @ * i > C*
t!rm 9
num!r.#ivi#!$Lig4!cimal.valu!?f$#!nom(2
scal!2 roun#ingMo#!(*
if $$i W @( G9 E( {
r!sult 9 r!sult.subtract$t!rm(*
+ !ls! {
r!sult 9 r!sult.a##$t!rm(*
+
i>>*
+ whil! $t!rm.compar!To$Lig4!cimal.V37?( G9 E(*
r!turn r!sult*
+
+
Note that all seriali9able classes, whether they implement the %!riali/abl! interface
directly or indirectly, must declare a privat! static final field
nameds!rialB!rsion564 to guarantee seriali9ation compatibility between versions. If
no previous version of the class has been released, then the value of this field can be
any longvalue, similar to the @@I1 used by Pi, as long as the value is used consistently
in future versions. If a previous version of the class has been released without an
e(plicits!rialB!rsion564 declaration, but seriali9ation compatibility with that version
is important, then the default implicitly computed value for the previous version must
MAT SOFT
JAVA REFERENCE GUIDE
240
be used for the value of the new version$s e(plicit declaration. The s!rialv!r tool can
be run against the previous version to determine the default computed value for it.
The most interesting feature of this e(ample is that the ,omput! implementation ob%ect
never needs the Pi class$s definition until a Pi ob%ect is passed in as an argument to
the!:!cut!Tas< method. "t that point, the code for the class is loaded by 23I into
the ,omput! ob%ect$s *ava virtual machine, the !:!cut! method is invoked, and the
task$s code is e(ecuted. The result, which in the case of the Pi task is
a Lig4!cimal ob%ect, is handed back to the calling client, where it is used to print the
result of the computation.
The fact that the supplied Tas< ob%ect computes the value of Pi is irrelevant to
the ,omput!3ngin! ob%ect. 1ou could also implement a task that, for e(ample,
generates a random prime number by using a probabilistic algorithm. That task would
also be computationally intensive and therefore a good candidate for passing to
the ,omput!3ngin!, but it would re5uire very different code. This code could also be
downloaded when the Tas< ob%ect is passed to a ,omput! ob%ect. In %ust the way that
the algorithm for computing is brought in when needed, the code that generates the
random prime number would be brought in when needed. The ,omput! ob%ect knows
only that each ob%ect it receives implements the !:!cut! method. The ,omput! ob%ect
does not know, and does not need to know, what the implementation does.
Compilin# the Example +ro#rams
In a real!world scenario in which a service such as the compute engine is deployed, a
developer would likely create a *ava "rchive +*"2, file that contains
the ,omput! andTas< interfaces for server classes to implement and client programs to
use. Ne(t, a developer, perhaps the same developer of the interface *"2 file, would
write an implementation of the ,omput! interface and deploy that service on a machine
available to clients. 4evelopers of client programs can use the ,omput! and
the Tas< interfaces, contained in the *"2 file, and independently develop a task and
client program that uses a ,omput! service.
In this section, you learn how to set up the *"2 file, server classes, and client classes.
1ou will see that the client$s Pi class will be downloaded to the server at runtime.
"lso, the ,omput! and Tas< interfaces will be downloaded from the server to the
registry at runtime.
This e(ample separates the interfaces, remote ob%ect implementation, and client code
into three packages:
MAT SOFT
JAVA REFERENCE GUIDE
241
comput! F ,omput! %03 Tas< #0"1-)%,1$
!ngin! F ,omput!3ngin! #6/*1610"%"#(0 ,*%$$
cli!nt F ,omput!Pi ,*#10" ,(31 %03 Pi "%$: #6/*1610"%"#(0
'irst, you need to build the interface *"2 file to provide to server and client
developers.
)uildin# a -A" .ile of Interface Classes
'irst, you need to compile the interface source files in the comput! package and then
build a *"2 file that contains their class files. "ssume that user wal#o has written
these interfaces and placed the source files in the
directory c-Ohom!Owal#oOsrcOcomput! on :indows or the
directory /hom!/wal#o/src/comput! on &olaris )& or 6inu(. ?iven these paths, you
can use the following commands to compile the interfaces and create the *"2 file:
Microsoft Windows:
c# c-Ohom!Owal#oOsrc
javac comput!O,omput!.java comput!OTas<.java
jar cvf comput!.jar comput!O*.class
Solaris OS or Linux:
c# /hom!/wal#o/src
javac comput!/,omput!.java comput!/Tas<.java
jar cvf comput!.jar comput!/*.class
The jar command displays the following output due to the ;v option:
a##!# manif!st
a##ing- comput!/,omput!.class$in 9 DEI( $out9 @EC($#!flat!# DFW(
a##ing- comput!/Tas<.class$in 9 @CI( $out9 CFK($#!flat!# DCW(
Now, you can distribute the comput!.jar file to developers of server and client
applications so that they can make use of the interfaces.
"fter you build either server!side or client!side classes with the javac compiler, if any
of those classes will need to be dynamically downloaded by other *ava virtual
machines, you must ensure that their class files are placed in a network!accessible
location. In this e(ample, for &olaris )& or 6inu( this location
is /hom!/user/publicThtml/class!s because many web servers allow the accessing of
MAT SOFT
JAVA REFERENCE GUIDE
242
a user$s publicThtml directory through an 7TT< 826 constructed
as http-//host/Zuser/. If your web server does not support this convention, you could
use a different location in the web server$s hierarchy, or you could use a file 826
instead. The file 826s take the formfil!-/hom!/user/publicThtml/class!s/ on
&olaris )& or 6inu( and the form fil!-/c-/hom!/user/publicThtml/class!s/ on
:indows. 1ou may also select another type of 826, as appropriate.
The network accessibility of the class files enables the 23I runtime to download code
when needed. 2ather than defining its own protocol for code downloading, 23I uses
826 protocols supported by the *ava platform +for e(ample, 7TT<, to download
code. Note that using a full, heavyweight web server to serve these class files is
unnecessary. 'or e(ample, a simple 7TT< server that provides the functionality
needed to make classes available for downloading in 23I through 7TT< can be
found at .
"lso see 2emote 3ethod Invocation 7ome.
)uildin# the Serer Classes
The !ngin! package contains only one server!side implementation
class, ,omput!3ngin!, the implementation of the remote interface ,omput!.
"ssume that user ann, the developer of the ,omput!3ngin! class, has
placed ,omput!3ngin!.java in the directory c-Ohom!OannOsrcO!ngin! on :indows or
the directory/hom!/ann/src/!ngin! on &olaris )& or 6inu(. &he is deploying the class
files for clients to download in a subdirectory of
her publicThtml directory,c-Ohom!OannOpublicThtmlOclass!s on :indows
or /hom!/ann/publicThtml/class!s on &olaris )& or 6inu(. This location is accessible
through some web servers ashttp-//host-port/Zann/class!s/.
The ,omput!3ngin! class depends on the ,omput! and Tas< interfaces, which are
contained in the comput!.jar *"2 file. Therefore, you need the comput!.jar file in
your class path when you build the server classes. "ssume that the comput!.jar file is
located in the directory c-Ohom!OannOpublicThtmlOclass!s on :indows or the
directory/hom!/ann/publicThtml/class!s on &olaris )& or 6inu(. ?iven these paths,
you can use the following commands to build the server classes:
Microsoft Windows:
c# c-Ohom!OannOsrc
javac ;cp c-Ohom!OannOpublicThtmlOclass!sOcomput!.jar
!ngin!O,omput!3ngin!.java
MAT SOFT
JAVA REFERENCE GUIDE
243
Solaris OS or Linux:
c# /hom!/ann/src
javac ;cp /hom!/ann/publicThtml/class!s/comput!.jar
!ngin!/,omput!3ngin!.java
The stub class for ,omput!3ngin! implements the ,omput! interface, which refers to
the Tas< interface. &o, the class definitions for those two interfaces need to be
network!accessible for the stub to be received by other *ava virtual machines such as
the registry$s *ava virtual machine. The client *ava virtual machine will already have
these interfaces in its class path, so it does not actually need to download their
definitions. The comput!.jar file under the publicThtml directory can serve this
purpose.
Now, the compute engine is ready to deploy. 1ou could do that now, or you could wait
until after you have built the client.
)uildin# the Client Classes
The cli!nt package contains two classes, ,omput!Pi, the main client program, and Pi,
the client$s implementation of the Tas< interface.
"ssume that user jon!s, the developer of the client classes, has
placed ,omput!Pi.java and Pi.java in the directory c-Ohom!Ojon!sOsrcOcli!nt on
:indows or the directory /hom!/jon!s/src/cli!nt on &olaris )& or 6inu(. 7e is
deploying the class files for the compute engine to download in a subdirectory of
his publicThtml directory,c-Ohom!Ojon!sOpublicThtmlOclass!s on :indows
or /hom!/jon!s/publicThtml/class!s on &olaris )& or 6inu(. This location is
accessible through some web servers as http-//host-port/Zjon!s/class!s/.
The client classes depend on the ,omput! and Tas< interfaces, which are contained in
the comput!.jar *"2 file. Therefore, you need the comput!.jar file in your class path
when you build the client classes. "ssume that the comput!.jar file is located in the
directory c-Ohom!Ojon!sOpublicThtmlOclass!s on :indows or the
directory/hom!/jon!s/publicThtml/class!s on &olaris )& or 6inu(. ?iven these
paths, you can use the following commands to build the client classes:
Microsoft Windows:
c# c-Ohom!Ojon!sOsrc
javac ;cp c-Ohom!Ojon!sOpublicThtmlOclass!sOcomput!.jar
cli!ntO,omput!Pi.java cli!ntOPi.java
m<#ir c-Ohom!Ojon!sOpublicThtmlOclass!sOcli!nt
MAT SOFT
JAVA REFERENCE GUIDE
244
cp cli!ntOPi.class
c-Ohom!Ojon!sOpublicThtmlOclass!sOcli!nt
Solaris OS or Linux:
c# /hom!/jon!s/src
javac ;cp /hom!/jon!s/publicThtml/class!s/comput!.jar
cli!nt/,omput!Pi.java cli!nt/Pi.java
m<#ir /hom!/jon!s/publicThtml/class!s/cli!nt
cp cli!nt/Pi.class
/hom!/jon!s/publicThtml/class!s/cli!nt
)nly the Pi class needs to be placed in the
directory publicThtmlOclass!sOcli!nt because only the Pi class needs to be available
for downloading to the compute engine$s *ava virtual machine. Now, you can run the
server and then the client.
"unnin# the Example +ro#rams
A Note A&out Security
The server and client programs run with a security manager installed. :hen you run
either program, you need to specify a security policy file so that the code is granted
the security permissions it needs to run. 7ere is an e(ample policy file to use with the
server program:
grant co#!Las! )fil!-/hom!/ann/src/) {
p!rmission java.s!curity.0llP!rmission*
+*
7ere is an e(ample policy file to use with the client program:
grant co#!Las! )fil!-/hom!/jon!s/src/) {
p!rmission java.s!curity.0llP!rmission*
+*
'or both e(ample policy files, all permissions are granted to the classes in the
program$s local class path, because the local application code is trusted, but no
permissions are granted to code downloaded from other locations. Therefore, the
compute engine server restricts the tasks that it e(ecutes +whose code is not known to
be trusted and might be hostile, from performing any operations that re5uire security
permissions. The e(ample client$s Pi task does not re5uire any permissions to e(ecute.
In this e(ample, the policy file for the server program is named s!rv!r.policy, and
the policy file for the client program is named cli!nt.policy.
MAT SOFT
JAVA REFERENCE GUIDE
245
Startin# the Serer
#efore starting the compute engine, you need to start the 23I registry. The 23I
registry is a simple server!side bootstrap naming facility that enables remote clients to
obtain a reference to an initial remote ob%ect. It can be started with
the rmir!gistry command. #efore you e(ecute rmir!gistry, you must make sure that
the shell or window in which you will run rmir!gistry either has
no ,10%%P0T environment variable set or has a ,10%%P0T environment variable that
does not include the path to any classes that you want downloaded to clients of your
remote ob%ects.
To start the registry on the server, e(ecute the rmir!gistry command. This command
produces no output and is typically run in the background. 'or this e(ample, the
registry is started on the host mycomput!r.
Microsoft Windows +use javaw if start is not available,:
start rmir!gistry
Solaris OS or Linux:
rmir!gistry [
#y default, the registry runs on port .->>. To start the registry on a different port,
specify the port number on the command line. 4o not forget to unset
your ,10%%P0Tenvironment variable.
Microsoft Windows:
start rmir!gistry @EEC
Solaris OS or Linux:
rmir!gistry @EEC [
)nce the registry is started, you can start the server. 1ou need to make sure that both
the comput!.jar file and the remote ob%ect implementation class are in your class path.
:hen you start the compute engine, you need to specify, using
the java.rmi.s!rv!r.co#!bas! property, where the server$s classes are network
accessible. In this e(ample, the server!side classes to be made available for
downloading are the ,omput! and Tas< interfaces, which are available in
the comput!.jar file in the publicThtmlOclass!sdirectory of user ann. The compute
MAT SOFT
JAVA REFERENCE GUIDE
246
engine server is started on the host mycomput!r, the same host on which the registry
was started.
Microsoft Windows:
java ;cp c-Ohom!OannOsrc*c-Ohom!OannOpublicThtmlOclass!sOcomput!.jar

;4java.rmi.s!rv!r.co#!bas!9fil!-/c-/hom!/ann/publicThtml/class!s/comput!.jar
;4java.rmi.s!rv!r.hostnam!9mycomput!r.!:ampl!.com
;4java.s!curity.policy9s!rv!r.policy
!ngin!.,omput!3ngin!
Solaris OS or Linux:
java ;cp /hom!/ann/src-/hom!/ann/publicThtml/class!s/comput!.jar
;4java.rmi.s!rv!r.co#!bas!9http-//mycomput!r/Zann/class!s/comput!.jar
;4java.rmi.s!rv!r.hostnam!9mycomput!r.!:ampl!.com
;4java.s!curity.policy9s!rv!r.policy
!ngin!.,omput!3ngin!
The above java command defines the following system properties:
T21 java.rmi.s!rv!r.co#!bas! /-(/1-"' $/1,#C1$ "21 *(,%"#(0> %
,(315%$1 ?RL> )-(6 &2#,2 "21 31C0#"#(0$ )(- ,*%$$1$
(-#+#0%"#0+ from "2#$ $1-<1- ,%0 51 3(&0*(%3134 I) "21
,(315%$1 $/1,#C1$ % 3#-1,"(-' 2#1-%-,2' 7%$ (//($13 "( % JAR
C*18> '(. 6.$" #0,*.31 % "-%#*#0+ $*%$2 %" "21 103 () "21
,(315%$1 ?RL4
T21 java.rmi.s!rv!r.hostnam! /-(/1-"' $/1,#C1$ "21 2($" 0%61 (-
%33-1$$ "( /." #0 "21 $".5$ )(- -16("1 (591,"$ 1A/(-"13 #0 "2#$
J%<% <#-".%* 6%,2#014 T2#$ <%*.1 #$ "21 2($" 0%61 (- %33-1$$
.$13 5' ,*#10"$ &210 "21' %""16/" "( ,(66.0#,%"1 -16("1
61"2(3 #0<(,%"#(0$4 B' 31)%.*"> "21 RMI #6/*1610"%"#(0 .$1$
"21 $1-<1-B$ IP %33-1$$ %$ #03#,%"13 5'
"21 java.n!t.6n!t0##r!ss.g!t1ocalost API4 @(&1<1-> $(61"#61$>
"2#$ %33-1$$ #$ 0(" %//-(/-#%"1 )(- %** ,*#10"$ %03 % ).**'
D.%*#C13 2($" 0%61 &(.*3 51 6(-1 1=1,"#<14 T( 10$.-1 "2%"
RMI .$1$ % 2($" 0%61 7(- IP %33-1$$8 )(- "21 $1-<1- "2%" #$
-(."%5*1 )-(6 %** /("10"#%* ,*#10"$> $1"
"21java.rmi.s!rv!r.hostnam! /-(/1-"'4
T21 java.s!curity.policy /-(/1-"' #$ .$13 "( $/1,#)' "21 /(*#,' C*1
"2%" ,(0"%#0$ "21 /1-6#$$#(0$ '(. #0"103 "( +-%0"4
MAT SOFT
JAVA REFERENCE GUIDE
247
Startin# the Client
)nce the registry and the compute engine are running, you can start the client,
specifying the following:
T21 *(,%"#(0 &21-1 "21 ,*#10" $1-<1$ #"$ ,*%$$1$ 7"21 Pi ,*%$$8 5'
.$#0+ "21 java.rmi.s!rv!r.co#!bas! /-(/1-"'
T21 java.s!curity.policy /-(/1-"'> &2#,2 #$ .$13 "( $/1,#)' "21
$1,.-#"' /(*#,' C*1 "2%" ,(0"%#0$ "21 /1-6#$$#(0$ '(. #0"103 "(
+-%0" "( <%-#(.$ /#1,1$ () ,(31
A$ ,(66%03;*#01 %-+.610"$> "21 2($" 0%61 () "21 $1-<1- 7$(
"2%" "21 ,*#10" :0(&$ &21-1 "( *(,%"1 "21 ,omput! -16("1 (591,"8
%03 "21 0.651- () 31,#6%* /*%,1$ "( .$1 #0 "21 ,%*,.*%"#(0
&tart the client on another host +a host named mys!con#comput!r, for e(ample, as
follows:
Microsoft Windows:
java ;cp c-Ohom!Ojon!sOsrc*c-Ohom!Ojon!sOpublicThtmlOclass!sOcomput!.jar
;4java.rmi.s!rv!r.co#!bas!9fil!-/c-/hom!/jon!s/publicThtml/class!s/
;4java.s!curity.policy9cli!nt.policy
cli!nt.,omput!Pi mycomput!r.!:ampl!.com FH
Solaris OS or Linux:
java ;cp /hom!/jon!s/src-/hom!/jon!s/publicThtml/class!s/comput!.jar
;4java.rmi.s!rv!r.co#!bas!9http-//mys!con#comput!r/Zjon!s/class!s/
;4java.s!curity.policy9cli!nt.policy
cli!nt.,omput!Pi mycomput!r.!:ampl!.com FH
Note that the class path is set on the command line so that the interpreter can find the
client classes and the *"2 file containing the interfaces. "lso note that the value of
thejava.rmi.s!rv!r.co#!bas! property, which specifies a directory hierarchy, ends
with a trailing slash.
"fter you start the client, the following output is displayed:
D.CFCHK@MHDHJKIKD@DJFM@MFDDJD@IKHE@JJFCKICMKDKK
MAT SOFT
JAVA REFERENCE GUIDE
248
The following figure illustrates where the rmir!gistry, the ,omput!3ngin! server, and
the ,omput!Pi client obtain classes during program e(ecution.
:hen the ,omput!3ngin! server binds its remote ob%ect reference in the registry, the
registry downloads the ,omput! and Tas< interfaces on which the stub class depends.
These classes are downloaded from either the ,omput!3ngin! server$s web server or
file system, depending on the type of codebase 826 used when starting the server.
#ecause the ,omput!Pi client has both the ,omput! and the Tas< interfaces available in
its class path, it loads their definitions from its class path, not from the server$s
codebase.
'inally, the Pi class is loaded into the ,omput!3ngin! server$s *ava virtual machine
when the Pi ob%ect is passed in the !:!cut!Tas< remote call to
the ,omput!3ngin!ob%ect. The Pi class is loaded by the server from either the client$s
web server or file system, depending on the type of codebase 826 used when starting
the client.
MAT SOFT
JAVA REFERENCE GUIDE
249
Day 27: APPLETS
An applet is a Java program that runs in a Web browser. An applet can be a fully functional Java
application because it has the entire Java API at its disposal.
There are some important differences between an applet and a standalone Java application, including
the following:
An applet is a Java class that extends the java.applet.Applet class.
A main() method is not invoked on an applet, and an applet class will not define main().
Applets are designed to be embedded within an HTML page.
When a user views an HTML page that contains an applet, the code for the applet is
downloaded to the user's machine.
A JVM is required to view an applet. The JVM can be either a plug-in of the Web browser or a
separate runtime environment.
The JVM on the user's machine creates an instance of the applet class and invokes various
methods during the applet's lifetime.
Applets have strict security rules that are enforced by the Web browser. The security of an
applet is often referred to as sandbox security, comparing the applet to a child playing in a
sandbox with various rules that must be followed.
Other classes that the applet needs can be downloaded in a single Java Archive (JAR) file.
MAT SOFT
JAVA REFERENCE GUIDE
250
Life Cycle of an Applet:
Four methods in the Applet class give you the framework on which you build any serious applet:
init: This method is intended for whatever initialization is needed for your applet. It is called
after the param tags inside the applet tag have been processed.
start: This method is automatically called after the browser calls the init method. It is also
called whenever the user returns to the page containing the applet after having gone off to
other pages.
stop: This method is automatically called when the user moves off the page on which the
applet sits. It can, therefore, be called repeatedly in the same applet.
destroy: This method is only called when the browser shuts down normally. Because applets
are meant to live on an HTML page, you should not normally leave resources behind after a
user leaves the page that contains the applet.
paint: Invoked immediately after the start() method, and also any time the applet needs to
repaint itself in the browser. The paint() method is actually inherited from the java.awt.
A "Hello, World" Applet:
The following is a simple applet named HelloWorldApplet.java:
import java.appl!t.**
import java.awt.**
public class !llo"orl#0ppl!t !:t!n#s 0ppl!t
{
public voi# paint $8raphics g(
{
g.#raw%tring $)!llo "orl#)2 @H2 HE(*
+
+
These import statements bring the classes into the scope of our applet class:
java.applet.Applet.
java.awt.Graphics.
Without those import statements, the Java compiler would not recognize the classes Applet and
Graphics, which the applet class refers to.
The Applet CLASS:
Every applet is an extension of the ja!a.applet.-pplet class. The base Applet class provides methods
that a derived Applet class may call to obtain information and services from the browser context.
These include methods that do the following:
MAT SOFT
JAVA REFERENCE GUIDE
251
Get applet parameters
Get the network location of the HTML file that contains the applet
Get the network location of the applet class directory
Print a status message in the browser
Fetch an image
Fetch an audio clip
Play an audio clip
Resize the applet
Additionally, the Applet class provides an interface by which the viewer or browser obtains information
about the applet and controls the applet's execution. The viewer may:
request information about the author, version and copyright of the applet
request a description of the parameters the applet recognizes
initialize the applet
destroy the applet
start the applet's execution
stop the applet's execution
The Applet class provides default implementations of each of these methods. Those implementations
may be overridden as necessary.
The "Hello, World" applet is complete as it stands. The only method overridden is the paint method.
Invoking an Applet:
An applet may be invoked by embedding directives in an HTML file and viewing the file through an
applet viewer or Java-enabled browser.
The <applet> tag is the basis for embedding an applet in an HTML file. Below is an example that
invokes the "Hello, World" applet:
Nhtml.
Ntitl!.Th! !llo2 "orl# 0ppl!tN/titl!.
Nhr.
Nappl!t co#!9)!llo"orl#0ppl!t.class) wi#th9)D@E) h!ight9)C@E).
6f your brows!r was Java;!nabl!#2 a )!llo2 "orl#)
m!ssag! woul# app!ar h!r!.
N/appl!t.
Nhr.
N/html.
MAT SOFT
JAVA REFERENCE GUIDE
252
Note: You can refer to HTML Applet Tag to understand more about calling applet from HTML.
The code attribute of the <applet> tag is required. It specifies the Applet class to run. Width and
height are also required to specify the initial size of the panel in which an applet runs. The applet
directive must be closed with a </applet> tag.
If an applet takes parameters, values may be passed for the parameters by adding <param> tags
between <applet> and </applet>. The browser ignores text and other tags between the applet tags.
Non-Java-enabled browsers do not process <applet> and </applet>. Therefore, anything that appears
between the tags, not related to the applet, is visible in non-Java-enabled browsers.
The viewer or browser looks for the compiled Java code at the location of the document. To specify
otherwise, use the codebase attribute of the <applet> tag as shown:
Nappl!t co#!bas!9)http-//amroo#.com/appl!ts)
co#!9)!llo"orl#0ppl!t.class) wi#th9)D@E) h!ight9)C@E).
If an applet resides in a package other than the default, the holding package must be specified in the
code attribute using the period character (.) to separate package/class components. For example:
Nappl!t co#!9)mypac<ag!.subpac<ag!.T!st0ppl!t.class)
wi#th9)D@E) h!ight9)C@E).
Getting Applet Parameters:
The following example demonstrates how to make an applet respond to setup parameters specified in
the document. This applet displays a checkerboard pattern of black and a second color.
The second color and the size of each square may be specified as parameters to the applet within the
document.
CheckerApplet gets its parameters in the init() method. It may also get its parameters in the paint()
method. However, getting the values and saving the settings once at the start of the applet, instead of
at every refresh, is convenient and efficient.
The applet viewer or browser calls the init() method of each applet it runs. The viewer calls init() once,
immediately after loading the applet. (Applet.init() is implemented to do nothing.) Override the default
implementation to insert custom initialization code.
The Applet.getParameter() method fetches a parameter given the parameter's name (the value of a
parameter is always a string). If the value is numeric or other non-character data, the string must be
parsed.
The following is a skeleton of CheckerApplet.java:
import java.appl!t.**
import java.awt.**
public class ,h!c<!r0ppl!t !:t!n#s 0ppl!t
{
MAT SOFT
JAVA REFERENCE GUIDE
253
int sPuar!%i/! 9 HE*// initiali/!# to #!fault si/!
public voi# init $( {+
privat! voi# pars!%Puar!%i/! $%tring param( {+
privat! ,olor pars!,olor $%tring param( {+
public voi# paint $8raphics g( {+
+
Here are CheckerApplet's init() and private parseSquareSize() methods:
public voi# init $(
{
%tring sPuar!%i/!Param 9 g!tParam!t!r $)sPuar!%i/!)(*
pars!%Puar!%i/! $sPuar!%i/!Param(*
%tring colorParam 9 g!tParam!t!r $)color)(*
,olor fg 9 pars!,olor $colorParam(*
s!tLac<groun# $,olor.blac<(*
s!tFor!groun# $fg(*
+
privat! voi# pars!%Puar!%i/! $%tring param(
{
if $param 99 null( r!turn*
try {
sPuar!%i/! 9 6nt!g!r.pars!6nt $param(*
+
catch $3:c!ption !( {
// 1!t #!fault valu! r!main
+
+
The applet calls parseSquareSize() to parse the squareSize parameter. parseSquareSize() calls the
library method Integer.parseInt(), which parses a string and returns an integer. Integer.parseInt()
throws an exception whenever its argument is invalid.
Therefore, parseSquareSize() catches exceptions, rather than allowing the applet to fail on bad input.
The applet calls parseColor() to parse the color parameter into a Color value. parseColor() does a
series of string comparisons to match the parameter value to the name of a predefined color. You need
to implement these methods to make this applet works.
Specifying Applet Parameters:
The following is an example of an HTML file with a CheckerApplet embedded in it. The HTML file
specifies both parameters to the applet by means of the <param> tag.
Nhtml.
Ntitl!.,h!c<!rboar# 0ppl!tN/titl!.
Nhr.
Nappl!t co#!9),h!c<!r0ppl!t.class) wi#th9)FJE) h!ight9)D@E).
Nparam nam!9)color) valu!9)blu!).
Nparam nam!9)sPuar!si/!) valu!9)DE).
N/appl!t.
MAT SOFT
JAVA REFERENCE GUIDE
254
Nhr.
N/html.
Note: Parameter names are not case sensitive.
Application Conversion to Applets:
It is easy to convert a graphical Java application (that is, an application that uses the AWT and that
you can start with the java program launcher) into an applet that you can embed in a web page.
Here are the specific steps for converting an application to an applet.
1. Make an HTML page with the appropriate tag to load the applet code.
2. Supply a subclass of the JApplet class. Make this class public. Otherwise, the applet cannot be
loaded.
3. Eliminate the main method in the application. Do not construct a frame window for the
application. Your application will be displayed inside the browser.
4. Move any initialization code from the frame window constructor to the init method of the
applet. You don't need to explicitly construct the applet object.the browser instantiates it for
you and calls the init method.
5. Remove the call to setSize; for applets, sizing is done with the width and height parameters in
the HTML file.
6. Remove the call to setDefaultCloseOperation. An applet cannot be closed; it terminates when
the browser exits.
7. If the application calls setTitle, eliminate the call to the method. Applets cannot have title bars.
(You can, of course, title the web page itself, using the HTML title tag.)
8. Don't call setVisible(true). The applet is displayed automatically.
Event Handling:
Applets inherit a group of event-handling methods from the Container class. The Container class
defines several methods, such as processKeyEvent and processMouseEvent, for handling particular
types of events, and then one catch-all method called processEvent.
Inorder to react an event, an applet must override the appropriate event-specific method.
import java.awt.!v!nt.Mous!1ist!n!r*
import java.awt.!v!nt.Mous!3v!nt*
import java.appl!t.0ppl!t*
import java.awt.8raphics*
public class 3:ampl!3v!ntan#ling !:t!n#s 0ppl!t
impl!m!nts Mous!1ist!n!r {
%tringLuff!r strLuff!r*
MAT SOFT
JAVA REFERENCE GUIDE
255
public voi# init$( {
a##Mous!1ist!n!r$this(*
strLuff!r 9 n!w %tringLuff!r$(*
a##6t!m$)initiali/ing th! appl! )(*
+
public voi# start$( {
a##6t!m$)starting th! appl!t )(*
+
public voi# stop$( {
a##6t!m$)stopping th! appl!t )(*
+
public voi# #!stroy$( {
a##6t!m$)unloa#ing th! appl!t)(*
+
voi# a##6t!m$%tring wor#( {
%yst!m.out.println$wor#(*
strLuff!r.app!n#$wor#(*
r!paint$(*
+
public voi# paint$8raphics g( {
//4raw a 7!ctangl! aroun# th! appl!t's #isplay ar!a.
g.#raw7!ct$E2 E2
g!t"i#th$( ; C2
g!t!ight$( ; C(*
//#isplay th! string insi#! th! r!ctangl!.
g.#raw%tring$strLuff!r.to%tring$(2 CE2 @E(*
+

public voi# mous!3nt!r!#$Mous!3v!nt !v!nt( {
+
public voi# mous!3:it!#$Mous!3v!nt !v!nt( {
+
public voi# mous!Pr!ss!#$Mous!3v!nt !v!nt( {
+
public voi# mous!7!l!as!#$Mous!3v!nt !v!nt( {
+
public voi# mous!,lic<!#$Mous!3v!nt !v!nt( {
a##6t!m$)mous! clic<!#G )(*
+
+
Now let us call this applet as follows:
Nhtml.
Ntitl!.3v!nt an#lingN/titl!.
MAT SOFT
JAVA REFERENCE GUIDE
256
Nhr.
Nappl!t co#!9)3:ampl!3v!ntan#ling.class)
wi#th9)DEE) h!ight9)DEE).
N/appl!t.
Nhr.
N/html.
Initially the applet will display "initializing the applet. Starting the applet." Then once you click inside
the rectangle "mouse clicked" will be displayed as well.
Based on the above examples, here is the live applet example: Applet Example.
Displaying Images:
An applet can display images of the format GIF, JPEG, BMP, and others. To display an image within the
applet, you use the drawImage() method found in the java.awt.Graphics class.
Following is the example showing all the steps to show images:
import java.appl!t.**
import java.awt.**
import java.n!t.**
public class 6mag!4!mo !:t!n#s 0ppl!t
{
privat! 6mag! imag!*
privat! 0ppl!t,ont!:t cont!:t*
public voi# init$(
{
cont!:t 9 this.g!t0ppl!t,ont!:t$(*
%tring imag!571 9 this.g!tParam!t!r$)imag!)(*
if$imag!571 99 null(
{
imag!571 9 )java.jpg)*
+
try
{
571 url 9 n!w 571$this.g!t4ocum!ntLas!$(2 imag!571(*
imag! 9 cont!:t.g!t6mag!$url(*
+catch$Malform!#5713:c!ption !(
{
!.print%tac<Trac!$(*
// 4isplay in brows!r status bar
cont!:t.show%tatus$),oul# not loa# imag!G)(*
+
+
public voi# paint$8raphics g(
{
cont!:t.show%tatus$)4isplaying imag!)(*
g.#raw6mag!$imag!2 E2 E2 @EE2 JF2 null(*
g.#raw%tring$)www.javalic!ns!.com)2 DH2 CEE(*
+
+
MAT SOFT
JAVA REFERENCE GUIDE
257
Now let us call this applet as follows:
Nhtml.
Ntitl!.Th! 6mag!4!mo appl!tN/titl!.
Nhr.
Nappl!t co#!9)6mag!4!mo.class) wi#th9)DEE) h!ight9)@EE).
Nparam nam!9)imag!) valu!9)java.jpg).
N/appl!t.
Nhr.
N/html.
Based on the above examples, here is the live applet example: Applet Example.
Playing Audio:
An applet can play an audio file represented by the AudioClip interface in the java.applet package. The
AudioClip interface has three methods, including:
p"$ic void p$ay,/: Plays the audio clip one time, from the beginning.
p"$ic void $oop,/: Causes the audio clip to replay continually.
p"$ic void stop,/: Stops playing the audio clip.
To obtain an AudioClip object, you must invoke the getAudioClip() method of the Applet class. The
getAudioClip() method returns immediately, whether or not the URL resolves to an actual audio file.
The audio file is not downloaded until an attempt is made to play the audio clip.
Following is the example showing all the steps to play an audio:
import java.appl!t.**
import java.awt.**
import java.n!t.**
public class 0u#io4!mo !:t!n#s 0ppl!t
{
privat! 0u#io,lip clip*
privat! 0ppl!t,ont!:t cont!:t*
public voi# init$(
{
cont!:t 9 this.g!t0ppl!t,ont!:t$(*
%tring au#io571 9 this.g!tParam!t!r$)au#io)(*
if$au#io571 99 null(
{
au#io571 9 )#!fault.au)*
+
try
{
571 url 9 n!w 571$this.g!t4ocum!ntLas!$(2 au#io571(*
clip 9 cont!:t.g!t0u#io,lip$url(*
+catch$Malform!#5713:c!ption !(
{
!.print%tac<Trac!$(*
MAT SOFT
JAVA REFERENCE GUIDE
258
cont!:t.show%tatus$),oul# not loa# au#io fil!G)(*
+
+
public voi# start$(
{
if$clip G9 null(
{
clip.loop$(*
+
+
public voi# stop$(
{
if$clip G9 null(
{
clip.stop$(*
+
+
+
Now let us call this applet as follows:
Nhtml.
Ntitl!.Th! 6mag!4!mo appl!tN/titl!.
Nhr.
Nappl!t co#!9)6mag!4!mo.class) wi#th9)E) h!ight9)E).
Nparam nam!9)au#io) valu!9)t!st.wav).
N/appl!t.
Nhr.
N/html.
You can use your test.wav at your PC to test the above example.
Day 28: E8%"t Dri8%" Pro7rammi"7
Event handling is fundamental to Java programming because it is integral to the creation of
applets and other types of GUI-based programs. Applets are event-driven programs that use a
graphical user interface to interact with the user. Furthermore, any program that uses a graphical
user interface, such as a Java application written for Windows, is event driven. Thus, you cannot
write these types of programs without a solid command of event handling. Events are supported
by a number of packages, including #ava1ti$, #ava1a3t, and #ava1a3t1event. Most events to
which your program will respond are generated when the user interacts with a GUI-based
program. These are the types of events examined in this chapter. They are passed to your
program in a variety of ways, with the specific method dependent upon the actual event. There
are several types of events, including those generated by the mouse, the keyboard, and various
GUI controls, such as a push button, scroll bar, or check box. This chapter begins with an
overview of Javas event handling mechanism. It then examines the main event classes and
interfaces used by the AWT and develop several examples that demonstrate the fundamentals of
MAT SOFT
JAVA REFERENCE GUIDE
259
event processing. This chapter also explains how to use adapter classes, inner classes, and
anonymous inner classes to streamline event handling code. The examples provided in the
remainder of this book make frequent use of these techniques.
NOTE This chapter $ocuses on e!ents related to 785-based programs. )o0e!er3 e!ents are
alsooccasionally used $or purposes not directly related to 785-based programs. 5n all cases3 the
samebasic e!ent handling techni4ues apply.
Two Event Handling Mechanisms
Before beginning our discussion of event handling, an important point must be made: The way in
which events are handled changed significantly between the original version of Java (1.0) and
modern versions of Java, beginning with version 1.1. The 1.0 method of event handling is still
supported, but it is not recommended for new programs. Also, many of the methods that support
the old 1.0 event model have been deprecated. The modern approach is the way that events
should be handled by all new programs and thus is the method employed by programs in this
book.
The Delegation Event Model
The modern approach to handling events is based on the delegation e!ent model3 which defines
standard and consistent mechanisms to generate and process events. Its concept is quite simple:
a source generates an event and sends it to one or more listeners. In this scheme, the listener
simply waits until it receives an event. Once an event is received, the listener processes the
event and then returns. The advantage of this design is that the application logic that processes
events is cleanly separated from the user interface logic that generates those events. Auser
interface element is able to "delegate the processing of an event to a separate piece of code. In
the delegation event model, listeners must register with a source in order to receive an event
notification. This provides an important benefit: notifications are sent only to listeners that want
to receive them. This is a more efficient way to handle events than the design used by the old
Java 1.0 approach. Previously, an event was propagated up the containment hierarchy until it
was handled by a component. This required components to receive events that they did not
process, and it wasted valuable time. The delegation event model eliminates this overhead.
NOTE: a!a also allo0s you to process e!ents 0ithout using the delegation e!ent model. This can
be done by extending an -*T component. This techni4ue is discussed at the end o$ Chapter
9:.)o0e!er3 the delegation e!ent model is the pre$erred design $or the reasons just cited. The
following sections define events and describe the roles of sources and listeners.
7vents
In the delegation model, an e!ent 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. Many
other user operations could also be cited as examples. 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. You are free to define events that are appropriate for your application.
7vent Sorces
Asource is an object that generates an event. This occurs when the internal state of that
objectchanges in some way. Sources may generate more than one type of event. Asource must
MAT SOFT
JAVA REFERENCE GUIDE
260
register listeners in order for the listeners to receive notifications about a specific type of event.
Each type of event has its own registration method. Here is the general form:
public void addTypeListener(TypeListener el)
Here, Type is the name of the event, and el is a reference to the event listener. For example, the
method that registers a keyboard event listener is called add6ey0istener, /. The method that
registers a mouse motion listener is called addMoseMotion0istener, /. When an event
occurs, all registered listeners are notified and receive a copy of the event object. This is known
as multicasting the event. In all cases, notifications are sent only to listeners that register to
receive them.
Some sources may allow only one listener to register. The general form of such a method is this:
public void addTypeListener(TypeListener el) throws java.util.TooManyListenersException
Here, Type is the name of the event, and el is a reference to the event listener. When such an
event occurs, the registered listener is notified. This is known as unicasting the event. A source
must also provide a method that allows a listener to unregister an interest in a specific type of
event. The general form of such a method is this:
public void removeTypeListener(TypeListener el)
Here, Type is the name of the event, and el is a reference to the event listener. For example, to
remove a keyboard listener, you would call remove6ey0istener, /. The methods that add or
remove listeners are provided by the source that generatesevents. For example, the Component
class provides methods to add and remove keyboard and mouse event listeners.
7vent 0isteners
Alistener is an object that is notified when an event occurs. It has two major requirements. First,
it must have been registered with one or more sources to receive notifications about specific
types of events. Second, it must implement methods to receive and process these notifications.
The methods that receive and process events are defined in a set of interfaces found in
#ava1a3t1event. For example, the MoseMotion0istener interface defines two methods to
receive notifications when the mouse is dragged or moved. Any object may receive and process
one or both of these events if it provides an implementation of this interface. Many other listener
interfaces are discussed later in this and other chapters.
7vent C$asses
The classes that represent events are at the core of Javas event handling mechanism. Thus, a
discussion of event handling must begin with the event classes. It is important to understand,
however, that Java defines several types of events and that not all event classes can be
discussed in this chapter. The most widely used events are those defined by the AWT and those
defined by Swing. This chapter focuses on the AWT events. (Most of these events also apply to
Swing.)
At the root of the Java event class hierarchy is 7vent!"#ect, which is in #ava1ti$. 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.
MAT SOFT
JAVA REFERENCE GUIDE
261
7vent!"#ect contains two methods: getSorce, / and toString, /. The getSorce, / method
returns the source of the event. Its general form is shown here:
Object getSource( )
As expected, toString, / returns the string equivalent of the event.
The class %9T7vent, defined within the #ava1a3t package, is a subclass of 7vent!"#ect. It is
the superclass (either directly or indirectly) of all AWT-based events used by the delegation event
model. Its getI), / method can be used to determine the type of the event. The signature
of this method is shown here:
int getID( )
Additional details about %9T7vent are provided at the end of Chapter 24. At this point, it is
important to know only that all of the other classes discussed in this section are subclasses of
%9T7vent. To summarize:
- 7vent!"#ect is a superclass of all events.
- %9T7vent is a superclass of all AWT events that are handled by the delegationevent model.
The package #ava1a3t1event defines many types of events that are generated by various user
interface elements. Table 22-1 shows several commonly used event classes and provides a brief
description of when they are generated. Commonly used constructors and methods in each class
are described in the following sections.
Below are the list of Event classes & listeners with methods:
ActionEvent
-----------
String getActionCommand()
int getModifiers()
long getWhen()
AdjustmentEvent
---------------
Adjustable getAdjustable()
int getAdjustmentType()
int getValue()
ComponentEvent
--------------
Component getComponent()
MAT SOFT
JAVA REFERENCE GUIDE
262
ContainerEvent
--------------
Container getContainer()
Component getClild()
FocusEvent
----------
Component getOppositeComponent()
boolean isTemporary()
ItemEvent
---------
Object getItem()
ItemSelectable getItemSelectable()
KeyEvent
--------
char getKeyChar()
int getKeyCode()
MouseEvent
----------
int getX()
int getY()
Point getPoint()
void translatePoint(int x, int y)
int getClickCount()
boolean isPopupTrigger()
int getButton()
Point getLocationOnScreen()
int getXOnScreen()
int getYOnScreen()
WindowEvent
-----------
Window getWindow()
Window getOppositeWindow()
int getOldState()
int getNewState()
Event Generation Sources
========
Action Event - Button, List & Menu when double clicked
Item Event - check Box, Choice, List & Menu when item selected,
Adjustment Event - Scroll Bar
MAT SOFT
JAVA REFERENCE GUIDE
263
Text Event - Text Components
Window Event - Windows
Key Event - Text Box
ActionListener
--------------
public void actionPerformed(ActionEvent ae)
AdjustmentListener
------------------
public void adjustmentValueChanged(AdjustmentEvent ae)
ComponentListener
-----------------
public void componentResized(ComponentEvent ce)
public void componentMoved(ComponentEvent ce)
public void componentShown(ComponentEvent ce)
public void componentHidden(ComponentEvent ce)
ContainerListener
-----------------
public void componentAdded(ContainerEvent ce)
public void componentRemoved(ContainerEvent ce)
FocusListener
-------------
public void focusGained(FocusEvent fe)
public void focusLost(FocusEvent fe)
ItemListener
------------
public void itemStateChanged(ItemEvent ie)
KeyListener
-----------
public void keyPressed(KeyEvent ke)
public void keyReleased(KeyEvent ke)
public void keyTyped(KeyEvent ke)
MouseListener
-------------
public void mouseClicked(MouseEvent me)
public void mouseEntered(MouseEvent me)
public void mouseExited(MouseEvent me)
public void mousePressed(MouseEvent me)
MAT SOFT
JAVA REFERENCE GUIDE
264
public void mouseReleased(MouseEvent me)
TextListener
------------
public void textChanged(TextEvent te)
WindowListener
--------------
public void windowActivated(WindowEvent we)
public void windowClosed(WindowEvent we)
public void windowClosing(WindowEvent we)
public void windowDeactivated(WindowEvent we)
public void windowDeiconified(WindowEvent we)
public void windowIconified(WindowEvent we)
public void windowOpened(WindowEvent we)
Bsing the )e$egation 7vent Mode$
Now that you have learned the theory behind the delegation event model and have had an
overview of its various components, it is time to see it in practice. Using the delegation event
model is actually quite easy. Just follow 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. Remember that a source may generate several types of events. Each event
must be registered separately. Also, an object may register to receive several types of events,
but it must implement all of the interfaces that are required to receive these events.
To see how the delegation model works in practice, we will look at examples that handle two
commonly used event generators: the mouse and keyboard.
Handling Mouse Events
To handle mouse events, you must implement the Mose0istener and the
MoseMotion0istener interfaces. (You may also want to implement Mose9hee$0istener,
but we wont be doing so, here.) The following applet demonstrates the process. It displays the
current coordinates of the mouse in the applets status window. Each time a button is pressed,
the word "Down is displayed at the location of the mouse pointer. Each time the button is
released, the word "Up is shown. If a button is clicked, the message "Mouse clicked is displayed
in the upperleft corner of the applet display area.
As the mouse enters or exits the applet window, a message is displayed in the upper-left corner
of the applet display area. When dragging the mouse, a * is shown, which tracks with the mouse
pointer as it is dragged. Notice that the two variables, mose> and moseA, store the location
of the mouse when a mouse pressed, released, or dragged event occurs. These coordinates are
then used by paint, / to display output at the point of these occurrences.
// Demonstrate the mouse event handlers.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
MAT SOFT
JAVA REFERENCE GUIDE
265
<applet code="MouseEvents" width=300 height=100>
</applet>
*/
public class MouseEvents extends Applet
implements MouseListener, MouseMotionListener {
String msg = "";
int mouseX = 0, mouseY = 0; // coordinates of mouse
public void init() {
addMouseListener(this);
addMouseMotionListener(this);
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse clicked.";
repaint();
}
// Handle mouse entered.
public void mouseEntered(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse entered.";
repaint();
}
// Handle mouse exited.
public void mouseExited(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse exited.";
repaint();
}
// Handle button pressed.
public void mousePressed(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Down";
repaint();
}
// Handle button released.
public void mouseReleased(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Up";
repaint();
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
repaint();
}
// Handle mouse moved.
MAT SOFT
JAVA REFERENCE GUIDE
266
public void mouseMoved(MouseEvent me) {
// show status
showStatus("Moving mouse at " + me.getX() + ", " + me.getY());
}
// Display msg in applet window at current X,Y location.
public void paint(Graphics g) {
g.drawString(msg, mouseX, mouseY);
}
}
Handling Keyboard Events
To handle keyboard events, you use the same general architecture as that shown in the mouse
event example in the preceding section. The difference, of course, is that you will be
implementing the 6ey0istener interface. Before looking at an example, it is useful to review
how key events are generated. When a key is pressed, a 67AGP'7SS7) event is generated.
This results in a call to the =eyPressed,/ event handler. When the key is released, a
67AG'707%S7) event is generated and the =ey'e$eased,/ handler is executed. If a character
is generated by the keystroke, then a 67AGTAP7) event is sent and the =eyTyped, / handler is
invoked. Thus, each time the user presses a key, at least two and often three events are
generated. If all you care about are actual characters, then you can ignore the information
passed by the keypress and release events.
However, if your program needs to handle special keys, such as the arrow or function keys,
then it must watch for them through the =eyPressed, / handler. The following program
demonstrates keyboard input. It echoes keystrokes to the applet window and shows the
pressed/released status of each key in the status window.
// Demonstrate the key event handlers.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="SimpleKey" width=300 height=100>
</applet>
*/
public class SimpleKey extends Applet
implements KeyListener {
String msg = "";
int X = 10, Y = 20; // output coordinates
public void init() {
addKeyListener(this);
}
public void keyPressed(KeyEvent ke) {
showStatus("Key Down");
}
public void keyReleased(KeyEvent ke) {
showStatus("Key Up");
}
public void keyTyped(KeyEvent ke) {
msg += ke.getKeyChar();
repaint();
}
// Display keystrokes.
public void paint(Graphics g) {
g.drawString(msg, X, Y);
MAT SOFT
JAVA REFERENCE GUIDE
267
}
}
If you want to handle the special keys, such as the arrow or function keys, you need to respond
to them within the =eyPressed, / handler. They are not available through =eyTyped, /.
To identify the keys, you use their virtual key codes. For example, the next applet outputs the
name of a few of the special keys:
// Demonstrate some virtual key codes.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="KeyEvents" width=300 height=100>
</applet>
*/
public class KeyEvents extends Applet
implements KeyListener {
String msg = "";
int X = 10, Y = 20; // output coordinates
public void init() {
addKeyListener(this);
}
public void keyPressed(KeyEvent ke) {
showStatus("Key Down");
int key = ke.getKeyCode();
switch(key) {
case KeyEvent.VK_F1:
msg += "<F1>";
break;
case KeyEvent.VK_F2:
msg += "<F2>";
break;
case KeyEvent.VK_F3:
msg += "<F3>";
break;
case KeyEvent.VK_PAGE_DOWN:
msg += "<PgDn>";
break;
case KeyEvent.VK_PAGE_UP:
msg += "<PgUp>";
break;
case KeyEvent.VK_LEFT:
msg += "<Left Arrow>";
break;
case KeyEvent.VK_RIGHT:
msg += "<Right Arrow>";
break;
}
repaint();
}
public void keyReleased(KeyEvent ke) {
showStatus("Key Up");
}
public void keyTyped(KeyEvent ke) {
msg += ke.getKeyChar();
repaint();
}
MAT SOFT
JAVA REFERENCE GUIDE
268
// Display keystrokes.
public void paint(Graphics g) {
g.drawString(msg, X, Y);
}
}
The procedures shown in the preceding keyboard and mouse event examples can be generalized
to any type of event handling, including those events generated by controls. In later chapters,
you will see many examples that handle other types of events, but they will all follow the same
basic structure as the programs just described.
Adapter Classes
Java provides a special feature, called an adapter class3 that can simplify the creation of event
handlers in certain situations. An adapter class provides an empty implementation of all methods
in an event listener interface. 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. You can define
a 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.
For example, the MoseMotion%dapter class has two methods, mose)ragged, / and
moseMoved, /, which are the methods defined by the MoseMotion0istener interface. If
you were interested in only mouse drag events, then you could simply extend
MoseMotion%dapter and override mose)ragged, /. The empty implementation of
moseMoved, / would handle the mouse motion events for you.
The following example demonstrates an adapter. It displays a message in the status bar of an
applet viewer or browser when the mouse is clicked or dragged. However, all other mouse events
are silently ignored. The program has three classes. %dapter)emo extends %pp$et. Its init, /
method creates an instance of MyMose%dapter and registers that object to receive
notifications of mouse events. It also creates an instance of MyMoseMotion%dapter and
registers that object to receive notifications of mouse motion events. Both of the constructors
take a reference to the applet as an argument.
MyMose%dapter extends Mose%dapter and overrides the moseC$ic=ed, / method. The
other mouse events are silently ignored by code inherited from the Mose%dapter class.
MyMoseMotion%dapter extends MoseMotion%dapter and overrides the
mose)ragged, / method. The other mouse motion event is silently ignored by code inherited
from the MoseMotion%dapter class.
Note that both of the event listener classes save a reference to the applet. This information is
provided as an argument to their constructors and is used later to invoke the sho3Stats,/
method.
// Demonstrate an adapter.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
Adapter Class Listener Interface
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
FocusAdapter FocusListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
MAT SOFT
JAVA REFERENCE GUIDE
269
WindowAdapter WindowListener
TABLE 22-4
Commonly Used
Listener Interfaces
Implemented by
Adapter Classes
<applet code="AdapterDemo" width=300 height=100>
</applet>
*/
public class AdapterDemo extends Applet {
public void init() {
addMouseListener(new MyMouseAdapter(this));
addMouseMotionListener(new MyMouseMotionAdapter(this));
}
}
class MyMouseAdapter extends MouseAdapter {
AdapterDemo adapterDemo;
public MyMouseAdapter(AdapterDemo adapterDemo) {
this.adapterDemo = adapterDemo;
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me) {
adapterDemo.showStatus("Mouse clicked");
}
}
class MyMouseMotionAdapter extends MouseMotionAdapter {
AdapterDemo adapterDemo;
public MyMouseMotionAdapter(AdapterDemo adapterDemo) {
this.adapterDemo = adapterDemo;
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me) {
adapterDemo.showStatus("Mouse dragged");
}
}
As you can see by looking at the program, not having to implement all of the methods defined by
the MoseMotion0istener and Mose0istener interfaces saves you a considerable amount of
effort and prevents your code from becoming cluttered with empty methods. As an exercise, you
might want to try rewriting one of the keyboard input examples shown earlier so that it uses a
6ey%dapter.
Inner Classes
To understand the benefit provided by 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. MosePressed)emo extends %pp$et, and MyMose%dapter extends
Mose%dapter. The init, / method of MosePressed)emo instantiates MyMose%dapter
and provides this object as an argument to the addMose0istener, / method. Notice that a
reference to the applet is supplied as an argument to the MyMose%dapter constructor. This
reference is stored in an instance variable for later use by the mosePressed, / method. When
the mouse is pressed, it invokes the sho3Stats, / method of the applet through the stored
applet reference. In other words, sho3Stats, / is invoked relative to the applet reference
stored by MyMose%dapter.
// This applet does NOT use an inner class.
import java.applet.*;
import java.awt.event.*;
/*
MAT SOFT
JAVA REFERENCE GUIDE
270
<applet code="MousePressedDemo" width=200 height=100>
</applet>
*/
public class MousePressedDemo extends Applet {
public void init() {
addMouseListener(new MyMouseAdapter(this));
}
}
class MyMouseAdapter extends MouseAdapter {
MousePressedDemo mousePressedDemo;
public MyMouseAdapter(MousePressedDemo mousePressedDemo) {
this.mousePressedDemo = mousePressedDemo;
}
public void mousePressed(MouseEvent me) {
mousePressedDemo.showStatus("Mouse Pressed.");
}
}
The following listing shows how the preceding program can be improved by using an inner class.
Here, InnerC$ass)emo is a top-level class that extends %pp$et. MyMose%dapter is an inner
class that extends Mose%dapter. Because MyMose%dapter is defined within the scope of
InnerC$ass)emo, it has access to all of the variables and methods within the scope of that
class. Therefore, the mosePressed, / method can call the sho3Stats, / method directly. It
no longer needs to do this via a stored reference to the applet. Thus, it is no longer necessary to
pass MyMose%dapter, / a reference to the invoking object.
// Inner class demo.
import java.applet.*;
import java.awt.event.*;
/*
<applet code="InnerClassDemo" width=200 height=100>
</applet>
*/
public class InnerClassDemo extends Applet {
public void init() {
addMouseListener(new MyMouseAdapter());
}
class MyMouseAdapter extends MouseAdapter {
public void mousePressed(MouseEvent me) {
showStatus("Mouse Pressed");
}
}
}
%nonymos Inner C$asses
An anonymous inner class is one that is not assigned a name. This section illustrates how an
anonymous inner class can facilitate the writing of event handlers. Consider the applet shown in
the following listing. As before, its goal is to display the string "Mouse Pressed in the status bar
of the applet viewer or browser when the mouse is pressed.
// Anonymous inner class demo.
import java.applet.*;
import java.awt.event.*;
/*
<applet code="AnonymousInnerClassDemo" width=200 height=100>
</applet>
*/
public class AnonymousInnerClassDemo extends Applet {
public void init() {
addMouseListener(new MouseAdapter() {
MAT SOFT
JAVA REFERENCE GUIDE
271
public void mousePressed(MouseEvent me) {
showStatus("Mouse Pressed");
}
});
}
}
There is one top-level class in this program: %nonymosInnerC$ass)emo. The init, / method
calls the addMose0istener, / method. Its argument is an expression that definesand
instantiates an anonymous inner class. Lets analyze this expression carefully. The syntax ne3
Mose%dapter, / C 111 D indicates to the compiler that the code between the braces defines an
anonymous inner class. Furthermore, that class extends Mose%dapter. This new class is not
named, but it is automatically instantiated when this expression is executed.Because this
anonymous inner class is defined within the scope of %nonymosInnerC$ass)emo, it has
access to all of the variables and methods within the scope of that class. Therefore, it can call the
sho3Stats, / method directly. As just illustrated, both named and anonymous inner classes
solve some annoying problems in a simple yet effective way. They also allow you to create more
efficient code.
D%' 29G AWT ; W(-:#0+ &#"2 W#03(&$> -%/2#,$> C(*(-> F(0"
%03 T1A"
The Abstract Window Toolkit (AWT) contains numerous classes and methods that allow you
to create and manage windows. It is also the foundation upon which Swing is built. The AWT is
quite large and a full description would easily fill an entire book. Therefore, it is not possible to
describe in detail every AWT class, method, or instance variable. However, this and the following
two chapters explain the basic techniques needed to use the AWT effectively when creating your
own applets or stand-alone GUI-based applications. From there, you will be able to explore other
parts of the AWT on your own. You will also be ready to move on to Swing.
In this chapter, you will learn how to create and manage windows, manage fonts, output text,
and utilize graphics. For the sake of convenience, most of the examples in this chapter are
contained in applets. To run them, you need to use an applet viewer or a Java-compatible web
browser. A few examples will demonstrate the creation of stand-alone, windowed programs. One
other point before beginning. Today, most Java programs employ user interfaces based on Swing.
Because Swing provides richer implementations than does the AWT of some common GUI
controls, such as buttons, lists, and check boxes, it is easy to jump to the conclusion that the
AWT is no longer important, that it has been superseded by Swing. This assumption is, however,
quite wrong. As mentioned, Swing is built on top of the AWT. Thus, many aspects of the AWT are
also aspects of Swing. Furthermore, many AWT classes are used either directly or indirectly by
Swing. Finally, for some types of small programs (especially small applets) that make only
minimal use of a GUI, using the AWT rather than Swing still makes sense. Therefore, even
though most interfaces today will be based on Swing, a solid knowledge of the AWT is still
required. Simply put, you cant be a great Java programmer without knowing the AWT.
MAT SOFT
JAVA REFERENCE GUIDE
272
NOTE 5$ you ha!e not yet read Chapter 993 please do so no0. 5t pro!ides an o!er!ie0 o$ e!ent
handling3 0hich is used by many o$ the examples in this chapter.
9indo3 +ndamenta$s
The AWT defines windows according to a class hierarchy that adds functionality and specificity
with each level. The two most common windows are those derived from Pane$, which is used by
applets, and those derived from +rame, which creates a standard application window. Much of
the functionality of these windows is derived from their parent classes. Thus, a description of the
class hierarchies relating to these two classes is fundamental to their understanding.
Component
At the top of the AWT hierarchy is the Component class. Component is an abstract class that
encapsulates all of the attributes of a visual component. All user interface elements that are
displayed on the screen and that interact with the user are subclasses of Component. It defines
over a hundred public methods that are responsible for managing events, such as mouse and
keyboard input, positioning and sizing the window, and repainting. (You already used many of
these methods when you created applets in Chapters 21 and 22.) A Component object is
responsible for remembering the current foreground and background colors and the currently
selected text font.
Container
The Container class is a subclass of Component. It has additional methods that allow other
Component objects to be nested within it. Other Container objects can be stored inside of a
Container (since they are themselves instances of Component). This makes for a multileveled
containment system. A container is responsible for laying out (that is, positioning) any
components that it contains. It does this through the use of various layout managers.
Pane$
The Pane$ class is a concrete subclass of Container. It doesnt add any new methods; it simply
implements Container. A Pane$ may be thought of as a recursively nestable, concrete screen
component. Pane$ is the superclass for %pp$et. When screen output is directed to an applet, it is
drawn on the surface of a Pane$ object. In essence, a Pane$ is a window that does not contain a
title bar, menu bar, or border. This is why you dont see these items when an applet is run inside
a browser. When you run an applet using an applet viewer, the applet viewer provides the title
and border. Other components can be added to a Pane$ object by its add, / method (inherited
from Container). Once these components have been added, you can position and resize them
manually using the set0ocation, /, setSi2e, /, setPreferredSi2e, /, or setBonds, /
methods defined by Component.
9indo3
The9indo3 class creates a top-level window. Atop-le!el 0indo0 is not contained within any
other object; it sits directly on the desktop. Generally, you wont create 9indo3 objects directly.
Instead, you will use a subclass of 9indo3 called +rame, described next.
+rame
+rame encapsulates what is commonly thought of as a "window. It is a subclass of9indo3 and
has a title bar, menu bar, borders, and resizing corners. If you create a +rame object from within
an applet, it will contain a warning message, such as "Java Applet Window, to the user that an
applet window has been created. This message warns users that the window they see was
started by an applet and not by software running on their computer. (An applet that could
MAT SOFT
JAVA REFERENCE GUIDE
273
masquerade as a host-based application could be used to obtain passwords and other sensitive
information without the users knowledge.) When a +rame window is created by a stand-alone
application rather than an applet, a normal window is created.
Canvas
Although it is not part of the hierarchy for applet or frame windows, there is one other type of
window that you will find valuable: Canvas. Canvas encapsulates a blank window upon which
you can draw.
9or=ing 3ith +rame 9indo3s
After the applet, the type of window you will most often create is derived from +rame. You will
use it to create child windows within applets, and top-level or child windows for stand-alone
applications. As mentioned, it creates a standard-style window. Here are two of +rames
constructors:
Frame( )
Frame(String title)
The first form creates a standard window that does not contain a title. The second form creates a
window with the title specified by title. Notice that you cannot specify the dimensions of the
window. Instead, you must set the size of the window after it has been created. There are
several key methods you will use when working with +rame windows. They are examined here.
Setting the 9indo3s )imensions
The setSi2e, / method is used to set the dimensions of the window. Its signature is shown here:
void setSize(int ne0*idth, int ne0)eight)
void setSize(Dimension ne02i/e)
The new size of the window is specified by ne0*idth and ne0)eight, or by the 3idth and
height fields of the )imension object passed in ne02i/e. The dimensions are specified in terms
of pixels. The getSi2e, / method is used to obtain the current size of a window. Its signature is
shown here:
Dimension getSize( )
This method returns the current size of the window contained within the 3idth and height fields
of a )imension object.
(iding and Sho3ing a 9indo3
After a frame window has been created, it will not be visible until you call set*isi"$e, /.Its
signature is shown here:
void setVisible(boolean !isible'lag)
The component is visible if the argument to this method is tre. Otherwise, it is hidden.
Setting a 9indo3s Tit$e
You can change the title in a frame window using setTit$e, /, which has this general form:
void setTitle(String ne0Title)
MAT SOFT
JAVA REFERENCE GUIDE
274
Here, ne0Title is the new title for the window.
C$osing a +rame 9indo3
When using a frame window, your program must remove that window from the screen when it is
closed, by calling set*isi"$e,fa$se/. To intercept a window-close event, you must implement the
3indo3C$osing, / method of the 9indo30istener interface. Inside 3indo3C$osing, /, you
must remove the window from the screen. The example in the next section illustratesthis
technique.
Creating a +rame 9indo3 in an %pp$et
While it is possible to simply create a window by creating an instance of +rame, you will seldom
do so, because you will not be able to do much with it. For example, you will not be able to
receive or process events that occur within it or easily output information to it. Most of the time,
you will create a subclass of +rame. Doing so lets you override +rames methods and provide
event handling.
Creating a new frame window from within an applet is actually quite easy. First, create a subclass
of +rame. Next, override any of the standard applet methods, such as init, /, start, /, and
stop, /, to show or hide the frame as needed. Finally, implement the 3indo3C$osing,/method
of the9indo30istener interface, calling set*isi"$e,fa$se/ when the window is closed. Once
you have defined a +rame subclass, you can create an object of that class. This causes a frame
window to come into existence, but it will not be initially visible. You make it visible by calling
set*isi"$e, /. When created, the window is given a default height and width. You can set the
size of the window explicitly by calling the setSi2e, / method.
The following applet creates a subclass of +rame called Samp$e+rame. A window of this
subclass is instantiated within the init, / method of %pp$et+rame. Notice that Samp$e+rame
calls +rames constructor. This causes a standard frame window to be created with the title
passed in tit$e. This example overrides the applets start, / and stop, / methods so that they
show and hide the child window, respectively. This causes the window to be removed
automatically when you terminate the applet, when you close the window, or, if using a browser,
when you move to another page. It also causes the child window to be shown when the browser
returns to the applet.
// Create a child frame window from within an applet.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="AppletFrame" width=300 height=50>
</applet>
*/
// Create a subclass of Frame.
class SampleFrame extends Frame {
SampleFrame(String title) {
super(title);
// create an object to handle window events
MyWindowAdapter adapter = new MyWindowAdapter(this);
// register it to receive those events
addWindowListener(adapter);
}
public void paint(Graphics g) {
g.drawString("This is in frame window", 10, 40);
}
}
class MyWindowAdapter extends WindowAdapter {
MAT SOFT
JAVA REFERENCE GUIDE
275
SampleFrame sampleFrame;
public MyWindowAdapter(SampleFrame sampleFrame) {
this.sampleFrame = sampleFrame;
}
public void windowClosing(WindowEvent we) {
sampleFrame.setVisible(false);
}
}
// Create frame window.
public class AppletFrame extends Applet {
Frame f;
public void init() {
f = new SampleFrame("A Frame Window");
f.setSize(250, 250);
f.setVisible(true);
}
public void start() {
f.setVisible(true);
}
public void stop() {
f.setVisible(false);
}
public void paint(Graphics g) {
g.drawString("This is in applet window", 10, 20);
}
}
Sample output from this program is shown here:
(and$ing 7vents in a +rame 9indo3
Since +rame is a subclass of Component, it inherits all the capabilities defined by Component.
This means that you can use and manage a frame window just like you manage an appletsmain
window. For example, you can override paint, / to display output, call repaint, / when you
need to restore the window, and add event handlers. Whenever an event occurs in a window, the
event handlers defined by that window will be called. Each window handles its own events. For
example, the following program creates a window that responds to mouse events. The main
applet window also responds to mouse events. When you experiment with this program, you will
see that mouse events are sent to the window in which the event occurs.
// Handle mouse events in both child and applet windows.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="WindowEvents" width=300 height=50>
</applet>
*/
// Create a subclass of Frame.
class SampleFrame extends Frame
implements MouseListener, MouseMotionListener {
String msg = "";
int mouseX=10, mouseY=40;
int movX=0, movY=0;
SampleFrame(String title) {
super(title);
// register this object to receive its own mouse events
addMouseListener(this);
addMouseMotionListener(this);
// create an object to handle window events
MAT SOFT
JAVA REFERENCE GUIDE
276
MyWindowAdapter adapter = new MyWindowAdapter(this);
// register it to receive those events
addWindowListener(adapter);
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me) {
}
// Handle mouse entered.
public void mouseEntered(MouseEvent evtObj) {
// save coordinates
mouseX = 10;
mouseY = 54;
msg = "Mouse just entered child.";
repaint();
}
// Handle mouse exited.
public void mouseExited(MouseEvent evtObj) {
// save coordinates
mouseX = 10;
mouseY = 54;
msg = "Mouse just left child window.";
repaint();
}
// Handle mouse pressed.
public void mousePressed(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Down";
repaint();
}
// Handle mouse released.
public void mouseReleased(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Up";
repaint();
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
movX = me.getX();
movY = me.getY();
msg = "*";
repaint();
}
// Handle mouse moved.
public void mouseMoved(MouseEvent me) {
// save coordinates
movX = me.getX();
movY = me.getY();
repaint(0, 0, 100, 60);
}
public void paint(Graphics g) {
g.drawString(msg, mouseX, mouseY);
g.drawString("Mouse at " + movX + ", " + movY, 10, 40);
}
}
MAT SOFT
JAVA REFERENCE GUIDE
277
class MyWindowAdapter extends WindowAdapter {
SampleFrame sampleFrame;
public MyWindowAdapter(SampleFrame sampleFrame) {
this.sampleFrame = sampleFrame;
}
public void windowClosing(WindowEvent we) {
sampleFrame.setVisible(false);
}
}
// Applet window.
public class WindowEvents extends Applet
implements MouseListener, MouseMotionListener {
SampleFrame f;
String msg = "";
int mouseX=0, mouseY=10;
int movX=0, movY=0;
// Create a frame window.
public void init() {
f = new SampleFrame("Handle Mouse Events");
f.setSize(300, 200);
f.setVisible(true);
// register this object to receive its own mouse events
addMouseListener(this);
addMouseMotionListener(this);
}
// Remove frame window when stopping applet.
public void stop() {
f.setVisible(false);
}
// Show frame window when starting applet.
public void start() {
f.setVisible(true);
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me) {
}
// Handle mouse entered.
public void mouseEntered(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 24;
msg = "Mouse just entered applet window.";
repaint();
}
// Handle mouse exited.
public void mouseExited(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 24;
msg = "Mouse just left applet window.";
repaint();
}
// Handle button pressed.
public void mousePressed(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Down";
repaint();
}
// Handle button released.
MAT SOFT
JAVA REFERENCE GUIDE
278
public void mouseReleased(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Up";
repaint();
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
movX = me.getX();
movY = me.getY();
msg = "*";
repaint();
}
// Handle mouse moved.
public void mouseMoved(MouseEvent me) {
// save coordinates
movX = me.getX();
movY = me.getY();
repaint(0, 0, 100, 20);
}
// Display msg in applet window.
public void paint(Graphics g) {
g.drawString(msg, mouseX, mouseY);
g.drawString("Mouse at " + movX + ", " + movY, 0, 10);
}
}
Sample output from this program is shown here:
Creating a 9indo3ed Program
Although creating applets is a common use for Javas AWT, it is also possible to create stand-
alone AWT-based applications. To do this, simply create an instance of the window or windows
you need inside main, /. For example, the following program creates a frame window that
responds to mouse clicks and keystrokes:
// Create an AWT-based application.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
// Create a frame window.
public class AppWindow extends Frame {
String keymsg = "This is a test.";
String mousemsg = "";
int mouseX=30, mouseY=30;
public AppWindow() {
addKeyListener(new MyKeyAdapter(this));
addMouseListener(new MyMouseAdapter(this));
addWindowListener(new MyWindowAdapter());
}
public void paint(Graphics g) {
g.drawString(keymsg, 10, 40);
g.drawString(mousemsg, mouseX, mouseY);
}
// Create the window.
public static void main(String args[]) {
AppWindow appwin = new AppWindow();
MAT SOFT
JAVA REFERENCE GUIDE
279
appwin.setSize(new Dimension(300, 200));
appwin.setTitle("An AWT-Based Application");
appwin.setVisible(true);
}
}
class MyKeyAdapter extends KeyAdapter {
AppWindow appWindow;
public MyKeyAdapter(AppWindow appWindow) {
this.appWindow = appWindow;
}
public void keyTyped(KeyEvent ke) {
appWindow.keymsg += ke.getKeyChar();
appWindow.repaint();
};
}
class MyMouseAdapter extends MouseAdapter {
AppWindow appWindow;
public MyMouseAdapter(AppWindow appWindow) {
this.appWindow = appWindow;
}
public void mousePressed(MouseEvent me) {
appWindow.mouseX = me.getX();
appWindow.mouseY = me.getY();
appWindow.mousemsg = "Mouse Down at " + appWindow.mouseX +
", " + appWindow.mouseY;
appWindow.repaint();
}
}
class MyWindowAdapter extends WindowAdapter {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
}
Once created, a frame window takes on a life of its own. Notice that main, / ends with the call
to app3in1set*isi"$e,tre/. However, the program keeps running until you close the window.
In essence, when creating a windowed application, you will use main, / to launch its top-level
window. After that, your program will function as a GUI-based application, not like the console-
based programs used earlier.
)isp$aying Information 9ithin a 9indo3
In the most general sense, a window is a container for information. Although we have already
output small amounts of text to a window in the preceding examples, we have not begun to take
advantage of a windows ability to present high-quality text and graphics. Indeed, much of the
power of the AWT comes from its support for these items. For this reason, the remainder of this
chapter discusses Javas text-, graphics-, and font-handling capabilities. As you will see, they are
both powerful and flexible.
9or=ing 3ith ?raphics
The AWT supports a rich assortment of graphics methods. All graphics are drawn relative to a
window. This can be the main window of an applet, a child window of an applet, or astand-alone
application window. The origin of each window is at the top-left corner and is 0,0. Coordinates
are specified in pixels. All output to a window takes place through a graphics context. Agraphics
context is encapsulated by the ?raphics class and is obtained in two ways:
- It is passed to an applet when one of its various methods, such as paint, / or pdate, /,
is called.
MAT SOFT
JAVA REFERENCE GUIDE
280
- It is returned by the get?raphics, / method of Component.
For the sake of convenience the remainder of the examples in this chapter will demonstrate
graphics in the main applet window. However, the same techniques will apply to any other
window.
The ?raphics class defines a number of drawing functions. Each shape can be drawn edge-only
or filled. Objects are drawn and filled in the currently selected graphics color, which is black by
default. When a graphics object is drawn that exceeds the dimensions of the window, output is
automatically clipped. Lets take a look at several of the drawing methods.
)ra3ing 0ines
Lines are drawn by means of the dra30ine, / method, shown here:
void drawLine(int start;, int start<, int end;, int end<)
dra30ine, / displays a line in the current drawing color that begins at start;,start< and ends at
end;,end<.
The following applet draws several lines:
// Draw lines
import java.awt.*;
import java.applet.*;
/*
<applet code="Lines" width=300 height=200>
</applet>
*/
public class Lines extends Applet {
public void paint(Graphics g) {
g.drawLine(0, 0, 100, 100);
g.drawLine(0, 100, 100, 0);
g.drawLine(40, 25, 250, 180);
g.drawLine(75, 90, 400, 400);
g.drawLine(20, 150, 400, 40);
g.drawLine(5, 290, 80, 19);
}
}
)ra3ing 'ectang$es
The dra3'ect, / and fi$$'ect, / methods display an outlined and filled rectangle, respectively.
They are shown here:
void drawRect(int top, int le$t, int 0idth, int height)
void fillRect(int top, int le$t, int 0idth, int height)
The upper-left corner of the rectangle is at top,le$t. The dimensions of the rectangle are specified
by 0idth and height. To draw a rounded rectangle, use dra3'ond'ect, / or
fi$$'ond'ect, /, both shown here:
void drawRoundRect(int top, int le$t, int 0idth, int height, int x6iam, int y6iam)
void fillRoundRect(int top, int le$t, int 0idth, int height, int x6iam, int y6iam)
Arounded rectangle has rounded corners. The upper-left corner of the rectangle is at top,le$t. The
dimensions of the rectangle are specified by 0idth and height. The diameter of the rounding arc
MAT SOFT
JAVA REFERENCE GUIDE
281
along the X axis is specified by x6iam. The diameter of the rounding arc along the Y axis is
specified by y6iam.
The following applet draws several rectangles:
// Draw rectangles
import java.awt.*;
import java.applet.*;
/*
<applet code="Rectangles" width=300 height=200>
</applet>
*/
public class Rectangles extends Applet {
public void paint(Graphics g) {
g.drawRect(10, 10, 60, 50);
g.fillRect(100, 10, 60, 50);
g.drawRoundRect(190, 10, 60, 50, 15, 15);
g.fillRoundRect(70, 90, 140, 100, 30, 40);
}
}
Sample output from this program is shown here:
)ra3ing 7$$ipses and Circ$es
To draw an ellipse, use dra3!va$, /. To fill an ellipse, use fi$$!va$, /. These methods are
shown here:
void drawOval(int top, int le$t, int 0idth, int height)
void fillOval(int top, int le$t, int 0idth, int height)
The ellipse is drawn within a bounding rectangle whose upper-left corner is specified by top,le$t
and whose width and height are specified by 0idth and height. To draw a circle, specify a square
as the bounding rectangle.
The following program draws several ellipses:
// Draw Ellipses
import java.awt.*;
import java.applet.*;
/*
<applet code="Ellipses" width=300 height=200>
</applet>
*/
public class Ellipses extends Applet {
public void paint(Graphics g) {
g.drawOval(10, 10, 50, 50);
g.fillOval(100, 10, 75, 50);
g.drawOval(190, 10, 90, 30);
g.fillOval(70, 90, 140, 100);
}
}
Sample output from this program is shown here:
)ra3ing %rcs
Arcs can be drawn with dra3%rc, / and fi$$%rc, /, shown here:
void drawArc(int top, int le$t, int 0idth, int height, int start-ngle, int s0eep-ngle)
void fillArc(int top, int le$t, int 0idth, int height, int start-ngle, int s0eep-ngle)
MAT SOFT
JAVA REFERENCE GUIDE
282
The arc is bounded by the rectangle whose upper-left corner is specified by top,le$t and whose
width and height are specified by 0idth and height. The arc is drawn from start-ngle through the
angular distance specified by s0eep-ngle. Angles are specified in degrees. Zero degrees is on
the horizontal, at the three oclock position. The arc is drawn counterclockwise if s0eep-ngle is
positive, and clockwise if s0eep-ngle is negative. Therefore, to draw an arc from twelve oclock
to six oclock, the start angle would be 90 and the sweep angle 180. The following applet draws
several arcs:
// Draw Arcs
import java.awt.*;
import java.applet.*;
/*
<applet code="Arcs" width=300 height=200>
</applet>
*/
public class Arcs extends Applet {
public void paint(Graphics g) {
g.drawArc(10, 40, 70, 70, 0, 75);
g.fillArc(100, 40, 70, 70, 0, 75);
g.drawArc(10, 100, 70, 80, 0, 175);
g.fillArc(100, 100, 70, 90, 0, 270);
g.drawArc(200, 80, 80, 80, 0, 180);
}
}
9or=ing 3ith Co$or
Java supports color in a portable, device-independent fashion. The AWT color system allows you
to specify any color you want. It then finds the best match for that color, given the limits of the
display hardware currently executing your program or applet. Thus, your code does not need to
be concerned with the differences in the way color is supported by various hardware devices.
Color is encapsulated by the Co$or class.
Co$or defines several constants (for example, Co$or1"$ac=) to specify a number of common
colors. You can also create your own colors, using one of the color constructors. Three commonly
used forms are shown here:
Color(int red, int green, int blue)
Color(int rgb"alue)
Color(float red, float green, float blue)
The first constructor takes three integers that specify the color as a mix of red, green, and blue.
These values must be between 0 and 255, as in this example:
new Color(255, 100, 100); // light red
The second color constructor takes a single integer that contains the mix of red, green, and blue
packed into an integer. The integer is organized with red in bits 16 to 23, green in bits 8 to 15,
and blue in bits 0 to 7. Here is an example of this constructor:
int newRed = (0xff000000 | (0xc0 << 16) | (0x00 << 8) | 0x00);
Color darkRed = new Color(newRed);
The final constructor, Co$or,f$oat< f$oat< f$oat/, takes three float values (between 0.0 and 1.0)
that specify the relative mix of red, green, and blue. Once you have created a color, you can use
it to set the foreground and/or background color by using the set+oregrond, / and
setBac=grond, / methods. You can also select it as the current drawing color.
MAT SOFT
JAVA REFERENCE GUIDE
283
Co$or Methods
The Co$or class defines several methods that help manipulate colors. They are examined here.
static int HSBtoRGB(float hue, float saturation, float brightness)
static float[ ] RGBtoHSB(int red, int green, int blue, float !alues[ ])
int getRed( )
int getGreen( )
int getBlue( )
int getRGB( )
void setColor(Color ne0Color)
Color getColor( )
% Co$or )emonstration %pp$et
The following applet constructs several colors and draws various objects using these colors:
// Demonstrate color.
import java.awt.*;
import java.applet.*;
/*
<applet code="ColorDemo" width=300 height=200>
</applet>
*/
public class ColorDemo extends Applet {
// draw lines
public void paint(Graphics g) {
Color c1 = new Color(255, 100, 100);
Color c2 = new Color(100, 255, 100);
Color c3 = new Color(100, 100, 255);
g.setColor(c1);
g.drawLine(0, 0, 100, 100);
g.drawLine(0, 100, 100, 0);
g.setColor(c2);
g.drawLine(40, 25, 250, 180);
g.drawLine(75, 90, 400, 400);
g.setColor(c3);
g.drawLine(20, 150, 400, 40);
g.drawLine(5, 290, 80, 19);
g.setColor(Color.red);
g.drawOval(10, 10, 50, 50);
g.fillOval(70, 90, 140, 100);
g.setColor(Color.blue);
g.drawOval(190, 10, 90, 30);
g.drawRect(10, 10, 60, 50);
g.setColor(Color.cyan);
g.fillRect(100, 10, 60, 50);
g.drawRoundRect(190, 10, 60, 50, 15, 15);
}
}
9or=ing 3ith +onts
The AWT supports multiple type fonts. Years ago, fonts emerged from the domain of traditional
typesetting to become an important part of computer-generated documents and displays. The
AWT provides flexibility by abstracting font-manipulation operations and allowing for dynamic
selection of fonts.
MAT SOFT
JAVA REFERENCE GUIDE
284
Fonts have a family name, a logical font name, and a face name. The $amily name is the general
name of the font, such as Courier. The logical name specifies a category of font, such as
Monospaced. The $ace name specifies a specific font, such as Courier Italic. Fonts are
encapsulated by the +ont class.
The +ont class defines these variables:
String name, float pointSize, int size Size, int style
Methods of +onts C$ass
String[ ] getAvailableFontFamilyNames( )
static Font decode(String str)
boolean equals(Object FontObj)
String getFamily( )
static Font getFont(String property)
static Font getFont(String property,Font defaultFont )
String getFontName()
String getName( )
int getSize( )
int getStyle( )
int hashCode( )
boolean isBold( )
boolean isItalic( )
boolean isPlain( )
String toString( )
Font[ ] getAllFonts( )
static GraphicsEnvironment getLocalGraphicsEnvironment( )
Here is an applet that shows how to obtain the names of the available font families:
// Display Fonts
/*
<applet code="ShowFonts" width=550 height=60>
</applet>
*/
import java.applet.*;
import java.awt.*;
public class ShowFonts extends Applet {
public void paint(Graphics g) {
String msg = "";
String FontList[];
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
FontList = ge.getAvailableFontFamilyNames();
for(int i = 0; i < FontList.length; i++)
msg += FontList[i] + " ";
g.drawString(msg, 4, 16);
}
}
MAT SOFT
JAVA REFERENCE GUIDE
285
AWT Controls
Controls are components that allow a user to interact with your application in various ways-for
example, a commonly used control is the push button. A layout manager automatically positions
components within a container. Thus, the appearance of a window is determined by a
combination of the controls that it contains and the layout manager used to position them.
In addition to the controls, a frame window can also include a standard-style menu bar. Each
entry in a menu bar activates a drop-down menu of options from which the user canchoose. A
menu bar is always positioned at the top of a window. Although different inappearance, menu
bars are handled in much the same way as are the other controls. While it is possible to
manually position components within a window, doing so is quite tedious. The layout manager
automates this task. For the first part of this chapter, which introduces the various controls, the
default layout manager will be used. This displays components in a container using left-to-right,
top-to-bottom organization. Once the controls have been covered, the layout managers will be
examined. There you will see how to better manage the positioning of your controls.
Contro$ +ndamenta$s
The AWT supports the following types of controls:
- Labels
- Push buttons
- Check boxes
- Choice lists
- Lists
- Scroll bars
- Text editing
These controls are subclasses of Component.
%dding and 'emoving Contro$s
To include a control in a window, you must add it to the window. To do this, you must first create
an instance of the desired control and then add it to a window by calling add, /, which is defined
by Container. The add, / method has several forms.
The following form is the one that is used for the first part of this chapter:
Component add(Component compObj)
Here, compObj is an instance of the control that you want to add. A reference to compObj is
returned. Once a control has been added, it will automatically be visible whenever its parent
window is displayed. Sometimes you will want to remove a control from a window when the
control is no longer needed. To do this, call remove, /. This method is also defined by
Container. It has this general form:
void remove(Component obj)
Here, obj is a reference to the control you want to remove. You can remove all controls by calling
remove%$$, /.
MAT SOFT
JAVA REFERENCE GUIDE
286
0a"e$s
The easiest control to use is a label. A label is an object of type 0a"e$, and it contains a string,
which it displays. Labels are passive controls that do not support any interaction with the user.
0a"e$ defines the following constructors:
Label( ) throws HeadlessException
Label(String str) throws HeadlessException
Label(String str, int ho0) throws HeadlessException
void setText(String str)
String getText( )
void setAlignment(int ho0)
int getAlignment( )
Here, ho0 must be one of the alignment constants shown earlier. The following example creates
three labels and adds them to an applet window:
// Demonstrate Labels
import java.awt.*;
import java.applet.*;
/*
<applet code="LabelDemo" width=300 height=200>
</applet>
*/
public class LabelDemo extends Applet {
public void init() {
Label one = new Label("One");
Label two = new Label("Two");
Label three = new Label("Three");
// add labels to applet window
add(one);
add(two);
add(three);
}
}
Bsing Bttons
Perhaps the most widely used control is the push button. A push button is a component that
contains a label and that generates an event when it is pressed. Push buttons are objects of type
Btton. Btton defines these two constructors:
Button( ) throws HeadlessException
Button(String str) throws HeadlessException
void setLabel(String str)
String getLabel( )
Here is an example that creates three buttons labeled "Yes, "No, and "Undecided.
Each time one is pressed, a message is displayed that reports which button has been
pressed. In this version, the action command of the button (which, by default, is its label)
is used to determine which button has been pressed. The label is obtained by calling the
get%ctionCommand, / method on the %ction7vent object passed to actionPerformed, /.
MAT SOFT
JAVA REFERENCE GUIDE
287
// Demonstrate Buttons
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="ButtonDemo" width=250 height=150>
</applet>
*/
public class ButtonDemo extends Applet implements ActionListener {
String msg = "";
Button yes, no, maybe;
public void init() {
yes = new Button("Yes");
no = new Button("No");
maybe = new Button("Undecided");
add(yes);
add(no);
add(maybe);
yes.addActionListener(this);
no.addActionListener(this);
maybe.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
String str = ae.getActionCommand();
if(str.equals("Yes")) {
msg = "You pressed Yes.";
}
else if(str.equals("No")) {
msg = "You pressed No.";
}
else {
msg = "You pressed Undecided.";
}
repaint();
}
public void paint(Graphics g) {
g.drawString(msg, 6, 100);
}
}
As mentioned, in addition to comparing button action command strings, you can also determine
which button has been pressed, by comparing the object obtained from the getSorce, /
method to the button objects that you added to the window. To do this, you must keep a list of
the objects when they are added. The following applet shows this approach:
// Recognize Button objects.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="ButtonList" width=250 height=150>
</applet>
*/
public class ButtonList extends Applet implements ActionListener {
String msg = "";
Button bList[] = new Button[3];
public void init() {
MAT SOFT
JAVA REFERENCE GUIDE
288
Button yes = new Button("Yes");
Button no = new Button("No");
Button maybe = new Button("Undecided");
// store references to buttons as added
bList[0] = (Button) add(yes);
bList[1] = (Button) add(no);
bList[2] = (Button) add(maybe);
// register to receive action events
for(int i = 0; i < 3; i++) {
bList[i].addActionListener(this);
}
}
public void actionPerformed(ActionEvent ae) {
for(int i = 0; i < 3; i++) {
if(ae.getSource() == bList[i]) {
msg = "You pressed " + bList[i].getLabel();
}
}
repaint();
}
public void paint(Graphics g) {
g.drawString(msg, 6, 100);
}
}
In this version, the program stores each button reference in an array when the buttons are
added to the applet window. (Recall that the add, / method returns a reference to the button
when it is added.) Inside actionPerformed, /, this array is then used to determine which
button has been pressed.
For simple programs, it is usually easier to recognize buttons by their labels. However, in
situations in which you will be changing the label inside a button during the execution of your
program, or using buttons that have the same label, it may be easier to determine which button
has been pushed by using its object reference. It is also possible to set theaction command
string associated with a button to something other than its label by calling set%ctionCommand,
/. This method changes the action command string, but does not affect the string used to label
the button. Thus, setting the action command enables the action command and the label of a
button to differ.
%pp$ying Chec= Boxes
A chec( box is a control that is used to turn an option on or off. It consists of a small box that
can either contain a check mark or not. There is a label associated with each check box that
describes what option the box represents. You change the state of a check box by clicking on it.
Check boxes can be used individually or as part of a group. Check boxes are objects of the
Chec="ox class. Chec="ox supports these constructors:
Checkbox( ) throws HeadlessException
Checkbox(String str) throws HeadlessException
Checkbox(String str, boolean on) throws HeadlessException
Checkbox(String str, boolean on, CheckboxGroup cb7roup) throws HeadlessException
Checkbox(String str, CheckboxGroup cb7roup, boolean on) throws HeadlessException
boolean getState( )
void setState(boolean on)
String getLabel( )
void setLabel(String str)
MAT SOFT
JAVA REFERENCE GUIDE
289
(and$ing Chec= Boxes
Each time a check box is selected or deselected, an item event is generated. This is sent to any
listeners that previously registered an interest in receiving item event notifications from that
component. Each listener implements the Item0istener interface. That interface defines the
itemStateChanged, / method. An Item7vent object is supplied as the argument to this
method. It contains information about the event (for example, whether it was a selection or
deselection).
The following program creates four check boxes. The initial state of the first box ischecked. The
status of each check box is displayed. Each time you change the state of a check box, the status
display is updated.
// Demonstrate check boxes.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="CheckboxDemo" width=250 height=200>
</applet>
*/
public class CheckboxDemo extends Applet implements ItemListener {
String msg = "";
Checkbox winXP, winVista, solaris, mac;
public void init() {
winXP = new Checkbox("Windows XP", null, true);
winVista = new Checkbox("Windows Vista");
solaris = new Checkbox("Solaris");
mac = new Checkbox("Mac OS");
add(winXP);
add(winVista);
add(solaris);
add(mac);
winXP.addItemListener(this);
winVista.addItemListener(this);
solaris.addItemListener(this);
mac.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie) {
repaint();
}
// Display current state of the check boxes.
public void paint(Graphics g) {
msg = "Current state: ";
g.drawString(msg, 6, 80);
msg = " Windows XP: " + winXP.getState();
g.drawString(msg, 6, 100);
msg = " Windows Vista: " + winVista.getState();
g.drawString(msg, 6, 120);
msg = " Solaris: " + solaris.getState();
g.drawString(msg, 6, 140);
msg = " Mac OS: " + mac.getState();
g.drawString(msg, 6, 160);
}
}
Chec="ox?rop
MAT SOFT
JAVA REFERENCE GUIDE
290
It is possible to create a set of mutually exclusive check boxes in which one and only one check
box in the group can be checked at any one time. These check boxes are often called radio
buttons3 because they act like the station selector on a car radio-only one station can be
selected at any one time. To create a set of mutually exclusive check boxes, you must first define
the group to which they will belong and then specify that group when you construct the check
boxes. Check box groups are objects of type Chec="ox?rop. Only the defaultconstructor is
defined, which creates an empty group.
Checkbox getSelectedCheckbox( )
void setSelectedCheckbox(Checkbox 0hich)
Here is a program that uses check boxes that are part of a group:
// Demonstrate check box group.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="CBGroup" width=250 height=200>
</applet>
*/
public class CBGroup extends Applet implements ItemListener {
String msg = "";
Checkbox winXP, winVista, solaris, mac;
FIGURE 24-2 Sample output from the CheckboxDemo applet
CheckboxGroup cbg;
public void init() {
cbg = new CheckboxGroup();
winXP = new Checkbox("Windows XP", cbg, true);
winVista = new Checkbox("Windows Vista", cbg, false);
solaris = new Checkbox("Solaris", cbg, false);
mac = new Checkbox("Mac OS", cbg, false);
add(winXP);
add(winVista);
add(solaris);
add(mac);
winXP.addItemListener(this);
winVista.addItemListener(this);
solaris.addItemListener(this);
mac.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie) {
repaint();
}
// Display current state of the check boxes.
public void paint(Graphics g) {
msg = "Current selection: ";
msg += cbg.getSelectedCheckbox().getLabel();
g.drawString(msg, 6, 100);
}
}
Output generated by the CB?rop applet is shown in Figure 24-3. Notice that the check
boxes are now circular in shape.
Choice Contro$s
The Choice class is used to create a pop-up list of items from which the user may choose. Thus,
a Choice control is a form of menu. When inactive, a Choice component takes up only enough
MAT SOFT
JAVA REFERENCE GUIDE
291
space to show the currently selected item. When the user clicks on it, the whole list of choices
pops up, and a new selection can be made. Each item in the list is a string that appears as a left-
justified label in the order it is added to the Choice object. Choice only defines the default
constructor, which creates an empty list.
void add(String name)
String getSelectedItem( )
int getSelectedIndex( )
int getItemCount( )
void select(int index)
void select(String name)
String getItem(int index)
(and$ing Choice 0ists
Each time a choice is selected, an item event is generated. This is sent to any listeners that
previously registered an interest in receiving item event notifications from that component. Each
listener implements the Item0istener interface. That interface defines the
itemStateChanged,/ method. An Item7vent object is supplied as the argument to this
method.
Here is an example that creates two Choice menus. One selects the operating system. The other
selects the browser.
// Demonstrate Choice lists.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="ChoiceDemo" width=300 height=180>
</applet>
*/
public class ChoiceDemo extends Applet implements ItemListener {
Choice os, browser;
String msg = "";
public void init() {
os = new Choice();
browser = new Choice();
// add items to os list
os.add("Windows XP");
os.add("Windows Vista");
os.add("Solaris");
os.add("Mac OS");
// add items to browser list
browser.add("Internet Explorer");
browser.add("Firefox");
browser.add("Opera");
// add choice lists to window
add(os);
add(browser);
// register to receive item events
os.addItemListener(this);
browser.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie) {
repaint();
}
// Display current selections.
public void paint(Graphics g) {
MAT SOFT
JAVA REFERENCE GUIDE
292
msg = "Current OS: ";
msg += os.getSelectedItem();
g.drawString(msg, 6, 120);
msg = "Current Browser: ";
msg += browser.getSelectedItem();
g.drawString(msg, 6, 140);
}
}
Bsing 0ists
The 0ist class provides a compact, multiple-choice, scrolling selection list. Unlike the Choice
object, which shows only the single selected item in the menu, a 0ist object can be constructed
to show any number of choices in the visible window. It can also be created to allow multiple
selections. 0ist provides these constructors:
List( ) throws HeadlessException
List(int num.o0s) throws HeadlessException
List(int num.o0s, boolean multiple2elect) throws HeadlessException
void add(String name)
void add(String name, int index)
String getSelectedItem( )
int getSelectedIndex( )
String[ ] getSelectedItems( )
int[ ] getSelectedIndexes( )
int getItemCount( )
void select(int index)
String getItem(int index)
(and$ing 0ists
To process list events, you will need to implement the %ction0istener interface. Each time a
0ist item is double-clicked, an %ction7vent object is generated. Its get%ctionCommand, /
method can be used to retrieve the name of the newly selected item. Also, each time an item is
selected or deselected with a single click, an Item7vent object is generated. Its
getStateChange, / method can be used to determine whether a selection or deselection
triggered this event. getItemSe$ecta"$e, / returns a reference to the object that triggered this
event.
Here is an example that converts the Choice controls in the preceding section into 0ist
components, one multiple choice and the other single choice:
// Demonstrate Lists.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="ListDemo" width=300 height=180>
</applet>
*/
public class ListDemo extends Applet implements ActionListener {
List os, browser;
String msg = "";
public void init() {
os = new List(4, true);
browser = new List(4, false);
// add items to os list
MAT SOFT
JAVA REFERENCE GUIDE
293
os.add("Windows XP");
os.add("Windows Vista");
os.add("Solaris");
os.add("Mac OS");
// add items to browser list
browser.add("Internet Explorer");
browser.add("Firefox");
browser.add("Opera");
browser.select(1);
// add lists to window
add(os);
add(browser);
// register to receive action events
os.addActionListener(this);
browser.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
repaint();
}
// Display current selections.
public void paint(Graphics g) {
int idx[];
msg = "Current OS: ";
idx = os.getSelectedIndexes();
for(int i=0; i<idx.length; i++)
msg += os.getItem(idx[i]) + " ";
g.drawString(msg, 6, 120);
msg = "Current Browser: ";
msg += browser.getSelectedItem();
g.drawString(msg, 6, 140);
}
}
Bsing a Text+ie$d
The Text+ie$d class implements a single-line text-entry area, usually called an edit control. Text
fields allow the user to enter strings and to edit the text using the arrow keys, cut and paste
keys, and mouse selections. Text+ie$d is a subclass of TextComponent. Text+ie$d defines the
following constructors:
TextField( ) throws HeadlessException
TextField(int numChars) throws HeadlessException
TextField(String str) throws HeadlessException
TextField(String str, int numChars) throws HeadlessException
String getText( )
void setText(String str)
String getSelectedText( )
void select(int start5ndex, int end5ndex)
boolean isEditable( )
void setEditable(boolean can=dit)
void setEchoChar(char ch)
boolean echoCharIsSet( )
char getEchoChar( )
(and$ing a Text+ie$d
MAT SOFT
JAVA REFERENCE GUIDE
294
Since text fields perform their own editing functions, your program generally will not respond to
individual key events that occur within a text field. However, you may want to respond when the
user presses ENTER. When this occurs, an action event is generated.
Here is an example that creates the classic user name and password screen:
// Demonstrate text field.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="TextFieldDemo" width=380 height=150>
</applet>
*/
public class TextFieldDemo extends Applet
implements ActionListener {
TextField name, pass;
public void init() {
Label namep = new Label("Name: ", Label.RIGHT);
Label passp = new Label("Password: ", Label.RIGHT);
name = new TextField(12);
pass = new TextField(8);
pass.setEchoChar('?');
add(namep);
add(name);
add(passp);
add(pass);
// register to receive action events
name.addActionListener(this);
pass.addActionListener(this);
}
// User pressed Enter.
public void actionPerformed(ActionEvent ae) {
repaint();
}
public void paint(Graphics g) {
g.drawString("Name: " + name.getText(), 6, 60);
g.drawString("Selected text in name: "
+ name.getSelectedText(), 6, 80);
g.drawString("Password: " + pass.getText(), 6, 100);
}
}
Bsing a Text%rea
Sometimes a single line of text input is not enough for a given task. To handle these situations,
the AWT includes a simple multiline editor called Text%rea. Following are the constructors for
Text%rea:
TextArea( ) throws HeadlessException
TextArea(int numLines, int numChars) throws HeadlessException
TextArea(String str) throws HeadlessException
TextArea(String str, int numLines, int numChars) throws HeadlessException
TextArea(String str, int numLines, int numChars, int sBars) throws HeadlessException
sBars must be one of these values:
SCROLLBARS_BOTH SCROLLBARS_NONE
SCROLLBARS_HORIZONTAL_ONLY SCROLLBARS_VERTICAL_ONLY
MAT SOFT
JAVA REFERENCE GUIDE
295
Text%rea is a subclass of TextComponent. Therefore, it supports the getText, /, setText, /,
getSe$ectedText, /, se$ect, /, is7dita"$e, /, and set7dita"$e, / methods described in the
preceding section.
Text%rea adds the following methods:
void append(String str)
void insert(String str, int index)
void replaceRange(String str, int start5ndex, int end5ndex)
Text areas only generate got-focus and lost-focus events. Normally, your program simply obtains
the current text when it is needed. The following program creates a Text%rea control:
// Demonstrate TextArea.
import java.awt.*;
import java.applet.*;
/*
<applet code="TextAreaDemo" width=300 height=250>
</applet>
*/
public class TextAreaDemo extends Applet {
public void init() {
String val =
"Java SE 6 is the latest version of the most\n" +
"widely-used computer language for Internet programming.\n" +
"Building on a rich heritage, Java has advanced both\n" +
"the art and science of computer language design.\n\n" +
"One of the reasons for Java's ongoing success is its\n" +
"constant, steady rate of evolution. Java has never stood\n" +
"still. Instead, Java has consistently adapted to the\n" +
"rapidly changing landscape of the networked world.\n" +
"Moreover, Java has often led the way, charting the\n" +
"course for others to follow.";
TextArea text = new TextArea(val, 10, 30);
add(text);
}
}
Men Bars and Mens
A menu bar displays a list of top-level menu choices. Each choice is associated with a drop-down
menu. This concept is implemented in the AWT by the following classes: MenBar, Men, and
MenItem. In general, a menu bar contains one or more Men objects. Each Men object
contains a list of MenItem objects. Each MenItem object represents something that can be
selected by the user. Since Men is a subclass of MenItem, a hierarchy of nested submenus
can be created. It is also possible to include checkable menu items. These are menu options of
type Chec="oxMenItem and will have a check mark next to them when they are selected. To
create a menu bar, first create an instance of MenBar. This class only defines the default
constructor. Next, create instances of Men that will define the selections displayed on the bar.
Following are the constructors for Men:
Menu( ) throws HeadlessException
Menu(String option+ame) throws HeadlessException
Menu(String option+ame, boolean remo!able) throws HeadlessException
MenuItem( ) throws HeadlessException
MenuItem(String item+ame) throws HeadlessException
MenuItem(String item+ame, MenuShortcut (ey-ccel) throws HeadlessException
MAT SOFT
JAVA REFERENCE GUIDE
296
void setLabel(String ne0+ame)
String getLabel( )
Chec="oxMenItem. It has these constructors:
CheckboxMenuItem( ) throws HeadlessException
CheckboxMenuItem(String item+ame) throws HeadlessException
CheckboxMenuItem(String item+ame, boolean on) throws HeadlessException
boolean getState( )
void setState(boolean chec(ed)
Menu add(Menu menu)
Object getItem( )
Following is an example that adds a series of nested menus to a pop-up window. The
item selected is displayed in the window. The state of the two check box menu items is also
displayed.
// Illustrate menus.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="MenuDemo" width=250 height=250>
</applet>
*/
// Create a subclass of Frame.
class MenuFrame extends Frame {
String msg = "";
CheckboxMenuItem debug, test;
MenuFrame(String title) {
super(title);
// create menu bar and add it to frame
MenuBar mbar = new MenuBar();
setMenuBar(mbar);
// create the menu items
Menu file = new Menu("File");
MenuItem item1, item2, item3, item4, item5;
file.add(item1 = new MenuItem("New..."));
file.add(item2 = new MenuItem("Open..."));
file.add(item3 = new MenuItem("Close"));
file.add(item4 = new MenuItem("-"));
file.add(item5 = new MenuItem("Quit..."));
mbar.add(file);
Menu edit = new Menu("Edit");
MenuItem item6, item7, item8, item9;
edit.add(item6 = new MenuItem("Cut"));
edit.add(item7 = new MenuItem("Copy"));
edit.add(item8 = new MenuItem("Paste"));
edit.add(item9 = new MenuItem("-"));
Menu sub = new Menu("Special");
MenuItem item10, item11, item12;
sub.add(item10 = new MenuItem("First"));
sub.add(item11 = new MenuItem("Second"));
sub.add(item12 = new MenuItem("Third"));
edit.add(sub);
// these are checkable menu items
debug = new CheckboxMenuItem("Debug");
edit.add(debug);
MAT SOFT
JAVA REFERENCE GUIDE
297
test = new CheckboxMenuItem("Testing");
edit.add(test);
mbar.add(edit);
// create an object to handle action and item events
MyMenuHandler handler = new MyMenuHandler(this);
// register it to receive those events
item1.addActionListener(handler);
item2.addActionListener(handler);
item3.addActionListener(handler);
item4.addActionListener(handler);
item5.addActionListener(handler);
item6.addActionListener(handler);
item7.addActionListener(handler);
item8.addActionListener(handler);
item9.addActionListener(handler);
item10.addActionListener(handler);
item11.addActionListener(handler);
item12.addActionListener(handler);
debug.addItemListener(handler);
test.addItemListener(handler);
// create an object to handle window events
MyWindowAdapter adapter = new MyWindowAdapter(this);
// register it to receive those events
addWindowListener(adapter);
}
public void paint(Graphics g) {
g.drawString(msg, 10, 200);
if(debug.getState())
g.drawString("Debug is on.", 10, 220);
else
g.drawString("Debug is off.", 10, 220);
if(test.getState())
g.drawString("Testing is on.", 10, 240);
else
g.drawString("Testing is off.", 10, 240);
}
}
class MyWindowAdapter extends WindowAdapter {
MenuFrame menuFrame;
public MyWindowAdapter(MenuFrame menuFrame) {
this.menuFrame = menuFrame;
}
public void windowClosing(WindowEvent we) {
menuFrame.setVisible(false);
}
}
class MyMenuHandler implements ActionListener, ItemListener {
MenuFrame menuFrame;
public MyMenuHandler(MenuFrame menuFrame) {
this.menuFrame = menuFrame;
}
// Handle action events.
public void actionPerformed(ActionEvent ae) {
String msg = "You selected ";
String arg = ae.getActionCommand();
if(arg.equals("New..."))
msg += "New.";
else if(arg.equals("Open..."))
msg += "Open.";
else if(arg.equals("Close"))
msg += "Close.";
MAT SOFT
JAVA REFERENCE GUIDE
298
else if(arg.equals("Quit..."))
msg += "Quit.";
else if(arg.equals("Edit"))
msg += "Edit.";
else if(arg.equals("Cut"))
msg += "Cut.";
else if(arg.equals("Copy"))
msg += "Copy.";
else if(arg.equals("Paste"))
msg += "Paste.";
else if(arg.equals("First"))
msg += "First.";
else if(arg.equals("Second"))
msg += "Second.";
else if(arg.equals("Third"))
msg += "Third.";
else if(arg.equals("Debug"))
msg += "Debug.";
else if(arg.equals("Testing"))
msg += "Testing.";
menuFrame.msg = msg;
menuFrame.repaint();
}
// Handle item events.
public void itemStateChanged(ItemEvent ie) {
menuFrame.repaint();
}
}
// Create frame window.
public class MenuDemo extends Applet {
Frame f;
public void init() {
f = new MenuFrame("Menu Demo");
int width = Integer.parseInt(getParameter("width"));
int height = Integer.parseInt(getParameter("height"));
setSize(new Dimension(width, height));
f.setSize(width, height);
f.setVisible(true);
}
public void start() {
f.setVisible(true);
}
public void stop() {
f.setVisible(false);
}
}
)ia$og Boxes
Often, you will want to use a dialog box to hold a set of related controls. Dialog boxes are
primarily used to obtain user input and are often child windows of a top-level window. Dialog
boxes dont have menu bars, but in other respects, they function like frame windows. (You can
add controls to them, for example, in the same way that you add controls to a frame window.)
Dialog boxes may be modal or modeless. When a modal dialog box is active, all input is directed
to it until it is closed. This means that you cannot access other parts of your program until you
have closed the dialog box. When a modeless dialog box is active, input focus can be directed to
another window in your program. Thus, other parts of your program remain active and
accessible. Dialog boxes are of type )ia$og. Two commonly used constructors are shown here:
Dialog(Frame parent*indo0, boolean mode)
MAT SOFT
JAVA REFERENCE GUIDE
299
Dialog(Frame parent*indo0, String title, boolean mode)
// Demonstrate Dialog box.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="DialogDemo" width=250 height=250>
</applet>
*/
// Create a subclass of Dialog.
class SampleDialog extends Dialog implements ActionListener {
SampleDialog(Frame parent, String title) {
super(parent, title, false);
setLayout(new FlowLayout());
setSize(300, 200);
add(new Label("Press this button:"));
Button b;
add(b = new Button("Cancel"));
b.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
dispose();
}
public void paint(Graphics g) {
g.drawString("This is in the dialog box", 10, 70);
}
}
// Create a subclass of Frame.
class MenuFrame extends Frame {
String msg = "";
CheckboxMenuItem debug, test;
MenuFrame(String title) {
super(title);
// create menu bar and add it to frame
MenuBar mbar = new MenuBar();
setMenuBar(mbar);
// create the menu items
Menu file = new Menu("File");
MenuItem item1, item2, item3, item4;
file.add(item1 = new MenuItem("New..."));
file.add(item2 = new MenuItem("Open..."));
file.add(item3 = new MenuItem("Close"));
file.add(new MenuItem("-"));
file.add(item4 = new MenuItem("Quit..."));
mbar.add(file);
Menu edit = new Menu("Edit");
MenuItem item5, item6, item7;
edit.add(item5 = new MenuItem("Cut"));
edit.add(item6 = new MenuItem("Copy"));
edit.add(item7 = new MenuItem("Paste"));
edit.add(new MenuItem("-"));
Menu sub = new Menu("Special", true);
MenuItem item8, item9, item10;
sub.add(item8 = new MenuItem("First"));
sub.add(item9 = new MenuItem("Second"));
sub.add(item10 = new MenuItem("Third"));
edit.add(sub);
// these are checkable menu items
debug = new CheckboxMenuItem("Debug");
edit.add(debug);
MAT SOFT
JAVA REFERENCE GUIDE
300
test = new CheckboxMenuItem("Testing");
edit.add(test);
mbar.add(edit);
// create an object to handle action and item events
MyMenuHandler handler = new MyMenuHandler(this);
// register it to receive those events
item1.addActionListener(handler);
item2.addActionListener(handler);
item3.addActionListener(handler);
item4.addActionListener(handler);
item5.addActionListener(handler);
item6.addActionListener(handler);
item7.addActionListener(handler);
item8.addActionListener(handler);
item9.addActionListener(handler);
item10.addActionListener(handler);
debug.addItemListener(handler);
test.addItemListener(handler);
// create an object to handle window events
MyWindowAdapter adapter = new MyWindowAdapter(this);
// register it to receive those events
addWindowListener(adapter);
}
public void paint(Graphics g) {
g.drawString(msg, 10, 200);
if(debug.getState())
g.drawString("Debug is on.", 10, 220);
else
g.drawString("Debug is off.", 10, 220);
if(test.getState())
g.drawString("Testing is on.", 10, 240);
else
g.drawString("Testing is off.", 10, 240);
}
}
class MyWindowAdapter extends WindowAdapter {
MenuFrame menuFrame;
public MyWindowAdapter(MenuFrame menuFrame) {
this.menuFrame = menuFrame;
}
public void windowClosing(WindowEvent we) {
menuFrame.dispose();
}
}
class MyMenuHandler implements ActionListener, ItemListener {
MenuFrame menuFrame;
public MyMenuHandler(MenuFrame menuFrame) {
this.menuFrame = menuFrame;
}
// Handle action events.
public void actionPerformed(ActionEvent ae) {
String msg = "You selected ";
String arg = ae.getActionCommand();
// Activate a dialog box when New is selected.
if(arg.equals("New...")) {
msg += "New.";
SampleDialog d = new
SampleDialog(menuFrame, "New Dialog Box");
d.setVisible(true);
}
MAT SOFT
JAVA REFERENCE GUIDE
301
// Try defining other dialog boxes for these options.
else if(arg.equals("Open..."))
msg += "Open.";
else if(arg.equals("Close"))
msg += "Close.";
else if(arg.equals("Quit..."))
msg += "Quit.";
else if(arg.equals("Edit"))
msg += "Edit.";
else if(arg.equals("Cut"))
msg += "Cut.";
else if(arg.equals("Copy"))
msg += "Copy.";
else if(arg.equals("Paste"))
msg += "Paste.";
else if(arg.equals("First"))
msg += "First.";
else if(arg.equals("Second"))
msg += "Second.";
else if(arg.equals("Third"))
msg += "Third.";
else if(arg.equals("Debug"))
msg += "Debug.";
else if(arg.equals("Testing"))
msg += "Testing.";
menuFrame.msg = msg;
menuFrame.repaint();
}
public void itemStateChanged(ItemEvent ie) {
menuFrame.repaint();
}
}
// Create frame window.
public class DialogDemo extends Applet {
Frame f;
public void init() {
f = new MenuFrame("Menu Demo");
int width = Integer.parseInt(getParameter("width"));
int height = Integer.parseInt(getParameter("height"));
setSize(width, height);
f.setSize(width, height);
f.setVisible(true);
}
public void start() {
f.setVisible(true);
}
public void stop() {
f.setVisible(false);
}
}
+i$e)ia$og
Java provides a built-in dialog box that lets the user specify a file. To create a file dialog box,
instantiate an object of type +i$e)ia$og. This causes a file dialog box to be displayed. Usually,
this is the standard file dialog box provided by the operating system. Here are three +i$e)ia$og
constructors:
FileDialog(Frame parent)
MAT SOFT
JAVA REFERENCE GUIDE
302
FileDialog(Frame parent, String box+ame)
FileDialog(Frame parent, String box+ame, int ho0)
String getDirectory( )
String getFile( )
/* Demonstrate File Dialog box.
This is an application, not an applet.
*/
import java.awt.*;
import java.awt.event.*;
// Create a subclass of Frame.
class SampleFrame extends Frame {
SampleFrame(String title) {
super(title);
// remove the window when closed
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}
}
// Demonstrate FileDialog.
class FileDialogDemo {
public static void main(String args[]) {
// create a frame that owns the dialog
Frame f = new SampleFrame("File Dialog Demo");
f.setVisible(true);
f.setSize(100, 100);
FileDialog fd = new FileDialog(f, "File Dialog");
fd.setVisible(true);
}
}
)ay 5H: The !rigins of S3ing
Swing did not exist in the early days of Java. Rather, it was a response to deficiencies present in
Javas original GUI subsystem: the Abstract Window Toolkit. The AWT defines a basic set of
controls, windows, and dialog boxes that support a usable, but limited graphical interface. One
reason for the limited nature of the AWT is that it translates its various visual components into
their corresponding, platform-specific equivalents, or peers. This means that the look and feel of
a component is defined by the platform, not by Java. Because the AWT components use native
code resources, they are referred to as hea!y0eight.The use of native peers led to several
problems. First, because of variations between operating systems, a component might look, or
even act, differently on different platforms. This potential variability threatened the overarching
philosophy of Java: write once, run anywhere. Second, the look and feel of each component was
fixed (because it is defined by the platform) and could not be (easily) changed. Third, the use of
heavyweight components caused some frustrating restrictions. For example, a heavyweight
component is always rectangular and opaque.
Not long after Javas original release, it became apparent that the limitations and restrictions
present in the AWT were sufficiently serious that a better approach was needed. The solution was
Swing. Introduced in 1997, Swing was included as part of the Java Foundation Classes (JFC).
Swing was initially available for use with Java 1.1 as a separate library. However, beginning with
Java 1.2, Swing (and the rest of the JFC) was fully integrated into Java.
MAT SOFT
JAVA REFERENCE GUIDE
303
S3ing Is Bi$t on the %9T
Before moving on, it is necessary to make one important point: although Swing eliminates a
number of the limitations inherent in the AWT, Swing does not replace it. Instead, Swing is built
on the foundation of the AWT. This is why the AWT is still a crucial part of Java. Swing also uses
the same event handling mechanism as the AWT. Therefore, a basic understanding of the AWT
and of event handling is required to use Swing.
T3o 6ey S3ing +eatres
As just explained, Swing was created to address the limitations present in the AWT. It does this
through two key features: lightweight components and a pluggable look and feel. Together they
provide an elegant, yet easy-to-use solution to the problems of the AWT. More than anything
else, it is these two features that define the essence of Swing. Each is examined here.
S3ing Components %re 0ight3eight
With very few exceptions, Swing components are light0eight. This means that they are written
entirely in Java and do not map directly to platform-specific peers. Because lightweight
components are rendered using graphics primitives, they can be transparent, which enables
nonrectangular shapes. Thus, lightweight components are more efficient and more flexible.
Furthermore, because lightweight components do not translate into native peers, the look and
feel of each component is determined by Swing, not by the underlying operating system. This
means that each component will work in a consistent manner across all platforms.
S3ing Spports a P$gga"$e 0oo= and +ee$
Swing supports a pluggable loo( and $eel (PLAF). Because each Swing component is rendered by
Java code rather than by native peers, the look and feel of a component is under the control of
Swing. This fact means that it is possible to separate the look and feel of a component from the
logic of the component, and this is what Swing does. Separating out the look and feel provides a
significant advantage: it becomes possible to change the way that a component is rendered
without affecting any of its other aspects. In other words, it is possible to "plug in a new look
and feel for any given component without creating any side effects in the code that uses that
component. Moreover, it becomes possible to define entire sets of look-and-feels that represent
different GUI styles. To use a specific style, its look and feel is simply "plugged in. Once this is
done, all components are automatically rendered using that style.
Pluggable look-and-feels offer several important advantages. It is possible to define a look and
feel that is consistent across all platforms. Conversely, it is possible to create a look and feel that
acts like a specific platform. For example, if you know that an application will be running only in
a Windows environment, it is possible to specify the Windows look and feel. It is also possible to
design a custom look and feel. Finally, the look and feel can be changed dynamically at run time.
Java SE 6 provides look-and-feels, such as metal and Motif, that are available to all Swing users.
The metal look and feel is also called the a!a loo( and $eel. It is platform-independent and
available in all Java execution environments. It is also the default look and feel. Windows
environments also have access to the Windows and Windows Classic look and feel. This book
uses the default Java look and feel (metal) because it is platform independent.
The M*C Connection
In general, a visual component is a composite of three distinct aspects:
- The way that the component looks when rendered on the screen
- The way that the component reacts to the user
- The state information associated with the component
MAT SOFT
JAVA REFERENCE GUIDE
304
No matter what architecture is used to implement a component, it must implicitly contain these
three parts. Over the years, one component architecture has proven itself to be exceptionally
effective: #odel-"ie0-Controller, or MVC for short. The MVC architecture is successful because
each piece of the design corresponds to an aspect of a component. In MVC terminology, the
model corresponds to the state information associated with the component. For example, in the
case of a check box, the model contains a field that indicates if the box is checked or unchecked.
The !ie0 determines how the component is displayed on the screen, including any aspects of the
view that are affected by the current state of the model. The controller determines how the
component reacts to theuser. For example, when the user clicks a check box, the controller
reacts by changing the model to reflect the users choice (checked or unchecked). This then
results in the view being updated. By separating a component into a model, a view, and a
controller, the specific implementation of each can be changed without affecting the other two.
For instance, different view implementations can render the same component in different ways
without affecting the model or the controller.
Although the MVC architecture and the principles behind it are conceptually sound, the high level
of separation between the view and the controller is not beneficial for Swing components.
Instead, Swing uses a modified version of MVC that combines the view and the controller into a
single logical entity called the 85 delegate. For this reason, Swings approach is called either the
#odel-6elegate architecture or the 2eparable #odel architecture. Therefore, although Swings
component architecture is based on MVC, it does not use a classical implementation of it.
Swings pluggable look and feel is made possible by its Model-Delegate architecture. Because the
view (look) and controller (feel) are separate from the model, the look and feel can be changed
without affecting how the component is used within a program. Conversely, it is possible to
customize the model without affecting the way that the component appears on the screen or
responds to user input. To support the Model-Delegate architecture, most Swing components
contain two objects. The first represents the model. The second represents the UI delegate.
Models are defined by interfaces. For example, the model for a button is defined by the
BttonMode$ interface. UI delegates are classes that inherit ComponentBI. For example, the
UI delegate for a button is BttonBI. Normally, your programs will not interact directly with the
UI delegate.
Components and Containers
ASwing GUI consists of two key items: components and containers. However, this distinction is
mostly conceptual because all containers are also components. The difference between the two is
found in their intended purpose: As the term is commonly used, a component is an independent
visual control, such as a push button or slider. A container holds a group of components. Thus, a
container is a special type of component that is designed to hold other components.
Furthermore, in order for a component to be displayed, it must be held within a container. Thus,
all Swing GUIs will have at least one container. Because containers are components, a container
can also hold other containers. This enables Swing to define what is called a containment
hierarchy, at the top of which must be a top-le!el container. Lets look a bit more closely at
components and containers.
Components
In general, Swing components are derived from the JComponent class. (The only exceptions to
this are the four top-level containers, described in the next section.) JComponent provides the
functionality that is common to all components. For example, JComponent supports the
pluggable look and feel. JComponent inherits the AWT classes Container and Component.
Thus, a Swing component is built on and compatible with an AWT component. All of Swings
components are represented by classes defined within the package #avax1s3ing. The following
is list of class names for Swing components (including those used as containers).
MAT SOFT
JAVA REFERENCE GUIDE
305
JApplet, JButton, JCheckBox, JCheckBoxMenuItem, JColorChooser, JComboBox, JComponent,
JDesktopPane, JDialog, JEditorPane, JFileChooser, JFormattedTextField, JFrame, JInternalFrame,
JLabel, JLayeredPane, JList JMenu, JMenuBar, JMenuItem, JOptionPane, JPanel, JPasswordField,
JPopupMenu, JProgressBar, JRadioButton, JRadioButtonMenuItem, JRootPane, JScrollBar, JScrollPane,
JSeparator, JSlider, JSpinner, JSplitPane, JTabbedPane, JTable, JTextArea, JTextField, JTextPane,
JTogglebutton, JToolBar, JToolTip, JTree, JViewport, JWindow
Notice that all component classes begin with the letter J. For example, the class for a label
is J0a"e$; the class for a push button is JBtton; and the class for a scroll bar is JScro$$Bar.
Containers
Swing defines two types of containers. The first are top-level containers: J+rame, J%pp$et,
J9indo3, and J)ia$og. These containers do not inherit JComponent. They do, however,
inherit the AWT classes Component and Container. Unlike Swings other components, which
are lightweight, the top-level containers are heavyweight. This makes the top-level containers a
special case in the Swing component library. As the name implies, a top-level container must be
at the top of a containment hierarchy. A top-level container is not contained within any other
container. Furthermore, every containment hierarchy must begin with a top-level container. The
one most commonly usedfor applications is J+rame. The one used for applets is J%pp$et.
The second type of containers supported by Swing are lightweight containers. Lightweight
containers do inherit JComponent. An example of a lightweight container is JPane$, which is a
general-purpose container. Lightweight containers are often used to organize and manage groups
of related components because a lightweight container can be contained within another
container. Thus, you can use lightweight containers such as JPane$ to create subgroups of
related controls that are contained within an outer container.
The S3ing Pac=ages
Swing is a very large subsystem and makes use of many packages. These are the packages
used by Swing that are defined by Java SE.
javax.swing javax.swing.border javax.swing.colorchooser
javax.swing.event javax.swing.filechooser javax.swing.plaf
javax.swing.plaf.basic javax.swing.plaf.metal javax.swing.plaf.multi
javax.swing.plaf.synth javax.swing.table javax.swing.text
javax.swing.text.html javax.swing.text.html.parser javax.swing.text.rtf
javax.swing.tree javax.swing.undo
The main package is #avax1s3ing. This package must be imported into any program that uses
Swing. It contains the classes that implement the basic Swing components, such as push
buttons, labels, and check boxes.
% Simp$e S3ing %pp$ication
Swing programs differ from both the console-based programs and the AWT-based programs
shown earlier in this book. For example, they use a different set of components and a different
container hierarchy than does the AWT. Swing programs also have special requirements that
relate to threading. The best way to understand the structure of a Swing program is to work
through an example. There are two types of Java programs in which Swing is typically used. The
first is a desktop application. The second is the applet. This section shows how to create a Swing
application. The creation of a Swing applet is described later in this chapter. Although quite short,
the following program shows one way to write a Swing application. In the process, it
demonstrates several key features of Swing. It uses two Swing components:
MAT SOFT
JAVA REFERENCE GUIDE
306
J+rame and J0a"e$. J+rame is the top-level container that is commonly used for Swing
applications. J0a"e$ is the Swing component that creates a label, which is a component that
displays information. The label is Swings simplest component because it is passive. That is, a
label does not respond to user input. It just displays output. The program uses a J+rame
container to hold an instance of a J0a"e$. The label displays a short text message.
// A simple Swing application.
import javax.swing.*;
class SwingDemo {
SwingDemo() {
// Create a new JFrame container.
JFrame jfrm = new JFrame("A Simple Swing Application");
// Give the frame an initial size.
jfrm.setSize(275, 100);
// Terminate the program when the user closes the application.
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create a text-based label.
JLabel jlab = new JLabel(" Swing means powerful GUIs.");
// Add the label to the content pane.
jfrm.add(jlab);
// Display the frame.
jfrm.setVisible(true);
}
public static void main(String args[]) {
// Create the frame on the event dispatching thread.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SwingDemo();
}
});
}
}
Swing programs are compiled and run in the same way as other Java applications. Thus,to
compile this program, you can use this command line:
javac SwingDemo.java
To run the program, use this command line:
java SwingDemo
7vent (and$ing
The preceding example showed the basic form of a Swing program, but it left out one important
part: event handling. Because J0a"e$ does not take input from the user, it does not generate
events, so no event handling was needed. However, the other Swing components do respond to
user input and the events generated by those interactions need to be handled. Events can also
be generated in ways not directly related to user input. For example, anevent is generated when
a timer goes off. Whatever the case, event handling is a large part of any Swing-based
application. The event handling mechanism used by Swing is the same as that used by the AWT.
This approach is called the delegation e!ent model. Swing uses the same events as does the
AWT, and these events are packaged in #ava1a3t1event. Events specific to Swing are stored in
MAT SOFT
JAVA REFERENCE GUIDE
307
#avax1s3ing1event. Although events are handled in Swing in the same way as they are with the
AWT, it is still useful to work through a simple example.
The following program handles the event generated by a Swing push button.
// Handle an event in a Swing program.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class EventDemo {
JLabel jlab;
EventDemo() {
// Create a new JFrame container.
JFrame jfrm = new JFrame("An Event Example");
// Specify FlowLayout for the layout manager.
jfrm.setLayout(new FlowLayout());
// Give the frame an initial size.
jfrm.setSize(220, 90);
// Terminate the program when the user closes the application.
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Make two buttons.
JButton jbtnAlpha = new JButton("Alpha");
JButton jbtnBeta = new JButton("Beta");
// Add action listener for Alpha.
jbtnAlpha.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
jlab.setText("Alpha was pressed.");
}
});
// Add action listener for Beta.
jbtnBeta.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
jlab.setText("Beta was pressed.");
}
});
// Add the buttons to the content pane.
jfrm.add(jbtnAlpha);
jfrm.add(jbtnBeta);
// Create a text-based label.
jlab = new JLabel("Press a button.");
// Add the label to the content pane.
jfrm.add(jlab);
// Display the frame.
jfrm.setVisible(true);
}
public static void main(String args[]) {
// Create the frame on the event dispatching thread.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new EventDemo();
}
});
}
}
MAT SOFT
JAVA REFERENCE GUIDE
308
Create a S3ing %pp$et
The second type of program that commonly uses Swing is the applet. Swing-based applets are
similar to AWT-based applets, but with an important difference: A Swing applet extends J%pp$et
rather than %pp$et. J%pp$et is derived from %pp$et. Thus, J%pp$et includes all of the
functionality found in %pp$et and adds support for Swing. J%pp$et is a top-level Swing container,
which means that it is not derived from JComponent. Because J%pp$et is a top-level container,
it includes the various panes described earlier. This means that all components are added to
J%pp$ets content pane in the same way that components are added to J+rames content pane.
Swing applets use the same four lifecycle methods as Applets: init, /, start, /, stop, /, and
destroy, /. Of course, you need override only those methods that are needed by your applet.
Painting is accomplished differently in Swing than it is in the AWT, and a Swing applet will not
normally override the paint, / method. (Painting in Swing is described later in this chapter.) One
other point: All interaction with components in a Swing applet must take place on the event
dispatching thread, as described in the previous section. This threading issue applies to all Swing
programs.
Here is an example of a Swing applet. It provides the same functionality as the previous
application, but does so in applet form. Figure 29-3 shows the program when executed by
app$etvie3er.
// A simple Swing-based applet
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/*
This HTML can be used to launch the applet:
<object code="MySwingApplet" width=220 height=90>
</object>
*/
public class MySwingApplet extends JApplet {
JButton jbtnAlpha;
JButton jbtnBeta;
JLabel jlab;
// Initialize the applet.
public void init() {
try {
SwingUtilities.invokeAndWait(new Runnable () {
public void run() {
makeGUI(); // initialize the GUI
}
});
} catch(Exception exc) {
System.out.println("Can't create because of "+ exc);
}
}
// This applet does not need to override start(), stop(),
// or destroy().
// Set up and initialize the GUI.
private void makeGUI() {
FIGURE 29-3 Output from the example Swing applet
// Set the applet to use flow layout.
setLayout(new FlowLayout());
// Make two buttons.
jbtnAlpha = new JButton("Alpha");
jbtnBeta = new JButton("Beta");
// Add action listener for Alpha.
jbtnAlpha.addActionListener(new ActionListener() {
MAT SOFT
JAVA REFERENCE GUIDE
309
public void actionPerformed(ActionEvent le) {
jlab.setText("Alpha was pressed.");
}
});
// Add action listener for Beta.
jbtnBeta.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent le) {
jlab.setText("Beta was pressed.");
}
});
// Add the buttons to the content pane.
add(jbtnAlpha);
add(jbtnBeta);
// Create a text-based label.
jlab = new JLabel("Press a button.");
// Add the label to the content pane.
add(jlab);
}
}
Painting in S3ing
Although the Swing component set is quite powerful, you are not limited to using it because
Swing also lets you write directly into the display area of a frame, panel, or one of Swings other
components, such as J0a"e$. Although many (perhaps most) uses of Swing will not involve
drawing directly to the surface of a component, it is available for those applications that need
this capability. To write output directly to the surface of a component, you will use one or more
drawing methods defined by the AWT, such as dra30ine, / or dra3'ect, /.
J0a"e$ and ImageIcon
J0a"e$ is Swings easiest-to-use component. It creates a label and was introduced in the
preceding chapter. Here, we will look at J0a"e$ a bit more closely. J0a"e$ can be used to display
text and/or an icon. It is a passive component in that it does not respond to user input. J0a"e$
defines several constructors. Here are three of them:
JLabel(Icon icon)
JLabel(String str)
JLabel(String str, Icon icon, int align)
ImageIcon(String $ilename)
Icon getIcon( )
String getText( )
void setIcon(Icon icon)
void setText(String str)
The following applet illustrates how to create and display a label containing both an icon and a
string. It begins by creating an ImageIcon object for the file france1gif, which depicts the flag
for France. This is used as the second argument to the J0a"e$ constructor.
The first and last arguments for the J0a"e$ constructor are the label text and the alignment.
Finally, the label is added to the content pane.
// Demonstrate JLabel and ImageIcon.
import java.awt.*;
import javax.swing.*;
/*
<applet code="JLabelDemo" width=250 height=150>
MAT SOFT
JAVA REFERENCE GUIDE
310
</applet>
*/
public class JLabelDemo extends JApplet {
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
// Create an icon.
ImageIcon ii = new ImageIcon("france.gif");
// Create a label.
JLabel jl = new JLabel("France", ii, JLabel.CENTER);
// Add the label to the content pane.
add(jl);
}
}
JText+ie$d
JText+ie$d is the simplest Swing text component. It is also probably its most widely used text
component. JText+ie$d allows you to edit one line of text. It is derived from JTextComponent,
which provides the basic functionality common to Swing text components. JText+ie$d uses the
)ocment interface for its model.
Three of JText+ie$ds constructors are shown here:
JTextField(int cols)
JTextField(String str, int cols)
JTextField(String str)
The following example illustrates JText+ie$d. It creates a JText+ie$d and adds it to the content
pane. When the user presses ENTER, an action event is generated. This is handled by displaying
the text in the status window.
// Demonstrate JTextField.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JTextFieldDemo" width=300 height=50>
</applet>
*/
public class JTextFieldDemo extends JApplet {
JTextField jtf;
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
MAT SOFT
JAVA REFERENCE GUIDE
311
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());
// Add text field to content pane.
jtf = new JTextField(15);
add(jtf);
jtf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
// Show text when user presses ENTER.
showStatus(jtf.getText());
}
});
}
}
The S3ing Bttons
Swing defines four types of buttons: JBtton, JTogg$eBtton, JChec=Box, and
J'adioBtton.
All are subclasses of the %"stractBtton class, which extends JComponent. Thus, all buttons
share a set of common traits. %"stractBtton contains many methods that allow you to control
the behavior of buttons. For example, you can define different icons that are displayed for the
button when it is disabled, pressed, or selected. Another icon can be used as a rollo!er icon,
which is displayed when the mouse is positioned over a button. The following methods set these
icons:
void setDisabledIcon(Icon di)
void setPressedIcon(Icon pi)
void setSelectedIcon(Icon si)
void setRolloverIcon(Icon ri)
The text associated with a button can be read and written via the following methods:
String getText( )
void setText(String str)
JBtton
The JBtton class provides the functionality of a push button. You have already seen a simple
form of it in the preceding chapter. JBtton allows an icon, a string, or both to be associated
with the push button. Three of its constructors are shown here:
JButton(Icon icon)
JButton(String str)
JButton(String str, Icon icon)
String getActionCommand( )
MAT SOFT
JAVA REFERENCE GUIDE
312
The following demonstrates an icon-based button. It displays four push buttons and a label. Each
button displays an icon that represents the flag of a country. When a button is pressed, the name
of that country is displayed in the label.
// Demonstrate an icon-based JButton.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JButtonDemo" width=250 height=450>
</applet>
*/
public class JButtonDemo extends JApplet
implements ActionListener {
JLabel jlab;
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());
// Add buttons to content pane.
ImageIcon france = new ImageIcon("france.gif");
JButton jb = new JButton(france);
jb.setActionCommand("France");
jb.addActionListener(this);
add(jb);
ImageIcon germany = new ImageIcon("germany.gif");
jb = new JButton(germany);
jb.setActionCommand("Germany");
jb.addActionListener(this);
add(jb);
ImageIcon italy = new ImageIcon("italy.gif");
jb = new JButton(italy);
jb.setActionCommand("Italy");
jb.addActionListener(this);
add(jb);
ImageIcon japan = new ImageIcon("japan.gif");
jb = new JButton(japan);
jb.setActionCommand("Japan");
jb.addActionListener(this);
add(jb);
// Create and add the label to content pane.
jlab = new JLabel("Choose a Flag");
add(jlab);
}
// Handle button events.
public void actionPerformed(ActionEvent ae) {
jlab.setText("You selected " + ae.getActionCommand());
}
}
MAT SOFT
JAVA REFERENCE GUIDE
313
JTogg$eBtton
A useful variation on the push button is called a toggle button. A toggle button looks just like a
push button, but it acts differently because it has two states: pushed and released. That is, when
you press a toggle button, it stays pressed rather than popping back up as a regular push button
does. When you press the toggle button a second time, it releases (pops up). Therefore, each
time a toggle button is pushed, it toggles between its two states.
JTogg$eBtton defines several constructors. The one used by the example in this section is
shown here:
JToggleButton(String str)
Object getItem( )
boolean isSelected( )
Here is an example that uses a toggle button. Notice how the item listener works. It simply calls
isSe$ected, / to determine the buttons state.
// Demonstrate JToggleButton.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JToggleButtonDemo" width=200 height=80>
</applet>
*/
public class JToggleButtonDemo extends JApplet {
JLabel jlab;
JToggleButton jtbn;
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());
// Create a label.
jlab = new JLabel("Button is off.");
// Make a toggle button.
jtbn = new JToggleButton("On/Off");
// Add an item listener for the toggle button.
jtbn.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ie) {
if(jtbn.isSelected())
jlab.setText("Button is on.");
else
jlab.setText("Button is off.");
MAT SOFT
JAVA REFERENCE GUIDE
314
}
});
// Add the toggle button and label to the content pane.
add(jtbn);
add(jlab);
}
}
Chec= Boxes
The JChec=Box class provides the functionality of a check box. Its immediate superclass is
JTogg$eBtton, which provides support for two-state buttons, as just described. JChec=Box
defines several constructors. The one used here is
JCheckBox(String str)
When the user selects or deselects a check box, an Item7vent is generated. You can obtain a
reference to the JChec=Box that generated the event by calling getItem, / on the Item7vent
passed to the itemStateChanged, / method defined by Item0istener. The easiest way to
determine the selected state of a check box is to call isSe$ected, / on the JChec=Box instance.
In addition to supporting the normal check box operation, JChec=Box lets you specify the icons
that indicate when a check box is selected, cleared, and rolled-over. We wont be using this
capability here, but it is available for use in your own programs.
The following example illustrates check boxes.
// Demonstrate JCheckbox.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JCheckBoxDemo" width=270 height=50>
</applet>
*/
public class JCheckBoxDemo extends JApplet
implements ItemListener {
JLabel jlab;
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());
// Add check boxes to the content pane.
JCheckBox cb = new JCheckBox("C");
cb.addItemListener(this);
add(cb);
cb = new JCheckBox("C++");
cb.addItemListener(this);
MAT SOFT
JAVA REFERENCE GUIDE
315
add(cb);
cb = new JCheckBox("Java");
cb.addItemListener(this);
add(cb);
cb = new JCheckBox("Perl");
cb.addItemListener(this);
add(cb);
// Create the label and add it to the content pane.
jlab = new JLabel("Select languages");
add(jlab);
}
// Handle item events for the check boxes.
public void itemStateChanged(ItemEvent ie) {
JCheckBox cb = (JCheckBox)ie.getItem();
if(cb.isSelected())
jlab.setText(cb.getText() + " is selected");
else
jlab.setText(cb.getText() + " is cleared");
}
}
'adio Bttons
Radio buttons are a group of mutually exclusive buttons, in which only one button can be
selected at any one time. They are supported by the J'adioBtton class, which extends
JTogg$eBtton.J'adioBtton provides several constructors. The one used in the example is
shown here:
JRadioButton(String str)
void add(AbstractButton ab)
// Demonstrate JRadioButton
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JRadioButtonDemo" width=300 height=50>
</applet>
*/
public class JRadioButtonDemo extends JApplet
implements ActionListener {
JLabel jlab;
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());
// Create radio buttons and add them to content pane.
MAT SOFT
JAVA REFERENCE GUIDE
316
JRadioButton b1 = new JRadioButton("A");
b1.addActionListener(this);
add(b1);
JRadioButton b2 = new JRadioButton("B");
b2.addActionListener(this);
add(b2);
JRadioButton b3 = new JRadioButton("C");
b3.addActionListener(this);
add(b3);
// Define a button group.
ButtonGroup bg = new ButtonGroup();
bg.add(b1);
bg.add(b2);
bg.add(b3);
// Create a label and add it to the content pane.
jlab = new JLabel("Select One");
add(jlab);
}
// Handle button selection.
public void actionPerformed(ActionEvent ae) {
jlab.setText("You selected " + ae.getActionCommand());
}
}
JTa""edPane
JTa""edPane encapsulates a tabbed pane. It manages a set of components by linking them
with tabs. Selecting a tab causes the component associated with that tab to come to the
forefront. Tabbed panes are very common in the modern GUI, and you have no doubt used them
many times. Given the complex nature of a tabbed pane, they are surprisingly easy to create
and use.
JTa""edPane defines three constructors. We will use its default constructor, which
creates an empty control with the tabs positioned across the top of the pane. The other two
constructors let you specify the location of the tabs, which can be along any of the four
sides. JTa""edPane uses the Sing$eSe$ectionMode$ model.
Tabs are added by calling addTa", /. Here is one of its forms:
void addTab(String name, Component comp)
The general procedure to use a tabbed pane is outlined here:
1. Create an instance of JTa""edPane.
2. Add each tab by calling addTa", /.
3. Add the tabbed pane to the content pane.
The following example illustrates a tabbed pane. The first tab is titled "Cities and contains four
buttons. Each button displays the name of a city. The second tab is titled "Colors and contains
three check boxes. Each check box displays the name of a color. The third tab is titled "Flavors
and contains one combo box. This enables the user to select one of three flavors.
// Demonstrate JTabbedPane.
import javax.swing.*;
/*
<applet code="JTabbedPaneDemo" width=400 height=100>
</applet>
*/
public class JTabbedPaneDemo extends JApplet {
public void init() {
try {
MAT SOFT
JAVA REFERENCE GUIDE
317
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
JTabbedPane jtp = new JTabbedPane();
jtp.addTab("Cities", new CitiesPanel());
jtp.addTab("Colors", new ColorsPanel());
jtp.addTab("Flavors", new FlavorsPanel());
add(jtp);
}
}
// Make the panels that will be added to the tabbed pane.
class CitiesPanel extends JPanel {
public CitiesPanel() {
JButton b1 = new JButton("New York");
add(b1);
JButton b2 = new JButton("London");
add(b2);
JButton b3 = new JButton("Hong Kong");
add(b3);
JButton b4 = new JButton("Tokyo");
add(b4);
}
}
class ColorsPanel extends JPanel {
public ColorsPanel() {
JCheckBox cb1 = new JCheckBox("Red");
add(cb1);
JCheckBox cb2 = new JCheckBox("Green");
add(cb2);
JCheckBox cb3 = new JCheckBox("Blue");
add(cb3);
}
}
class FlavorsPanel extends JPanel {
public FlavorsPanel() {
JComboBox jcb = new JComboBox();
jcb.addItem("Vanilla");
jcb.addItem("Chocolate");
jcb.addItem("Strawberry");
add(jcb);
}
}
JScro$$Pane
MAT SOFT
JAVA REFERENCE GUIDE
318
JScro$$Pane is a lightweight container that automatically handles the scrolling of nother
component. The component being scrolled can either be an individual component, such as a
table, or a group of components contained within another lightweight container, such as a
JPane$. In either case, if the object being scrolled is larger than the viewable area, horizontal
and/or vertical scroll bars are automatically provided, and the component can be scrolled
through the pane. Because JScro$$Pane automates scrolling, it usually eliminates the need to
manage individual scroll bars. The viewable area of a scroll pane is called the !ie0port. It is a
window in which the component being scrolled is displayed. Thus, the viewport displays the
visible portion of the component being scrolled. The scroll bars scroll the component through the
viewport. In its default behavior, a JScro$$Pane will dynamically add or remove a scroll bar as
needed. For example, if the component is taller than the viewport, a vertical scroll bar is added.
If the component will completely fit within the viewport, the scroll bars are removed.
JScro$$Pane defines several constructors. The one used in this chapter is shown here:
JScrollPane(Component comp)
Here are the steps to follow to use a scroll pane:
1. Create the component to be scrolled.
2. Create an instance of JScro$$Pane, passing to it the object to scroll.
3. Add the scroll pane to the content pane.
The following example illustrates a scroll pane. First, a JPane$ object is created, and 400 buttons
are added to it, arranged into 20 columns. This panel is then added to a scroll pane, and the
scroll pane is added to the content pane. Because the panel is larger than the viewport, vertical
and horizontal scroll bars appear automatically. You can use the scroll bars to scroll the buttons
into view.
// Demonstrate JScrollPane.
import java.awt.*;
import javax.swing.*;
/*
<applet code="JScrollPaneDemo" width=300 height=250>
</applet>
*/
public class JScrollPaneDemo extends JApplet {
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
// Add 400 buttons to a panel.
JPanel jp = new JPanel();
jp.setLayout(new GridLayout(20, 20));
int b = 0;
for(int i = 0; i < 20; i++) {
for(int j = 0; j < 20; j++) {
jp.add(new JButton("Button " + b));
++b;
MAT SOFT
JAVA REFERENCE GUIDE
319
}
}
// Create the scroll pane.
JScrollPane jsp = new JScrollPane(jp);
// Add the scroll pane to the content pane.
// Because the default border layout is used,
// the scroll pane will be added to the center.
add(jsp, BorderLayout.CENTER);
}
}
J0ist
In Swing, the basic list class is called J0ist. It supports the selection of one or more items from a
list. Although the list often consists of strings, it is possible to create a list of just about any
object that can be displayed. J0ist is so widely used in Java that it is highly unlikely that you
have not seen one before.
J0ist provides several constructors. The one used here is
JList(Object[ ] items)
void valueChanged(ListSelectionEvent le)
void setSelectionMode(int mode)
0istSe$ectionMode$:
SINGLE_SELECTION
SINGLE_INTERVAL_SELECTION
MULTIPLE_INTERVAL_SELECTION
int getSelectedIndex( )
Object getSelectedValue( )
The following applet demonstrates a simple J0ist, which holds a list of cities. Each time
a city is selected in the list, a 0istSe$ection7vent is generated, which is handled by the
va$eChanged, / method defined by 0istSe$ection0istener. It responds by obtaining the
index of the selected item and displaying the name of the selected city in a label.
// Demonstrate JList.
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="JListDemo" width=200 height=120>
</applet>
*/
public class JListDemo extends JApplet {
JList jlst;
JLabel jlab;
JScrollPane jscrlp;
// Create an array of cities.
String Cities[] = { "New York", "Chicago", "Houston",
"Denver", "Los Angeles", "Seattle",
"London", "Paris", "New Delhi",
"Hong Kong", "Tokyo", "Sydney" };
MAT SOFT
JAVA REFERENCE GUIDE
320
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());
// Create a JList.
jlst = new JList(Cities);
// Set the list selection mode to single selection.
jlst.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
// Add the list to a scroll pane.
jscrlp = new JScrollPane(jlst);
// Set the preferred size of the scroll pane.
jscrlp.setPreferredSize(new Dimension(120, 90));
// Make a label that displays the selection.
jlab = new JLabel("Choose a City");
// Add selection listener for the list.
jlst.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent le) {
// Get the index of the changed item.
int idx = jlst.getSelectedIndex();
// Display selection, if item was selected.
if(idx != -1)
jlab.setText("Current selection: " + Cities[idx]);
else // Otherwise, reprompt.
jlab.setText("Choose a City");
}
});
// Add the list and label to the content pane.
add(jscrlp);
add(jlab);
}
}
JCom"oBox
Swing provides a combo box (a combination of a text field and a drop-down list) through the
JCom"oBox class. A combo box normally displays one entry, but it will also display a drop-down
list that allows a user to select a different entry. You can also create a combo box that lets the
user enter a selection into the text field.
The JCom"oBox constructor used by the example is shown here:
JComboBox(Object[ ] items)
MAT SOFT
JAVA REFERENCE GUIDE
321
Object getSelectedItem( )
The following example demonstrates the combo box. The combo box contains entries
for "France, "Germany, "Italy, and "Japan. When a country is selected, an icon-based
label is updated to display the flag for that country. You can see how little code is required
to use this powerful component.
// Demonstrate JComboBox.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JComboBoxDemo" width=300 height=100>
</applet>
*/
public class JComboBoxDemo extends JApplet {
JLabel jlab;
ImageIcon france, germany, italy, japan;
JComboBox jcb;
String flags[] = { "France", "Germany", "Italy", "Japan" };
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());
// Instantiate a combo box and add it to the content pane.
jcb = new JComboBox(flags);
add(jcb);
// Handle selections.
jcb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String s = (String) jcb.getSelectedItem();
jlab.setIcon(new ImageIcon(s + ".gif"));
}
});
// Create a label and add it to the content pane.
jlab = new JLabel(new ImageIcon("france.gif"));
add(jlab);
}
}
MAT SOFT
JAVA REFERENCE GUIDE
322
)ay EI: %dvanced S3ing Contro$s
Trees
A tree is a component that presents a hierarchical view of data. The user has the ability to
expand or collapse individual subtrees in this display. Trees are implemented in Swing by the
JTree class. A sampling of its constructors is shown here:
JTree(Object obj[ ])
JTree(Vector<?> !)
JTree(TreeNode tn)
TreePath getPath( )
DefaultMutableTreeNode(Object obj)
void add(MutableTreeNode child)
JTree does not provide any scrolling capabilities of its own. Instead, a JTree is typically placed
within a JScro$$Pane. This way, a large tree can be scrolled through a smaller viewport. Here
are the steps to follow to use a tree:
1. Create an instance of JTree.
2. Create a JScro$$Pane and specify the tree as the object to be scrolled.
3. Add the tree to the scroll pane.
4. Add the scroll pane to the content pane.
The following example illustrates how to create a tree and handle selections. The program
creates a )efa$tMta"$eTreeNode instance labeled "Options. This is the top node of the tree
hierarchy. Additional tree nodes are then created, and the add, / method is called to connect
these nodes to the tree. A reference to the top node in the tree is provided as the argument to
the JTree constructor. The tree is then provided as the argument to the JScro$$Pane
constructor. This scroll pane is then added to the content pane. Next, a label is created and
added to the content pane. The tree selection is displayed in this label. To receive selection
events from the tree, a TreeSe$ection0istener is registered for the tree. Inside the
va$eChanged, / method, the path to the current selection is obtained and displayed.
// Demonstrate JTree.
import java.awt.*;
import javax.swing.event.*;
import javax.swing.*;
import javax.swing.tree.*;
/*
<applet code="JTreeDemo" width=400 height=200>
</applet>
*/
public class JTreeDemo extends JApplet {
JTree tree;
JLabel jlab;
public void init() {
try {
MAT SOFT
JAVA REFERENCE GUIDE
323
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
// Create top node of tree.
DefaultMutableTreeNode top = new DefaultMutableTreeNode("Options");
// Create subtree of "A".
DefaultMutableTreeNode a = new DefaultMutableTreeNode("A");
top.add(a);
DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("A1");
a.add(a1);
DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("A2");
a.add(a2);
// Create subtree of "B".
DefaultMutableTreeNode b = new DefaultMutableTreeNode("B");
top.add(b);
DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("B1");
b.add(b1);
DefaultMutableTreeNode b2 = new DefaultMutableTreeNode("B2");
b.add(b2);
DefaultMutableTreeNode b3 = new DefaultMutableTreeNode("B3");
b.add(b3);
// Create the tree.
tree = new JTree(top);
// Add the tree to a scroll pane.
JScrollPane jsp = new JScrollPane(tree);
// Add the scroll pane to the content pane.
add(jsp);
// Add the label to the content pane.
jlab = new JLabel();
add(jlab, BorderLayout.SOUTH);
// Handle tree selection events.
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent tse) {
jlab.setText("Selection is " + tse.getPath());
}
});
}
}
JTa"$e
JTa"$e is a component that displays rows and columns of data. It is perhaps Swings most
complicated component. However, in its default configuration, JTa"$e still offers substantial
functionality that is easy to use-especially if you simply want to use the table to present data in
a tabular format. The brief overview presented here will give you a general understanding of this
powerful component. Like JTree, JTa"$e has many classes and interfaces associated with it.
These are packaged in #avax1s3ing1ta"$e. At its core, JTa"$e is conceptually simple. It is a
component that consists of one or more columns of information. At the top of each column is a
heading. In addition to describing the data in a column, the heading also provides the
mechanism by which the user can change the size of a column or change the location of a
MAT SOFT
JAVA REFERENCE GUIDE
324
column within the table. JTa"$e does not provide any scrolling capabilities of its own. Instead,
you will normally wrap a JTa"$e inside a JScro$$Pane.
JTa"$e supplies several constructors. The one used here is
JTable(Object data[ ][ ], Object col)eads[ ])
Here are the steps required to set up a simple JTa"$e that can be used to display data:
1. Create an instance of JTa"$e.
2. Create a JScro$$Pane object, specifying the table as the object to scroll.
3. Add the table to the scroll pane.
4. Add the scroll pane to the content pane.
The following example illustrates how to create and use a simple table. Aone-dimensional array
of strings called co$(eads is created for the column headings. Atwo-dimensional array of strings
called data is created for the table cells. You can see that each element in the array is an array
of three strings. These arrays are passed to the JTa"$e constructor. The table is added to a scroll
pane, and then the scroll pane is added to the content pane. The table displays the data in the
data array. The default table configuration also allows the contents of a cell to be edited.
Changes affect the underlying array, which is data in this case.
// Demonstrate JTable.
import java.awt.*;
import javax.swing.*;
/*
<applet code="JTableDemo" width=400 height=200>
</applet>
*/
public class JTableDemo extends JApplet {
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}});
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
// Initialize column headings.
String[] colHeads = { "Name", "Extension", "ID#" };
// Initialize data.
Object[][] data = {{ "Gail", "4567", "865" },
{ "Ken", "7566", "555" },
{ "Viviane", "5634", "587" },
{ "Melanie", "7345", "922" },
{ "Anne", "1237", "333" },
{ "John", "5656", "314" },
{ "Matt", "5672", "217" },
{ "Claire", "6741", "444" },
{ "Erwin", "9023", "519" },
{ "Ellen", "1134", "532" },
{ "Jennifer", "5689", "112" },
{ "Ed", "9030", "133" },
{ "Helen", "6751", "145" }};
// Create the table.
MAT SOFT
JAVA REFERENCE GUIDE
325
JTable table = new JTable(data, colHeads);
JScrollPane jsp = new JScrollPane(table);
add(jsp);
}
}
)ay E4: SJ0 Basics
Before proceeding to JDBC coding, it would be nice to learn some basics about SQL and Database
Installation settings to work with:
SQL SYNTAX
Structured Juery 0anguage (SQL) is a standardized language that allows you to perform
operations on a database, such as creating entries, reading content, updating content, and
deleting entries.
SQL is supported by all most any database you will likely use, and it allows you to write
database code independently of the underlying database.
This material gives an overview of SQL, which is a pre-requisite to understand JDBC concepts.
This material gives you enough SQL to be able to Create, Read, Update, and Delete (often
referred to as CRUD operations) data from a database.
Create Database:
The CREATE DATABASE statement is used for creating a new database. The syntax is:
%X1. ,730T3 40T0L0%3 40T0L0%3T=0M3*
Example:
The following SQL statement creates a Database named EMP:
%X1. ,730T3 40T0L0%3 3MP*
Drop Database:
The DROP DATABASE statement is used for deleting an existing database. The syntax is:
%X1. 47?P 40T0L0%3 40T0L0%3T=0M3*
Note: To create or drop a database you should have administrator privilege on your database
server. Be careful, deleting a database would loss all the data stored in database.
Create Table:
MAT SOFT
JAVA REFERENCE GUIDE
326
The CREATE TABLE statement is used for creating a new table. The syntax is:
%X1. ,730T3 T0L13 tabl!Tnam!
$
columnTnam! columnT#ataTtyp!2
columnTnam! columnT#ataTtyp!2
columnTnam! columnT#ataTtyp!
...
(*
Example:
The following SQL statement creates a table named Employees with four columns:
%X1. ,730T3 T0L13 3mploy!!s
$
i# 6=T =?T =5112
ag! 6=T =?T =5112
first B07,07$@HH(2
last B07,07$@HH(2
P76M07A Y3A $ i# (
(*
Drop Table:
The DROP TABLE statement is used for deleting an existing table. The syntax is:
%X1. 47?P T0L13 tabl!Tnam!*
Example:
The following SQL statement deletes a table named Employees:
%X1. 47?P T0L13 3mploy!!s*
INSERT Data:
The syntax for INSERT looks similar to the following, where column1, column2, and so on
represent the new data to appear in the respective columns:
%X1. 6=%37T 6=T? tabl!Tnam! B0153% $columnC2 column@2 ...(*
Example:
The following SQL INSERT statement inserts a new row in the Employees database created
earlier:
MAT SOFT
JAVA REFERENCE GUIDE
327
%X1. 6=%37T 6=T? 3mploy!!s B0153% $CEE2 CJ2 'Vara'2 '0li'(*
SELECT Data:
The SELECT statement is used to retrieve data from a database. The syntax for SELECT is:
%X1. %313,T columnTnam!2 columnTnam!2 ...
F7?M tabl!Tnam!
"373 con#itions*
The WHERE clause can use the comparison operators such as =, !=, <, >, <=,and >=, as well
as the BETWEEN and LIKE operators.
Example:
The following SQL statement selects the age, first and last columns from the Employees table
where id column is 100:
%X1. %313,T first2 last2 ag!
F7?M 3mploy!!s
"373 i# 9 CEE*
The following SQL statement selects the age, first and last columns from the Employees table
where $irst column contains >ara:
%X1. %313,T first2 last2 ag!
F7?M 3mploy!!s
"373 first 16Y3 'WVaraW'*
UPDATE Data:
The UPDATE statement is used to update data. The syntax for UPDATE is:
%X1. 5P40T3 tabl!Tnam!
%3T columnTnam! 9 valu!2 columnTnam! 9 valu!2 ...
"373 con#itions*
The WHERE clause can use the comparison operators such as =, !=, <, >, <=,and >=, as well
as the BETWEEN and LIKE operators.
Example:
The following SQL UPDATE statement changes the age column of the employee whose id is
100:
%X1. 5P40T3 3mploy!!s %3T ag!9@E "373 i#9CEE*
MAT SOFT
JAVA REFERENCE GUIDE
328
DELETE Data:
The DELETE statement is used to delete data from tables. The syntax for DELETE is:
%X1. 4313T3 F7?M tabl!Tnam! "373 con#itions*
The WHERE clause can use the comparison operators such as =, !=, <, >, <=,and >=, as well
as the BETWEEN and LIKE operators.
Example:
The following SQL DELETE statement delete the record of the employee whose id is 100:
%X1. 4313T3 F7?M 3mploy!!s "373 i#9CEE*
CREATING THE ENVIRONMENT
Install Database:
The most important thing you will need, of course is an actual running database with a table that you
can query and modify.
Install a database that is most suitable for you. You can have plenty of choices and most common are:
1. MySJ0 )B: MySQL is an open source database. You can download it from MySQL Official Site.
We recommend downloading the full Windows installation.
In addition, download and install MySQL Administrator as well as MySQL Query Browser.These
are GUI based tools that will make your development much easier.
Finally, download and unzip MySQL Connector/J (the MySQL JDBC driver) in a convenient
directory. For the purpose of this material we will assume that you have installed the driver at
C:\Program Files\MySQL\mysql-connector-java-5.1.8.
Accordingly set CLASSPATH variable to C:\Program Files\MySQL\mysql-connector-java-
5.1.8\mysql-connector-java-5.1.8-bin.jar. Your driver version may vary based on your
installation.
2. PostgreSJ0 )B: PostgreSQL is an open source database. You can download it
fromPostgreSQL Official Site.
The Postgres installation contains a GUI based administrative tool called pgAdmin III. JDBC
drivers are also included as part of the installation.
3. !rac$e )B: Oracle DB is an commercial database sold by Oracle . We assume that you have
the necessary distribution media to install it.
Oracle installation includes a GUI based administrative tool called Enterprise Manager. JDBC
drivers are also included as part of the installation.
MAT SOFT
JAVA REFERENCE GUIDE
329
Install Database Drivers:
The latest JDK includes a JDBC-ODBC Bridge driver that makes most Open Database Connectivity
(ODBC) drivers available to programmers using the JDBC API.
Now a days most of the Database vendors are supplying appropriate JDBC drivers along with Database
installation. So you should not worry about this part.
Set Database Credential:
For this material we are going to use MySQL database. When you install any of the above database, its
administrator ID is set to root and gives provision to set a password of your choice.
Using root ID and password you can either create another users ID and password or you can use root
ID and password for your JDBC application.
There are various database operations like database creation and deletion, which would need
administrator ID and password.
For rest of the JDBC material we would use MySQL Database with sername as ID andpass3ord as
password.
If you do not have sufficient privilege to create new users then you can ask your Database
Administrator (DBA) to create a user ID and password for you.
Create Database:
To create the 7MP database, use the following steps:
Step 1:
Open a Command Prompt and change to the installation directory as follows:
,-O.
,-O.c# Program Fil!sOMy%X1Obin
,-OProgram Fil!sOMy%X1Obin.
Note: The path to mys;$d1exe may vary depending on the install location of MySQL on your system.
You can also check documentation on how to start and stop your database server.
Step 2:
Start the database server by executing the following command, if it is already not running.
,-OProgram Fil!sOMy%X1Obin.mysPl#
,-OProgram Fil!sOMy%X1Obin.
MAT SOFT
JAVA REFERENCE GUIDE
330
Step 3:
Create the 7MP database by executing the following command
,-OProgram Fil!sOMy%X1Obin. mysPla#min cr!at! 3MP ;u root ;p
3nt!r passwor#- ********
,-OProgram Fil!sOMy%X1Obin.
Create Table
To create the 7mp$oyees table in EMP database, use the following steps:
Step 1: !pen a Command Prompt and change to the insta$$ation directory as fo$$o3s:
,-O.
,-O.c# Program Fil!sOMy%X1Obin
,-OProgram Fil!sOMy%X1Obin.
Step 2: 0ogin to data"ase as fo$$o3s
,-OProgram Fil!sOMy%X1Obin.mysPl ;u root ;p
3nt!r passwor#- ********
mysPl.
Step 3: Create the ta"$e Employee as fo$$o3s:
mysPl. us! 3MP*
mysPl. cr!at! tabl! 3mploy!!s
;. $
;. i# int not null2
;. ag! int not null2
;. first varchar $@HH(2
;. last varchar $@HH(
;. (*
Xu!ry ?Y2 E rows aff!ct!# $E.EJ s!c(
mysPl.
Create Data Records
Finally you create few records in Employee table as follows:
mysPl. 6=%37T 6=T? 3mploy!!s B0153% $CEE2 CJ2 'Vara'2 '0li'(*
Xu!ry ?Y2 C row aff!ct!# $E.EH s!c(
mysPl. 6=%37T 6=T? 3mploy!!s B0153% $CEC2 @H2 'Mahna/'2 'Fatma'(*
Xu!ry ?Y2 C row aff!ct!# $E.EE s!c(
MAT SOFT
JAVA REFERENCE GUIDE
331
mysPl. 6=%37T 6=T? 3mploy!!s B0153% $CE@2 DE2 'Vai#'2 'Yhan'(*
Xu!ry ?Y2 C row aff!ct!# $E.EE s!c(
mysPl. 6=%37T 6=T? 3mploy!!s B0153% $CED2 @J2 '%umit'2 'Mittal'(*
Xu!ry ?Y2 C row aff!ct!# $E.EE s!c(
mysPl.
Now you are ready to start experimenting with JDBC.
Day 32: What is JDBC?
JDBC stands for Java )ata"ase Connectivity, which is a standard Java API for database-independent
connectivity between the Java programming language and a wide range of databases.
The JDBC library includes APIs for each of the tasks commonly associated with database usage:
Making a connection to a database
Creating SQL or MySQL statements
Executing that SQL or MySQL queries in the database
Viewing & Modifying the resulting records
Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for
portable access to an underlying database. Java can be used to write different types of executables,
such as:
Java Applications
Java Applets
Java Servlets
Java ServerPages (JSPs)
Enterprise JavaBeans (EJBs)
All of these different executables are able to use a JDBC driver to access a database and take
advantage of the stored data.
JDBC provides the same capabilities as ODBC, allowing Java programs to contain database-
independent code.
JDBC Architecture:
The JDBC API supports both two-tier and three-tier processing models for database access but in
general JDBC Architecture consists of two layers:
1. J)BC %PI: This provides the application-to-JDBC Manager connection.
MAT SOFT
JAVA REFERENCE GUIDE
332
2. J)BC )river %PI: This supports the JDBC Manager-to-Driver Connection.
The JDBC API uses a driver manager and database-specific drivers to provide transparent connectivity
to heterogeneous databases.
The JDBC driver manager ensures that the correct driver is used to access each data source. The
driver manager is capable of supporting multiple concurrent drivers connected to multiple
heterogeneous databases.
Following is the architectural diagram, which shows the location of the driver manager with respect to
the JDBC drivers and the Java application:
Common JDBC Components:
The JDBC API provides the following interfaces and classes:
)riverManager: This class manages a list of database drivers. Matches connection requests
from the java application with the proper database driver using communication subprotocol.
The first driver that recognizes a certain subprotocol under JDBC will be used to establish a
database Connection.
)river: This interface handles the communications with the database server. You will interact
directly with Driver objects very rarely. Instead, you use DriverManager objects, which
manages objects of this type. It also abstracts the details associated with working with Driver
objects
Connection : This interface with all methods for contacting a database. The connection object
represents communication context, i.e., all communication with database is through
connection object only.
MAT SOFT
JAVA REFERENCE GUIDE
333
Statement : You use objects created from this interface to submit the SQL statements to the
database. Some derived interfaces accept parameters in addition to executing stored
procedures.
'es$tSet: These objects hold data retrieved from a database after you execute an SQL query
using Statement objects. It acts as an iterator to allow you to move through its data.
SJ07xception: This class handles any errors that occur in a database application.
The JDBC 4.0 Packages
The java.sql and javax.sql are the primary packages for JDBC 4.0. This is the latest JDBC version at
the time of writing this material. It offers the main classes for interacting with your data sources.
The new features in these packages include changes in the following areas:
Automatic database driver loading
Exception handling improvements
Enhanced BLOB/CLOB functionality
Connection and statement interface enhancements
National character set support
SQL ROWID access
SQL 2003 XML data type support
What is JDBC Driver ?
JDBC drivers implement the defined interfaces in the JDBC API for interacting with your database
server.
For example, using JDBC drivers enable you to open database connections and to interact with it by
sending SQL or database commands then receiving results with Java.
The a!a.s4l package that ships with JDK contains various classes with their behaviours defined and
their actual implementaions are done in third-party drivers. Third party vendors implements
the ja!a.s4l.6ri!er interface in their database driver.
JDBC Drivers Types:
JDBC driver implementations vary because of the wide variety of operating systems and hardware
platforms in which Java operates. Sun has divided the implementation types into four categories,
Types 1, 2, 3, and 4, which is explained below:
MAT SOFT
JAVA REFERENCE GUIDE
334
Type 1: JDBC-ODBC Bridge Driver:
In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client machine.
Using ODBC requires configuring on your system a Data Source Name (DSN) that represents the
target database.
When Java first came out, this was a useful driver because most databases only supported ODBC
access but now this type of driver is recommended only for experimental use or when no other
alternative is available.
The JDBC-ODBC bridge that comes with JDK 1.2 is a good example of this kind of driver.
Type 2: JDBC-Native API:
In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls which are unique to the
database. These drivers typically provided by the database vendors and used in the same manner as
the JDBC-ODBC Bridge, the vendor-specific driver must be installed on each client machine.
If we change the Database we have to change the native API as it is specific to a database and they
are mostly obsolete now but you may realize some speed increase with a Type 2 driver, because it
eliminates ODBC's overhead.
MAT SOFT
JAVA REFERENCE GUIDE
335
The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.
Type 3: JDBC-Net pure Java:
In a Type 3 driver, a three-tier approach is used to accessing databases. The JDBC clients use
standard network sockets to communicate with an middleware application server. The socket
information is then translated by the middleware application server into the call format required by the
DBMS, and forwarded to the database server.
This kind of driver is extremely flexible, since it requires no code installed on the client and a single
driver can actually provide access to multiple databases.
MAT SOFT
JAVA REFERENCE GUIDE
336
You can think of the application server as a JDBC "proxy," meaning that it makes calls for the client
application. As a result, you need some knowledge of the application server's configuration in order to
effectively use this driver type.
Your application server might use a Type 1, 2, or 4 driver to communicate with the database,
understanding the nuances will prove helpful.
Type 4: 100% pure Java:
In a Type 4 driver, a pure Java-based driver that communicates directly with vendor's database
through socket connection. This is the highest performance driver available for the database and is
usually provided by the vendor itself.
This kind of driver is extremely flexible, you don't need to install special software on the client or
server. Further, these drivers can be downloaded dynamically.
MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of their network
protocols, database vendors usually supply type 4 drivers.
Which Driver should be used?
If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver type is
4.
If your Java application is accessing multiple types of databases at the same time, type 3 is the
preferred driver.
Type 2 drivers are useful in situations where a type 3 or type 4 driver is not available yet for your
database.
MAT SOFT
JAVA REFERENCE GUIDE
337
The type 1 driver is not considered a deployment-level driver and is typically used for development
and testing purposes only.
CONNECTION
After you've installed the appropriate driver, it's time to establish a database connection using JDBC.
The programming involved to establish a JDBC connection is fairly simple. Here are these simple four
steps:
.. Import J)BC Pac=ages: Add import statements to your Java program to import required
classes in your Java code.
/. 'egister J)BC )river: This step causes the JVM to load the desired driver implementation
into memory so it can fulfill your JDBC requests.
0. )ata"ase B'0 +orm$ation: This is to create a properly formatted address that points to the
database to which you wish to connect.
@. Create Connection !"#ect: Finally, code a call to
the 6ri!er#anager object'sgetConnection( ) method to establish actual database connection.
Import JDBC Packages:
The Import statements tell the Java compiler where to find the classes you reference in your code
and are placed at the very beginning of your source code.
To use the standard JDBC package, which allows you to select, insert, update, and delete data in SQL
tables, add the following imports to your source code:
import java.sPl.* * // for stan#ar# J4L, programs
import java.math.* * // for Lig4!cimal an# Lig6nt!g!r support
Register JDBC Driver:
You must register the your driver in your program before you use it. Registering the driver is the
process by which the Oracle driver's class file is loaded into memory so it can be utilized as an
implementation of the JDBC interfaces.
You need to do this registration only once in your program. You can register a driver in one of two
ways.
Approach (I) - Class.forName():
The most common approach to register a driver is to use Java's C$ass1forName,/ method to
dynamically load the driver's class file into memory, which automatically registers it. This method is
preferable because it allows you to make the driver registration configurable and portable.
The following example uses Class.forName( ) to register the Oracle driver:
MAT SOFT
JAVA REFERENCE GUIDE
338
try {
,lass.for=am!$)oracl!.j#bc.#riv!r.?racl!4riv!r)(*
+
catch$,lass=otFoun#3:c!ption !:( {
%yst!m.out.println$)3rror- unabl! to loa# #riv!r classG)(*
%yst!m.!:it$C(*
+
You can use getInstance,/ method to work around noncompliant JVMs, but then you'll have to code
for two extra Exceptions as follows:
try {
,lass.for=am!$)oracl!.j#bc.#riv!r.?racl!4riv!r)(.n!w6nstanc!$(*
+
catch$,lass=otFoun#3:c!ption !:( {
%yst!m.out.println$)3rror- unabl! to loa# #riv!r classG)(*
%yst!m.!:it$C(*
catch$6ll!gal0cc!ss3:c!ption !:( {
%yst!m.out.println$)3rror- acc!ss probl!m whil! loa#ingG)(*
%yst!m.!:it$@(*
catch$6nstantiation3:c!ption !:( {
%yst!m.out.println$)3rror- unabl! to instantiat! #riv!rG)(*
%yst!m.!:it$D(*
+
Approach (II) - DriverManager.registerDriver():
The second approach you can use to register a driver is to use the
static)riverManager1register)river,/ method.
You should use the register6ri!er() method if you are using a non-JDK compliant JVM, such as the one
provided by Microsoft.
The following example uses registerDriver() to register the Oracle driver:
try {
4riv!r my4riv!r 9 n!w oracl!.j#bc.#riv!r.?racl!4riv!r$(*
4riv!rManag!r.r!gist!r4riv!r$ my4riv!r (*
+
catch$,lass=otFoun#3:c!ption !:( {
%yst!m.out.println$)3rror- unabl! to loa# #riv!r classG)(*
%yst!m.!:it$C(*
+
Database URL Formulation:
After you've loaded the driver, you can establish a connection using
the)riverManager1getConnection,/ method. For easy reference, let me list the three overloaded
DriverManager.getConnection() methods:
MAT SOFT
JAVA REFERENCE GUIDE
339
1. getConnection(String url)
2. getConnection(String url, Properties prop)
3. getConnection(String url, String user, String password)
Here each form requires a database B'0. A database URL is an address that points to your database.
Formulating a database URL is where most of the problems associated with establishing a connection
occur.
Following table lists down popular JDBC driver names and database URL.
')BMS J)BC driver name B'0 format
MySQL com.mysql.jdbc.Driver #d"c:mys;$:KKhostname/ databaseName
ORACLE oracle.jdbc.driver.OracleDriver #d"c:orac$e:thin:Lhostname:port
Number:databaseName
DB2 COM.ibm.db2.jdbc.net.DB2Driver #d"c:d"5:hostname:port Number/databaseName
Sybase com.sybase.jdbc.SybDriver #d"c:sy"ase:Tds:hostname: port
Number/databaseName
All the highlighted part in URL format is static and you need to change only remaining part as per your
database setup.
Create Connection Object:
Using a database URL with a username and password:
I listed down three forms of )riverManager1getConnection,/ method to create a connection object.
The most commonly used form of getConnection() requires you to pass a database URL, a username,
and a pass0ord:
Assuming you are using Oracle's thin driver, you'll specify a host:port:databaseName value for the
database portion of the URL.
If you have a host at TCP/IP address 192.0.0.1 with a host name of amrood, and your Oracle listener
is configured to listen on port 1521, and your database name is EMP, then complete database URL
would then be:
j#bc-oracl!-thin-\amroo#-CH@C-3MP
Now you have to call getConnection() method with appropriate username and password to get
aConnection object as follows:
MAT SOFT
JAVA REFERENCE GUIDE
340
%tring 571 9 )j#bc-oracl!-thin-\amroo#-CH@C-3MP)*
%tring 5%37 9 )us!rnam!)*
%tring P0%% 9 )passwor#)
,onn!ction conn 9 4riv!rManag!r.g!t,onn!ction$5712 5%372 P0%%(*
Using only a database URL:
A second form of the DriverManager.getConnection( ) method requires only a database URL:
4riv!rManag!r.g!t,onn!ction$%tring url(*
However, in this case, the database URL includes the username and password and has the following
general form:
j#bc-oracl!-#riv!r-us!rnam!/passwor#\#atabas!
So the above connection can be created as follows:
%tring 571 9 )j#bc-oracl!-thin-us!rnam!/passwor#\amroo#-CH@C-3MP)*
,onn!ction conn 9 4riv!rManag!r.g!t,onn!ction$571(*
Using a database URL and a Properties object:
A third form of the DriverManager.getConnection( ) method requires a database URL and a Properties
object:
4riv!rManag!r.g!t,onn!ction$%tring url2 Prop!rti!s info(*
A Properties object holds a set of keyword-value pairs. It's used to pass driver properties to the driver
during a call to the getConnection() method.
To make the same connection made by the previous examples, use the following code:
import java.util.**
%tring 571 9 )j#bc-oracl!-thin-\amroo#-CH@C-3MP)*
Prop!rti!s info 9 n!w Prop!rti!s$ (*
info.put$ )us!r)2 )us!rnam!) (*
info.put$ )passwor#)2 )passwor#) (*
,onn!ction conn 9 4riv!rManag!r.g!t,onn!ction$5712 info(*
Closing JDBC connections:
MAT SOFT
JAVA REFERENCE GUIDE
341
At the end of your JDBC program, it is required explicitly close all the connections to the database to
end each database session. However, if you forget, Java's garbage collector will close the connection
when it cleans up stale objects.
Relying on garbage collection, especially in database programming, is very poor programming
practice. You should make a habit of always closing the connection with the close() method associated
with connection object.
To ensure that a connection is closed, you could provide a finally block in your code. A $inallyblock
always executes, regardless if an exception occurs or not.
To close above opened connection you should call close() method as follows:
conn.clos!$(*
Explicitly closing a connection conserves DBMS resources, which will make your database
administrator happy.
STATEMENT
Once a connection is obtained we can interact with the database. The JDBC 2tatement3
Callable2tatement3 and Prepared2tatement interfaces define the methods and properties that enable
you to send SQL or PL/SQL commands and receive data from your database.
They also define methods that help bridge data type differences between Java and SQL data types
used in a database.
Following table provides a summary of each interface's purpose to understand how do you decide
which interface to use?
Interfaces 'ecommended Bse
Statement Use for general-purpose access to your database. Useful when you are
using static SQL statements at runtime. The Statement interface cannot
accept parameters.
PreparedStatement Use when you plan to use the SQL statements many times. The
PreparedStatement interface accepts input parameters at runtime.
CallableStatement Use when you want to access database stored procedures. The
CallableStatement interface can also accept runtime input parameters.
The Statement Objects:
MAT SOFT
JAVA REFERENCE GUIDE
342
Creating Statement Object:
Before you can use a Statement object to execute a SQL statement, you need to create one using the
Connection object's createStatement( ) method, as in the following example:
%tat!m!nt stmt 9 null*
try {
stmt 9 conn.cr!at!%tat!m!nt$ (*
. . .
+
catch $%X13:c!ption !( {
. . .
+
finally {
. . .
+
Once you've created a Statement object, you can then use it to execute a SQL statement with one of
its three execute methods.
.. "oo$ean execte,String SJ0/ : Returns a boolean value of true if a ResultSet object can be
retrieved; otherwise, it returns false. Use this method to execute SQL DDL statements or when
you need to use truly dynamic SQL.
/. int execteBpdate,String SJ0/ : Returns the numbers of rows affected by the execution of
the SQL statement. Use this method to execute SQL statements for which you expect to get a
number of rows affected - for example, an INSERT, UPDATE, or DELETE statement.
0. 'es$tSet execteJery,String SJ0/ : Returns a ResultSet object. Use this method when
you expect to get a result set, as you would with a SELECT statement.
Closing Statement Obeject:
Just as you close a Connection object to save database resources, for the same reason you should also
close the Statement object.
A simple call to the close() method will do the job. If you close the Connection object first it will close
the Statement object as well. However, you should always explicitly close the Statement object to
ensure proper cleanup.
%tat!m!nt stmt 9 null*
try {
stmt 9 conn.cr!at!%tat!m!nt$ (*
. . .
+
catch $%X13:c!ption !( {
. . .
+
finally {
stmt.clos!$(*
+
MAT SOFT
JAVA REFERENCE GUIDE
343
For a better understanding, I would suggest to study Statement - Example Code.
The PreparedStatement Objects:
The Prepared2tatement interface extends the Statement interface which gives you added functionality
with a couple of advantages over a generic Statement object.
This statement gives you the flexibility of supplying arguments dynamically.
Creating PreparedStatement Object:
Pr!par!#%tat!m!nt pstmt 9 null*
try {
%tring %X1 9 )5p#at! 3mploy!!s %3T ag! 9 S "373 i# 9 S)*
pstmt 9 conn.pr!par!%tat!m!nt$%X1(*
. . .
+
catch $%X13:c!ption !( {
. . .
+
finally {
. . .
+
All parameters in JDBC are represented by the M symbol, which is known as the parameter marker.
You must supply values for every parameter before executing the SQL statement.
The set>>>,/ methods bind values to the parameters, where >>> represents the Java data type of
the value you wish to bind to the input parameter. If you forget to supply the values, you will receive
an SQLException.
Each parameter marker is referred to by its ordinal position. The first marker represents position 1,
the next position 2, and so forth. This method differs from that of Java array indices, which start at 0.
All of the Statement o"#ectNs methods for interacting with the database (a) execute(), (b)
executeQuery(), and (c) executeUpdate() also work with the PreparedStatement object. However, the
methods are modified to use SQL statements that can take input the parameters.
Closing PreparedStatement Obeject:
Just as you close a Statement object, for the same reason you should also close the
PreparedStatement object.
A simple call to the close() method will do the job. If you close the Connection object first it will close
the PreparedStatement object as well. However, you should always explicitly close the
PreparedStatement object to ensure proper cleanup.
Pr!par!#%tat!m!nt pstmt 9 null*
try {
MAT SOFT
JAVA REFERENCE GUIDE
344
%tring %X1 9 )5p#at! 3mploy!!s %3T ag! 9 S "373 i# 9 S)*
pstmt 9 conn.pr!par!%tat!m!nt$%X1(*
. . .
+
catch $%X13:c!ption !( {
. . .
+
finally {
pstmt.clos!$(*
+
The CallableStatement Objects:
Just as a Connection object creates the Statement and PreparedStatement objects, it also creates the
CallableStatement object which would be used to execute a call to a database stored procedure.
Creating CallableStatement Object:
Suppose, you need to execute the following Oracle stored procedure:
,730T3 ?7 73P10,3 P7?,34573 g!t3mp=am!
$3MPT64 6= =5ML372 3MPTF67%T ?5T B07,07( 0%
L386=
%313,T first 6=T? 3MPTF67%T
F7?M 3mploy!!s
"373 64 9 3MPT64*
3=4*
N!T7: Above stored procedure has been written for Oracle, but we are working with MySQL database
so let us write same stored procedure for MySQL as follows to create it in EMP database:
4316M6T37 UU
47?P P7?,34573 6F 3R6%T% ]3MP].]g!t3mp=am!] UU
,730T3 P7?,34573 ]3MP].]g!t3mp=am!]
$6= 3MPT64 6=T2 ?5T 3MPTF67%T B07,07$@HH((
L386=
%313,T first 6=T? 3MPTF67%T
F7?M 3mploy!!s
"373 64 9 3MPT64*
3=4 UU
4316M6T37 *
Three types of parameters exist: IN, OUT, and INOUT. The PreparedStatement object only uses the IN
parameter. The CallableStatement object can use all three.
Here are the definitions of each:
MAT SOFT
JAVA REFERENCE GUIDE
345
Parameter )escription
IN A parameter whose value is unknown when the SQL statement is
created. You bind values to IN parameters with the setXXX() methods.
OUT A parameter whose value is supplied by the SQL statement it returns.
You retrieve values from theOUT parameters with the getXXX() methods.
INOUT A parameter that provides both input and output values. You bind
variables with the setXXX() methods and retrieve values with the
getXXX() methods.
The following code snippet shows how to employ the Connection1prepareCa$$,/ method to
instantiate a Ca$$a"$eStatement object based on the preceding stored procedure:
,allabl!%tat!m!nt cstmt 9 null*
try {
%tring %X1 9 ){call g!t3mp=am! $S2 S(+)*
cstmt 9 conn.pr!par!,all $%X1(*
. . .
+
catch $%X13:c!ption !( {
. . .
+
finally {
. . .
+
The String variable SQL represents the stored procedure, with parameter placeholders.
Using CallableStatement objects is much like using PreparedStatement objects. You must bind values
to all parameters before executing the statement, or you will receive an SQLException.
If you have IN parameters, just follow the same rules and techniques that apply to a
PreparedStatement object; use the setXXX() method that corresponds to the Java data type you are
binding.
When you use OUT and INOUT parameters you must employ an additional CallableStatement method,
registerOutParameter(). The registerOutParameter() method binds the JDBC data type to the data
type the stored procedure is expected to return.
Once you call your stored procedure, you retrieve the value from the OUT parameter with the
appropriate getXXX() method. This method casts the retrieved value of SQL type to a Java data type.
Closing CallableStatement Obeject:
Just as you close other Statement object, for the same reason you should also close the
CallableStatement object.
MAT SOFT
JAVA REFERENCE GUIDE
346
A simple call to the close() method will do the job. If you close the Connection object first it will close
the CallableStatement object as well. However, you should always explicitly close the
CallableStatement object to ensure proper cleanup.
,allabl!%tat!m!nt cstmt 9 null*
try {
%tring %X1 9 ){call g!t3mp=am! $S2 S(+)*
cstmt 9 conn.pr!par!,all $%X1(*
. . .
+
catch $%X13:c!ption !( {
. . .
+
finally {
cstmt.clos!$(*
+
Day 33: RESULT SET
The SQL statements that read data from a database query return the data in a result set. The SELECT
statement is the standard way to select rows from a database and view them in a result set.
The ja!a.s4l..esult2et interface represents the result set of a database query.
A ResultSet object maintains a cursor that points to the current row in the result set. The term "result
set" refers to the row and column data contained in a ResultSet object.
The methods of the ResultSet interface can be broken down into three categories:
1. Navigationa$ methods: used to move the cursor around.
2. ?et methods: used to view the data in the columns of the current row being pointed to by
the cursor.
3. Bpdate methods: used to update the data in the columns of the current row. The updates
can then be updated in the underlying database as well.
The cursor is movable based on the properties of the ResultSet. These properties are designated when
the corresponding Statement that generated the ResultSet is created.
JDBC provides following connection methods to create statements with desired ResultSet:
41 createStatement,int 'SType< int 'SConcrrency/O
51 prepareStatement,String SJ0< int 'SType< int 'SConcrrency/O
E1 prepareCa$$,String s;$< int 'SType< int 'SConcrrency/O
The first argument indicate the type of a ResultSet object and the second argument is one of two
ResultSet constants for specifying whether a result set is read-only or updatable.
MAT SOFT
JAVA REFERENCE GUIDE
347
Type of ResultSet:
The possible RSType are given below, If you do not specify any ResultSet type, you will automatically
get one that is TYPE_FORWARD_ONLY.
Type )escription
ResultSet.TYPE_FORWARD_ONLY The cursor can only move forward in the result set.
ResultSet.TYPE_SCROLL_INSENSITIVE The cursor can scroll forwards and backwards, and the
result set is not sensitive to changes made by others to
the database that occur after the result set was created.
ResultSet.TYPE_SCROLL_SENSITIVE. The cursor can scroll forwards and backwards, and the
result set is sensitive to changes made by others to the
database that occur after the result set was created.
Concurrency of ResultSet:
The possible RSConcurrency are given below, If you do not specify any Concurrency type, you will
automatically get one that is CONCUR_READ_ONLY.
Concrrency )escription
ResultSet.CONCUR_READ_ONLY Creates a read-only result set. This is the default
ResultSet.CONCUR_UPDATABLE Creates an updateable result set.
Our all the examples written so far can be written as follows which initializes a Statement object to
create a forward-only, read only ResultSet object:
try {
%tat!m!nt stmt 9 conn.cr!at!%tat!m!nt$
7!sult%!t.TAP3TF?7"074T?=1A2
7!sult%!t.,?=,57T7304T?=1A(*
+
catch$3:c!ption !:( {
....
+
finally {
....
+
Navigating a Result Set:
MAT SOFT
JAVA REFERENCE GUIDE
348
There are several methods in the ResultSet interface that involve moving the cursor, including:
S1N1 Methods : )escription
1 p"$ic void "efore+irst,/ thro3s SJ07xception
Moves the cursor to just before the first row
2 p"$ic void after0ast,/ thro3s SJ07xception
Moves the cursor to just after the last row
3 p"$ic "oo$ean first,/ thro3s SJ07xception
Moves the cursor to the first row
4 p"$ic void $ast,/ thro3s SJ07xception
Moves the cursor to the last row.
5 p"$ic "oo$ean a"so$te,int ro3/ thro3s SJ07xception
Moves the cursor to the specified row
6 p"$ic "oo$ean re$ative,int ro3/ thro3s SJ07xception
Moves the cursor the given number of rows forward or backwards from where it currently is
pointing.
7 p"$ic "oo$ean previos,/ thro3s SJ07xception
Moves the cursor to the previous row. This method returns false if the previous row is off the
result set
8 p"$ic "oo$ean next,/ thro3s SJ07xception
Moves the cursor to the next row. This method returns false if there are no more rows in the
result set
9 p"$ic int get'o3,/ thro3s SJ07xception
Returns the row number that the cursor is pointing to.
10 p"$ic void moveToInsert'o3,/ thro3s SJ07xception
Moves the cursor to a special row in the result set that can be used to insert a new row into the
database. The current cursor location is remembered.
11 p"$ic void moveToCrrent'o3,/ thro3s SJ07xception
Moves the cursor back to the current row if the cursor is currently at the insert row; otherwise,
this method does nothing
Viewing a Result Set:
The ResultSet interface contains dozens of methods for getting the data of the current row.
MAT SOFT
JAVA REFERENCE GUIDE
349
There is a get method for each of the possible data types, and each get method has two versions:
1. One that takes in a column name.
2. One that takes in a column index.
For example, if the column you are interested in viewing contains an int, you need to use one of the
getInt() methods of ResultSet:
S1N1 Methods : )escription
1 p"$ic int getInt,String co$mnName/ thro3s SJ07xception
Returns the int in the current row in the column named columnName
2 p"$ic int getInt,int co$mnIndex/ thro3s SJ07xception
Returns the int in the current row in the specified column index. The column index starts at 1,
meaning the first column of a row is 1, the second column of a row is 2, and so on.
Similarly there are get methods in the ResultSet interface for each of the eight Java primitive types, as
well as common types such as java.lang.String, java.lang.Object, and java.net.URL
There are also methods for getting SQL data types java.sql.Date, java.sql.Time, java.sql.TimeStamp,
java.sql.Clob, and java.sql.Blob. Check the documentation for more information about using these SQL
data types.
For a better understanding, I would suggest to study Viewing - Example Code.
Updating a Result Set:
The ResultSet interface contains a collection of update methods for updating the data of a result set.
As with the get methods, there are two update methods for each data type:
1. One that takes in a column name.
2. One that takes in a column index.
For example, to update a String column of the current row of a result set, you would use one of the
following updateString() methods:
S1N1 Methods : )escription
1 p"$ic void pdateString,int co$mnIndex< String s/ thro3s SJ07xception
Changes the String in the specified column to the value of s.
2 p"$ic void pdateString,String co$mnName< String s/ thro3s SJ07xception
Similar to the previous method, except that the column is specified by its name instead of its
index.
MAT SOFT
JAVA REFERENCE GUIDE
350
There are update methods for the eight primitive data types, as well as String, Object, URL, and the
SQL data types in the java.sql package.
Updating a row in the result set changes the columns of the current row in the ResultSet object, but
not in the underlying database. To update your changes to the row in the database, you need to
invoke one of the following methods.
S1N1 Methods : )escription
1 p"$ic void pdate'o3,/
Updates the current row by updating the corresponding row in the database.
2 p"$ic void de$ete'o3,/
Deletes the current row from the database
3 p"$ic void refresh'o3,/
Refreshes the data in the result set to reflect any recent changes in the database.
4 p"$ic void cance$'o3Bpdates,/
Cancels any updates made on the current row.
5 p"$ic void insert'o3,/
Inserts a row into the database. This method can only be invoked when the cursor is pointing to
the insert row.
Creating JDBC Application:
There are following six steps involved in building a JDBC application:
14 Import the pac=ages 1 Requires that you include the packages containing the JDBC classes
needed for database programming. Most often, using import ja!a.s4l.? will suffice.
24 'egister the J)BC driver 1 Requires that you initialize a driver so you can open a
communications channel with the database.
34 !pen a connection 1 Requires using the 6ri!er#anager.getConnection() method to create a
Connection object, which represents a physical connection with the database.
44 7xecte a ;ery 1 Requires using an object of type Statement for building and submitting an
SQL statement to the database.
54 7xtract data from res$t set 1 Requires that you use the
appropriate.esult2et.get;;;() method to retrieve the data from the result set.
64 C$ean p the environment 1 Requires explicitly closing all database resources versus relying
on the JVM's garbage collection.
MAT SOFT
JAVA REFERENCE GUIDE
351
Sample Code:
This sample example can serve as a temp$ate when you need to create your own JDBC application in
the future.
This sample code has been written based on the environment and database setup done in previous
chapter.
Copy and past following example in FirstExample.java, compile and run as follows:
//%T3P C. 6mport r!Puir!# pac<ag!s
import java.sPl.**
public class First3:ampl! {
// J4L, #riv!r nam! an# #atabas! 571
static final %tring J4L,T476B37 9 )com.mysPl.j#bc.4riv!r)*
static final %tring 4LT571 9 )j#bc-mysPl-//localhost/3MP)*
// 4atabas! cr!#!ntials
static final %tring 5%37 9 )us!rnam!)*
static final %tring P0%% 9 )passwor#)*

public static voi# main$%tring&' args( {
,onn!ction conn 9 null*
%tat!m!nt stmt 9 null*
try{
//%T3P @- 7!gist!r J4L, #riv!r
,lass.for=am!$)com.mysPl.j#bc.4riv!r)(*
//%T3P D- ?p!n a conn!ction
%yst!m.out.println$),onn!cting to #atabas!...)(*
conn 9 4riv!rManag!r.g!t,onn!ction$4LT57125%372P0%%(*
//%T3P F- 3:!cut! a Pu!ry
%yst!m.out.println$),r!ating stat!m!nt...)(*
stmt 9 conn.cr!at!%tat!m!nt$(*
%tring sPl*
sPl 9 )%313,T i#2 first2 last2 ag! F7?M 3mploy!!s)*
7!sult%!t rs 9 stmt.!:!cut!Xu!ry$sPl(*
//%T3P H- 3:tract #ata from r!sult s!t
whil!$rs.n!:t$(({
//7!tri!v! by column nam!
int i# 9 rs.g!t6nt$)i#)(*
int ag! 9 rs.g!t6nt$)ag!)(*
%tring first 9 rs.g!t%tring$)first)(*
%tring last 9 rs.g!t%tring$)last)(*
//4isplay valu!s
%yst!m.out.print$)64- ) > i#(*
%yst!m.out.print$)2 0g!- ) > ag!(*
%yst!m.out.print$)2 First- ) > first(*
%yst!m.out.println$)2 1ast- ) > last(*
MAT SOFT
JAVA REFERENCE GUIDE
352
+
//%T3P M- ,l!an;up !nvironm!nt
rs.clos!$(*
stmt.clos!$(*
conn.clos!$(*
+catch$%X13:c!ption s!({
//an#l! !rrors for J4L,
s!.print%tac<Trac!$(*
+catch$3:c!ption !({
//an#l! !rrors for ,lass.for=am!
!.print%tac<Trac!$(*
+finally{
//finally bloc< us!# to clos! r!sourc!s
try{
if$stmtG9null(
stmt.clos!$(*
+catch$%X13:c!ption s!@({
+// nothing w! can #o
try{
if$connG9null(
conn.clos!$(*
+catch$%X13:c!ption s!({
s!.print%tac<Trac!$(*
+//!n# finally try
+//!n# try
%yst!m.out.println$)8oo#by!G)(*
+//!n# main
+//!n# First3:ampl!
Now let us compile above example as follows:
,-O.javac First3:ampl!.java
,-O.
When you run +irst7xamp$e, it produces following result:
,-O.java First3:ampl!
,onn!cting to #atabas!...
,r!ating stat!m!nt...
64- CEE2 0g!- CJ2 First- Vara2 1ast- 0li
64- CEC2 0g!- @H2 First- Mahna/2 1ast- Fatma
64- CE@2 0g!- DE2 First- Vai#2 1ast- Yhan
64- CED2 0g!- @J2 First- %umit2 1ast- Mittal
,-O.
MAT SOFT
JAVA REFERENCE GUIDE
353
UPDATING DATABASE USING RESULTSET
Following is the example which makes use
of 'es$tSet1C!NCB'GBP)%T%B07 and'es$tSet1TAP7GSC'!00GINS7NSITI*7 described in
Result Set material. This example would explain INSERT, UPDATE and DELETE operation on a table.
It should be noted that tables you are working on should have Primary Key set properly.
This sample code has been written based on the environment and database setup done in previous
chapters.
Copy and past following example in JDBCExample.java, compile and run as follows:
//%T3P C. 6mport r!Puir!# pac<ag!s
import java.sPl.**
public class J4L,3:ampl! {
// J4L, #riv!r nam! an# #atabas! 571
static final %tring J4L,T476B37 9 )com.mysPl.j#bc.4riv!r)*
static final %tring 4LT571 9 )j#bc-mysPl-//localhost/3MP)*
// 4atabas! cr!#!ntials
static final %tring 5%37 9 )us!rnam!)*
static final %tring P0%% 9 )passwor#)*

public static voi# main$%tring&' args( {
,onn!ction conn 9 null*
try{
//%T3P @- 7!gist!r J4L, #riv!r
,lass.for=am!$)com.mysPl.j#bc.4riv!r)(*
//%T3P D- ?p!n a conn!ction
%yst!m.out.println$),onn!cting to #atabas!...)(*
conn 9 4riv!rManag!r.g!t,onn!ction$4LT57125%372P0%%(*
//%T3P F- 3:!cut! a Pu!ry to cr!at! statm!nt with
// r!Puir!# argum!nts for 7% !:ampl!.
MAT SOFT
JAVA REFERENCE GUIDE
354
%yst!m.out.println$),r!ating stat!m!nt...)(*
%tat!m!nt stmt 9 conn.cr!at!%tat!m!nt$
7!sult%!t.TAP3T%,7?11T6=%3=%6T6B32
7!sult%!t.,?=,57T5P40T0L13(*
//%T3P H- 3:!cut! a Pu!ry
%tring sPl 9 )%313,T i#2 first2 last2 ag! F7?M 3mploy!!s)*
7!sult%!t rs 9 stmt.!:!cut!Xu!ry$sPl(*
%yst!m.out.println$)1ist r!sult s!t for r!f!r!nc!....)(*
print7s$rs(*
//%T3P M- 1oop through r!sult s!t an# a## H in ag!
//Mov! to LF7 postion so whil!;loop wor<s prop!rly
rs.b!for!First$(*
//%T3P I- 3:tract #ata from r!sult s!t
whil!$rs.n!:t$(({
//7!tri!v! by column nam!
int n!w0g! 9 rs.g!t6nt$)ag!)( > H*
rs.up#at!4oubl!$ )ag!)2 n!w0g! (*
rs.up#at!7ow$(*
+
%yst!m.out.println$)1ist r!sult s!t showing n!w ag!s...)(*
print7s$rs(*
// 6ns!rt a r!cor# into th! tabl!.
//Mov! to ins!rt row an# a## column #ata with up#at!RRR$(
%yst!m.out.println$)6ns!rting a n!w r!cor#...)(*
rs.mov!To6ns!rt7ow$(*
rs.up#at!6nt$)i#)2CEF(*
rs.up#at!%tring$)first)2)John)(*
rs.up#at!%tring$)last)2)Paul)(*
rs.up#at!6nt$)ag!)2FE(*
//,ommit row
rs.ins!rt7ow$(*
%yst!m.out.println$)1ist r!sult s!t showing n!w s!t...)(*
print7s$rs(*

// 4!l!t! s!con# r!cor# from th! tabl!.
// %!t position to s!con# r!cor# first
rs.absolut!$ @ (*
%yst!m.out.println$)1ist th! r!cor# b!for! #!l!ting...)(*
//7!tri!v! by column nam!
int i# 9 rs.g!t6nt$)i#)(*
int ag! 9 rs.g!t6nt$)ag!)(*
%tring first 9 rs.g!t%tring$)first)(*
%tring last 9 rs.g!t%tring$)last)(*
//4isplay valu!s
%yst!m.out.print$)64- ) > i#(*
%yst!m.out.print$)2 0g!- ) > ag!(*
%yst!m.out.print$)2 First- ) > first(*
%yst!m.out.println$)2 1ast- ) > last(*
//4!l!t! row
rs.#!l!t!7ow$(*
MAT SOFT
JAVA REFERENCE GUIDE
355
%yst!m.out.println$)1ist r!sult s!t aft!r O
#!l!ting on! r!cor#s...)(*
print7s$rs(*
//%T3P J- ,l!an;up !nvironm!nt
rs.clos!$(*
stmt.clos!$(*
conn.clos!$(*
+catch$%X13:c!ption s!({
//an#l! !rrors for J4L,
s!.print%tac<Trac!$(*
+catch$3:c!ption !({
//an#l! !rrors for ,lass.for=am!
!.print%tac<Trac!$(*
+finally{
//finally bloc< us!# to clos! r!sourc!s
try{
if$connG9null(
conn.clos!$(*
+catch$%X13:c!ption s!({
s!.print%tac<Trac!$(*
+//!n# finally try
+//!n# try
%yst!m.out.println$)8oo#by!G)(*
+//!n# main
public static voi# print7s$7!sult%!t rs( throws %X13:c!ption{
//3nsur! w! start with first row
rs.b!for!First$(*
whil!$rs.n!:t$(({
//7!tri!v! by column nam!
int i# 9 rs.g!t6nt$)i#)(*
int ag! 9 rs.g!t6nt$)ag!)(*
%tring first 9 rs.g!t%tring$)first)(*
%tring last 9 rs.g!t%tring$)last)(*
//4isplay valu!s
%yst!m.out.print$)64- ) > i#(*
%yst!m.out.print$)2 0g!- ) > ag!(*
%yst!m.out.print$)2 First- ) > first(*
%yst!m.out.println$)2 1ast- ) > last(*
+
%yst!m.out.println$(*
+//!n# print7s$(
+//!n# J4L,3:ampl!
Now let us compile above example as follows:
,-O.javac J4L,3:ampl!.java
,-O.
When you run J)BC7xamp$e, it produces following result:
MAT SOFT
JAVA REFERENCE GUIDE
356
,-O.java J4L,3:ampl!
,onn!cting to #atabas!...
,r!ating stat!m!nt...
1ist r!sult s!t for r!f!r!nc!....
64- CEE2 0g!- DD2 First- Vara2 1ast- 0li
64- CEC2 0g!- FE2 First- Mahna/2 1ast- Fatma
64- CE@2 0g!- HE2 First- Vai#2 1ast- Yhan
64- CED2 0g!- FH2 First- %umit2 1ast- Mittal
1ist r!sult s!t showing n!w ag!s...
64- CEE2 0g!- DJ2 First- Vara2 1ast- 0li
64- CEC2 0g!- FH2 First- Mahna/2 1ast- Fatma
64- CE@2 0g!- HH2 First- Vai#2 1ast- Yhan
64- CED2 0g!- HE2 First- %umit2 1ast- Mittal
6ns!rting a n!w r!cor#...
1ist r!sult s!t showing n!w s!t...
64- CEE2 0g!- DJ2 First- Vara2 1ast- 0li
64- CEC2 0g!- FH2 First- Mahna/2 1ast- Fatma
64- CE@2 0g!- HH2 First- Vai#2 1ast- Yhan
64- CED2 0g!- HE2 First- %umit2 1ast- Mittal
64- CEF2 0g!- FE2 First- John2 1ast- Paul
1ist th! r!cor# b!for! #!l!ting...
64- CEC2 0g!- FH2 First- Mahna/2 1ast- Fatma
1ist r!sult s!t aft!r #!l!ting on! r!cor#s...
64- CEE2 0g!- DJ2 First- Vara2 1ast- 0li
64- CE@2 0g!- HH2 First- Vai#2 1ast- Yhan
64- CED2 0g!- HE2 First- %umit2 1ast- Mittal
64- CEF2 0g!- FE2 First- John2 1ast- Paul
8oo#by!G
,-O.
JAVATYPES VERSES SQL TYPES
The JDBC driver converts the Java data type to the appropriate JDBC type before sending it to the
database. It uses a default mapping for most data types. For example, a Java int is converted to an
SQL INTEGER. Default mappings were created to provide consistency between drivers.
The following table summarizes the default JDBC data type that the Java data type is converted to
when you call the setXXX() method of the PreparedStatement or CallableStatement object or the
ResultSet.updateXXX() method.
SJ0 J)BCKJava set>>> pdate>>>
VARCHAR java.lang.String setString updateString
CHAR java.lang.String setString updateString
MAT SOFT
JAVA REFERENCE GUIDE
357
LONGVARCHAR java.lang.String setString updateString
BIT boolean setBoolean updateBoolean
NUMERIC java.math.BigDecimal setBigDecimal updateBigDecimal
TINYINT byte setByte updateByte
SMALLINT short setShort updateShort
INTEGER int setInt updateInt
BIGINT long setLong updateLong
REAL float setFloat updateFloat
FLOAT float setFloat updateFloat
DOUBLE double setDouble updateDouble
VARBINARY byte[ ] setBytes updateBytes
BINARY byte[ ] setBytes updateBytes
DATE java.sql.Date setDate updateDate
TIME java.sql.Time setTime updateTime
TIMESTAMP java.sql.Timestamp setTimestamp updateTimestamp
CLOB java.sql.Clob setClob updateClob
BLOB java.sql.Blob setBlob updateBlob
ARRAY java.sql.Array setARRAY updateARRAY
REF java.sql.Ref SetRef updateRef
STRUCT java.sql.Struct SetStruct updateStruct
JDBC 3.0 has enhanced support for BLOB, CLOB, ARRAY, and REF data types. The ResultSet object
now has updateBLOB(), updateCLOB(), updateArray(), and updateRef() methods that enable you to
directly manipulate the respective data on the server.
The setXXX() and updateXXX() methods enable you to convert specific Java types to specific JDBC
data types. The methods, setObject() and updateObject(), enable you to map almost any Java type to
a JDBC data type.
ResultSet object provides corresponding getXXX() method for each data type to retrieve column value.
Each method can be used with column name or by its ordinal position.
SJ0 J)BCKJava set>>> get>>>
VARCHAR java.lang.String setString getString
CHAR java.lang.String setString getString
LONGVARCHAR java.lang.String setString getString
BIT boolean setBoolean getBoolean
MAT SOFT
JAVA REFERENCE GUIDE
358
NUMERIC java.math.BigDecimal setBigDecimal getBigDecimal
TINYINT byte setByte getByte
SMALLINT short setShort getShort
INTEGER int setInt getInt
BIGINT long setLong getLong
REAL float setFloat getFloat
FLOAT float setFloat getFloat
DOUBLE double setDouble getDouble
VARBINARY byte[ ] setBytes getBytes
BINARY byte[ ] setBytes getBytes
DATE java.sql.Date setDate getDate
TIME java.sql.Time setTime getTime
TIMESTAMP java.sql.Timestamp setTimestamp getTimestamp
CLOB java.sql.Clob setClob getClob
BLOB java.sql.Blob setBlob getBlob
ARRAY java.sql.Array setARRAY getARRAY
REF java.sql.Ref SetRef getRef
STRUCT java.sql.Struct SetStruct getStruct
Date & Time Data Types:
The java.sql.Date class maps to the SQL DATE type, and the java.sql.Time and java.sql.Timestamp
classes map to the SQL TIME and SQL TIMESTAMP data types, respectively.
Following examples shows how the Date and Time classes format standard Java date and time values
to match the SQL data type requirements.
import java.sPl.4at!*
import java.sPl.Tim!*
import java.sPl.Tim!stamp*
import java.util.**
public class %Pl4at!Tim! {
public static voi# main$%tring&' args( {
//8!t stan#ar# #at! an# tim!
java.util.4at! java4at! 9 n!w java.util.4at!$(*
long javaTim! 9 java4at!.g!tTim!$(*
%yst!m.out.println$)Th! Java 4at! is-) >
java4at!.to%tring$((*
//8!t an# #isplay %X1 40T3
MAT SOFT
JAVA REFERENCE GUIDE
359
java.sPl.4at! sPl4at! 9 n!w java.sPl.4at!$javaTim!(*
%yst!m.out.println$)Th! %X1 40T3 is- ) >
sPl4at!.to%tring$((*
//8!t an# #isplay %X1 T6M3
java.sPl.Tim! sPlTim! 9 n!w java.sPl.Tim!$javaTim!(*
%yst!m.out.println$)Th! %X1 T6M3 is- ) >
sPlTim!.to%tring$((*
//8!t an# #isplay %X1 T6M3%T0MP
java.sPl.Tim!stamp sPlTim!stamp 9
n!w java.sPl.Tim!stamp$javaTim!(*
%yst!m.out.println$)Th! %X1 T6M3%T0MP is- ) >
sPlTim!stamp.to%tring$((*
+//!n# main
+//!n# %Pl4at!Tim!
Now let us compile above example as follows:
,-O.javac %Pl4at!Tim!.java
,-O.
When you run J)BC7xamp$e, it produces following result:
,-O.java %Pl4at!Tim!
Th! Java 4at! is-Tu! 0ug CJ CD-FM-E@ 8MT>EF-EE @EEK
Th! %X1 40T3 is- @EEK;EJ;CJ
Th! %X1 T6M3 is- CD-FM-E@
Th! %X1 T6M3%T0MP is- @EEK;EJ;CJ CD-FM-E@.J@J
,-O.
Handling NULL Values:
SQL's use of NULL values and Java's use of null are different concepts. So how do you handle SQL
NULL values in Java? There are three tactics you can use:
1. Avoid using getXXX( ) methods that return primitive data types.
2. Use wrapper classes for primitive data types, and use the ResultSet object's wasNull( ) method
to test whether the wrapper class variable that received the value returned by the getXXX( )
method should be set to null.
3. Use primitive data types and the ResultSet object's wasNull( ) method to test whether the
primitive variable that received the value returned by the getXXX( ) method should be set to
an acceptable value that you've chosen to represent a NULL.
Here is one example to handle a NULL value:
%tat!m!nt stmt 9 conn.cr!at!%tat!m!nt$ (*
%tring sPl 9 )%313,T i#2 first2 last2 ag! F7?M 3mploy!!s)*
7!sult%!t rs 9 stmt.!:!cut!Xu!ry$sPl(*
MAT SOFT
JAVA REFERENCE GUIDE
360
int i# 9 rs.g!t6nt$C(*
if$ rs.was=ull$ ( ( {
i# 9 E*
+
Day 34: TRANSACTION CONTROLLING
If your JDBC Connection is in auto-commit mode, which it is by default, then every SQL statement is
committed to the database upon its completion.
That may be fine for simple applications, but there are three reasons why you may want to turn off
auto-commit and manage your own transactions:
1. To increase performance
2. To maintain the integrity of business processes
3. To use distributed transactions
Transactions enable you to control if, and when, changes are applied to the database. It treats a single
SQL statement or a group of SQL statements as one logical unit, and if any statement fails, the whole
transaction fails.
To enable manual- transaction support instead of the auto-commit mode that the JDBC driver uses by
default, use the Connection object's set%toCommit,/ method. If you pass a boolean false to
setAutoCommit( ), you turn off auto-commit. You can pass a boolean true to turn it back on again.
For example, if you have a Connection object named conn, code the following to turn off auto-commit:
conn.s!t0uto,ommit$fals!(*
Commit & Rollback
Once you are done with your changes and you want to commit the changes then
call commit,/method on connection object as follows:
conn.commit$ (*
Otherwise, to roll back updates to the database made using the Connection named conn, use the
following code:
conn.rollbac<$ (*
The following example illustrates the use of a commit and rollback object:
MAT SOFT
JAVA REFERENCE GUIDE
361
try{
//0ssum! a vali# conn!ction obj!ct conn
conn.s!t0uto,ommit$fals!(*
%tat!m!nt stmt 9 conn.cr!at!%tat!m!nt$(*

%tring %X1 9 )6=%37T 6=T? 3mploy!!s ) >
)B0153% $CEM2 @E2 '7ita'2 'T!/'()*
stmt.!:!cut!5p#at!$%X1(*
//%ubmit a malform!# %X1 stat!m!nt that br!a<s
%tring %X1 9 )6=%37T34 6= 3mploy!!s ) >
)B0153% $CEI2 @@2 '%ita'2 '%ingh'()*
stmt.!:!cut!5p#at!$%X1(*
// 6f th!r! is no !rror.
conn.commit$(*
+catch$%X13:c!ption s!({
// 6f th!r! is any !rror.
conn.rollbac<$(*
+
In this case none of the abobe INSERT statement would success and everything would be rolled back.
Using Savepoints:
The new JDBC 3.0 Savepoint interface gives you additional transactional control. Most modern DBMS
support savepoints within their environments such as Oracle's PL/SQL.
When you set a savepoint you define a logical rollback point within a transaction. If an error occurs
past a savepoint, you can use the rollback method to undo either all the changes or only the changes
made after the savepoint.
The Connection object has two new methods that help you manage savepoints:
1. setSavepoint,String savepointName/: defines a new savepoint. It also returns a Savepoint
object.
2. re$easeSavepoint,Savepoint savepointName/: deletes a savepoint. Notice that it requires
a Savepoint object as a parameter. This object is usually a savepoint generated by the
setSavepoint() method.
There is one ro$$"ac= , String savepointName / method which rolls back work to the specified
savepoint.
The following example illustrates the use of a Savepoint object:
try{
//0ssum! a vali# conn!ction obj!ct conn
conn.s!t0uto,ommit$fals!(*
%tat!m!nt stmt 9 conn.cr!at!%tat!m!nt$(*

//s!t a %av!point
%av!point sav!pointC 9 conn.s!t%av!point$)%av!pointC)(*
%tring %X1 9 )6=%37T 6=T? 3mploy!!s ) >
)B0153% $CEM2 @E2 '7ita'2 'T!/'()*
MAT SOFT
JAVA REFERENCE GUIDE
362
stmt.!:!cut!5p#at!$%X1(*
//%ubmit a malform!# %X1 stat!m!nt that br!a<s
%tring %X1 9 )6=%37T34 6= 3mploy!!s ) >
)B0153% $CEI2 @@2 '%ita'2 'T!/'()*
stmt.!:!cut!5p#at!$%X1(*
// 6f th!r! is no !rror2 commit th! chang!s.
conn.commit$(*
+catch$%X13:c!ption s!({
// 6f th!r! is any !rror.
conn.rollbac<$sav!pointC(*
+
In this case none of the abobe INSERT statement would success and everything would be rolled back.
Exception handling allows you to handle exceptional conditions such as program-defined errors in a
controlled fashion.
When an exception condition occurs, an exception is thrown. The term thrown means that current
program execution stops, and control is redirected to the nearest applicable catch clause. If no
applicable catch clause exists, then the program's execution ends.
JDBC Exception handling is very similar to Java Excpetion handling but for JDBC, the most common
exception you'll deal with is #ava1s;$1SJ07xception1
SQLException Methods:
A SQLException can occur both in the driver and the database. When such an exception occurs, an
object of type SQLException will be passed to the catch clause.
The passed SQLException object has the following methods available for retrieving additional
information about the exception:
Method )escription
getErrorCode( ) Gets the error number associated with the exception.
getMessage( ) Gets the JDBC driver's error message for an error handled
by the driver or gets the Oracle error number and
message for a database error.
getSQLState( ) Gets the XOPEN SQLstate string. For a JDBC driver error,
no useful information is returned from this method. For a
database error, the five-digit XOPEN SQLstate code is
returned. This method can return null.
getNextException( ) Gets the next Exception object in the exception chain.
MAT SOFT
JAVA REFERENCE GUIDE
363
printStackTrace( ) Prints the current exception, or throwable, and its
backtrace to a standard error stream.
printStackTrace(PrintStream s) Prints this throwable and its backtrace to the print stream
you specify.
printStackTrace(PrintWriter w) Prints this throwable and its backtrace to the print writer
you specify.
By utilizing the information available from the Exception object, you can catch an exception and
continue your program appropriately. Here is the general form of a try block:
try {
// Aour ris<y co#! go!s b!tw!!n th!s! curly brac!sGGG
+
catch$3:c!ption !:( {
// Aour !:c!ption han#ling co#! go!s b!tw!!n th!s!
// curly brac!s2 similar to th! !:c!ption claus!
// in a P1/%X1 bloc<.
+
finally {
// Aour must;always;b!;!:!cut!# co#! go!s b!tw!!n th!s!
// curly brac!s. 1i<! closing #atabas! conn!ction.
+
Example:
Study the following example code to understand the usage of try1111catch111fina$$y blocks.
//%T3P C. 6mport r!Puir!# pac<ag!s
import java.sPl.**
public class J4L,3:ampl! {
// J4L, #riv!r nam! an# #atabas! 571
static final %tring J4L,T476B37 9 )com.mysPl.j#bc.4riv!r)*
static final %tring 4LT571 9 )j#bc-mysPl-//localhost/3MP)*
// 4atabas! cr!#!ntials
static final %tring 5%37 9 )us!rnam!)*
static final %tring P0%% 9 )passwor#)*

public static voi# main$%tring&' args( {
,onn!ction conn 9 null*
try{
//%T3P @- 7!gist!r J4L, #riv!r
,lass.for=am!$)com.mysPl.j#bc.4riv!r)(*
//%T3P D- ?p!n a conn!ction
%yst!m.out.println$),onn!cting to #atabas!...)(*
conn 9 4riv!rManag!r.g!t,onn!ction$4LT57125%372P0%%(*
MAT SOFT
JAVA REFERENCE GUIDE
364
//%T3P F- 3:!cut! a Pu!ry
%yst!m.out.println$),r!ating stat!m!nt...)(*
%tat!m!nt stmt 9 conn.cr!at!%tat!m!nt$(*
%tring sPl*
sPl 9 )%313,T i#2 first2 last2 ag! F7?M 3mploy!!s)*
7!sult%!t rs 9 stmt.!:!cut!Xu!ry$sPl(*
//%T3P H- 3:tract #ata from r!sult s!t
whil!$rs.n!:t$(({
//7!tri!v! by column nam!
int i# 9 rs.g!t6nt$)i#)(*
int ag! 9 rs.g!t6nt$)ag!)(*
%tring first 9 rs.g!t%tring$)first)(*
%tring last 9 rs.g!t%tring$)last)(*
//4isplay valu!s
%yst!m.out.print$)64- ) > i#(*
%yst!m.out.print$)2 0g!- ) > ag!(*
%yst!m.out.print$)2 First- ) > first(*
%yst!m.out.println$)2 1ast- ) > last(*
+
//%T3P M- ,l!an;up !nvironm!nt
rs.clos!$(*
stmt.clos!$(*
conn.clos!$(*
+catch$%X13:c!ption s!({
//an#l! !rrors for J4L,
s!.print%tac<Trac!$(*
+catch$3:c!ption !({
//an#l! !rrors for ,lass.for=am!
!.print%tac<Trac!$(*
+finally{
//finally bloc< us!# to clos! r!sourc!s
try{
if$connG9null(
conn.clos!$(*
+catch$%X13:c!ption s!({
s!.print%tac<Trac!$(*
+//!n# finally try
+//!n# try
%yst!m.out.println$)8oo#by!G)(*
+//!n# main
+//!n# J4L,3:ampl!
Now let us compile above example as follows:
,-O.javac J4L,3:ampl!.java
,-O.
When you run J)BC7xamp$e, it produces following result if there is no problem, otherwise
corresponding error would be caught and error message would be displayed:
MAT SOFT
JAVA REFERENCE GUIDE
365
,-O.java J4L,3:ampl!
,onn!cting to #atabas!...
,r!ating stat!m!nt...
64- CEE2 0g!- CJ2 First- Vara2 1ast- 0li
64- CEC2 0g!- @H2 First- Mahna/2 1ast- Fatma
64- CE@2 0g!- DE2 First- Vai#2 1ast- Yhan
64- CED2 0g!- @J2 First- %umit2 1ast- Mittal
,-O.
Try above example by passing wrong database name or wrong username or password and check the
result.
BATCH PROCESSING
Batch Processing allows you to group related SQL statements into a batch and submit them with one
call to the database.
When you send several SQL statements to the database at once, you reduce the amount of
communication overhead, thereby improving performance.
JDBC drivers are not required to support this feature. You should use
the6atabase#eta6ata.supportsBatch8pdates() method to determine if the target database
supports batch update processing. The method returns true if your JDBC driver supports this
feature.
The addBatch,/ method of 2tatement3 Prepared2tatement3 and Callable2tatement is used to
add individual statements to the batch. The execteBatch,/ is used to start the execution of
all the statements grouped together.
The execteBatch,/ returns an array of integers, and each element of the array represents
the update count for the respective update statement.
Just as you can add statements to a batch for processing, you can remove them with
thec$earBatch,/ method. This method removes all the statements you added with the
addBatch() method. However, you cannot selectively choose which statement to remove.
Batching with Statement Object:
Here is a typical sequence of steps to use Batch Processing with Statment Object:
1. Create a Statement object using either create2tatement() methods.
2. Set auto-commit to false using set-utoCommit().
3. Add as many as SQL statements you like into batch using addBatch() method on created
statement object.
4. Execute all the SQL statements using executeBatch() method on created statement object.
5. Finally, commit all the changes using commit() method.
MAT SOFT
JAVA REFERENCE GUIDE
366
Example:
The following code snippet provides an example of a batch update using Statement object:
// ,r!at! stat!m!nt obj!ct
%tat!m!nt stmt 9 conn.cr!at!%tat!m!nt$(*
// %!t auto;commit to fals!
conn.s!t0uto,ommit$fals!(*
// ,r!at! %X1 stat!m!nt
%tring %X1 9 )6=%37T 6=T? 3mploy!!s $i#2 first2 last2 ag!( ) >
)B0153%$@EE2'Via'2 '0li'2 DE()*
// 0## abov! %X1 stat!m!nt in th! batch.
stmt.a##Latch$%X1(*
// ,r!at! on! mor! %X1 stat!m!nt
%tring %X1 9 )6=%37T 6=T? 3mploy!!s $i#2 first2 last2 ag!( ) >
)B0153%$@EC2'7aj'2 'Yumar'2 DH()*
// 0## abov! %X1 stat!m!nt in th! batch.
stmt.a##Latch$%X1(*
// ,r!at! on! mor! %X1 stat!m!nt
%tring %X1 9 )5P40T3 3mploy!!s %3T ag! 9 DH ) >
)"373 i# 9 CEE)*
// 0## abov! %X1 stat!m!nt in th! batch.
stmt.a##Latch$%X1(*
// ,r!at! an int&' to hol# r!turn!# valu!s
int&' count 9 stmt.!:!cut!Latch$(*
//3:plicitly commit stat!m!nts to apply chang!s
conn.commit$(*
Batching with PrepareStatement Object:
Here is a typical sequence of steps to use Batch Processing with PrepareStatement Object:
1. Create SQL statements with placeholders.
2. Create PrepareStatement object using either prepare2tatement() methods.
3. Set auto-commit to false using set-utoCommit().
4. Add as many as SQL statements you like into batch using addBatch() method on created
statement object.
5. Execute all the SQL statements using executeBatch() method on created statement object.
6. Finally, commit all the changes using commit() method.
The following code snippet provides an example of a batch update using PrepareStatement object:
MAT SOFT
JAVA REFERENCE GUIDE
367
// ,r!at! %X1 stat!m!nt
%tring %X1 9 )6=%37T 6=T? 3mploy!!s $i#2 first2 last2 ag!( ) >
)B0153%$S2 S2 S2 S()*
// ,r!at! Pr!par!%tat!m!nt obj!ct
Pr!par!#%tat!m!n pstmt 9 conn.pr!par!%tat!m!nt$%X1(*
//%!t auto;commit to fals!
conn.s!t0uto,ommit$fals!(*
// %!t th! variabl!s
pstmt.s!t6nt$ C2 FEE (*
pstmt.s!t%tring$ @2 )Pappu) (*
pstmt.s!t%tring$ D2 )%ingh) (*
pstmt.s!t6nt$ F2 DD (*
// 0## it to th! batch
pstmt.a##Latch$(*
// %!t th! variabl!s
pstmt.s!t6nt$ C2 FEC (*
pstmt.s!t%tring$ @2 )Pawan) (*
pstmt.s!t%tring$ D2 )%ingh) (*
pstmt.s!t6nt$ F2 DC (*
// 0## it to th! batch
pstmt.a##Latch$(*
//a## mor! batch!s
.
.
.
.
//,r!at! an int&' to hol# r!turn!# valu!s
int&' count 9 stmt.!:!cut!Latch$(*
//3:plicitly commit stat!m!nts to apply chang!s
conn.commit$(*
STREAMING DATA USING JDBC
A PreparedStatement object has the ability to use input and output streams to supply parameter data.
This enables you to place entire files into database columns that can hold large values, such as CLOB
and BLOB data types.
There are following methods which can be used to stream data:
1. set%sciiStream,/: This method is used to supply large ASCII values.
2. setCharacterStream,/: This method is used to supply large UNICODE values.
3. setBinaryStream,/: This method is used to supply large binary values.
MAT SOFT
JAVA REFERENCE GUIDE
368
The setXXXStream() method requires an extra parameter, the file size, besides the parameter
placeholder. This parameter informs the driver how much data should be sent to the database using
the stream.
Example
Consider we want to upload an XML file XML_Data.xml into a database table. Here is the content of
this XML file:
NS:ml v!rsion9)C.E)S.
N3mploy!!.
Ni#.CEEN/i#.
Nfirst.VaraN/first.
Nlast.0liN/last.
N%alary.CEEEEN/%alary.
N4ob.CJ;EJ;CKIJN/4ob.
N3mploy!!.
Keep this XML file in the same directory where you are going to run this example.
This example would create a database table XML_Data and then file XML_Data.xml would be uploaded
into this table.
Copy and past following example in JDBCExample.java, compile and run as follows:
// 6mport r!Puir!# pac<ag!s
import java.sPl.**
import java.io.**
import java.util.**
public class J4L,3:ampl! {
// J4L, #riv!r nam! an# #atabas! 571
static final %tring J4L,T476B37 9 )com.mysPl.j#bc.4riv!r)*
static final %tring 4LT571 9 )j#bc-mysPl-//localhost/3MP)*
// 4atabas! cr!#!ntials
static final %tring 5%37 9 )us!rnam!)*
static final %tring P0%% 9 )passwor#)*

public static voi# main$%tring&' args( {
,onn!ction conn 9 null*
Pr!par!#%tat!m!nt pstmt 9 null*
%tat!m!nt stmt 9 null*
7!sult%!t rs 9 null*
try{
// 7!gist!r J4L, #riv!r
,lass.for=am!$)com.mysPl.j#bc.4riv!r)(*
// ?p!n a conn!ction
%yst!m.out.println$),onn!cting to #atabas!...)(*
conn 9 4riv!rManag!r.g!t,onn!ction$4LT57125%372P0%%(*
MAT SOFT
JAVA REFERENCE GUIDE
369
//,r!at! a %tat!m!nt obj!ct an# buil# tabl!
stmt 9 conn.cr!at!%tat!m!nt$(*
cr!at!RM1Tabl!$stmt(*
//?p!n a Fil!6nput%tr!am
Fil! f 9 n!w Fil!$)RM1T4ata.:ml)(*
long fil!1!ngth 9 f.l!ngth$(*
Fil!6nput%tr!am fis 9 n!w Fil!6nput%tr!am$f(*
//,r!at! Pr!par!#%tat!m!nt an# str!am #ata
%tring %X1 9 )6=%37T 6=T? RM1T4ata B0153% $S2S()*
pstmt 9 conn.pr!par!%tat!m!nt$%X1(*
pstmt.s!t6nt$C2CEE(*
pstmt.s!t0scii%tr!am$@2fis2$int(fil!1!ngth(*
pstmt.!:!cut!$(*
//,los! input str!am
fis.clos!$(*
// 4o a Pu!ry to g!t th! row
%X1 9 )%313,T 4ata F7?M RM1T4ata "373 i#9CEE)*
rs 9 stmt.!:!cut!Xu!ry $%X1(*
// 8!t th! first row
if $rs.n!:t $(({
//7!tri!v! #ata from input str!am
6nput%tr!am :ml6nput%tr!am 9 rs.g!t0scii%tr!am $C(*
int c*
Lyt!0rray?utput%tr!am bos 9 n!w Lyt!0rray?utput%tr!am$(*
whil! $$ c 9 :ml6nput%tr!am.r!a# $(( G9 ;C(
bos.writ!$c(*
//Print r!sults
%yst!m.out.println$bos.to%tring$((*
+
// ,l!an;up !nvironm!nt
rs.clos!$(*
stmt.clos!$(*
pstmt.clos!$(*
conn.clos!$(*
+catch$%X13:c!ption s!({
//an#l! !rrors for J4L,
s!.print%tac<Trac!$(*
+catch$3:c!ption !({
//an#l! !rrors for ,lass.for=am!
!.print%tac<Trac!$(*
+finally{
//finally bloc< us!# to clos! r!sourc!s
try{
if$stmtG9null(
stmt.clos!$(*
+catch$%X13:c!ption s!@({
+// nothing w! can #o
try{
if$pstmtG9null(
pstmt.clos!$(*
+catch$%X13:c!ption s!@({
MAT SOFT
JAVA REFERENCE GUIDE
370
+// nothing w! can #o
try{
if$connG9null(
conn.clos!$(*
+catch$%X13:c!ption s!({
s!.print%tac<Trac!$(*
+//!n# finally try
+//!n# try
%yst!m.out.println$)8oo#by!G)(*
+//!n# main
public static voi# cr!at!RM1Tabl!$%tat!m!nt stmt(
throws %X13:c!ption{
%yst!m.out.println$),r!ating RM1T4ata tabl!...) (*
//,r!at! %X1 %tat!m!nt
%tring str!aming4ata%Pl 9 ),730T3 T0L13 RM1T4ata ) >
)$i# 6=T38372 4ata 1?=8()*
//4rop tabl! first if it !:ists.
try{
stmt.!:!cut!5p#at!$)47?P T0L13 RM1T4ata)(*
+catch$%X13:c!ption s!({
+// #o nothing
//Luil# tabl!.
stmt.!:!cut!5p#at!$str!aming4ata%Pl(*
+//!n# cr!at!RM1Tabl!
+//!n# J4L,3:ampl!
Now let us compile above example as follows:
,-O.javac J4L,3:ampl!.java
,-O.
When you run J)BC7xamp$e, it produces following result:
,-O.java J4L,3:ampl!
,onn!cting to #atabas!...
,r!ating RM1T4ata tabl!...
NS:ml v!rsion9)C.E)S.
N3mploy!!.
Ni#.CEEN/i#.
Nfirst.VaraN/first.
Nlast.0liN/last.
N%alary.CEEEEN/%alary.
N4ob.CJ;EJ;CKIJN/4ob.
N3mploy!!.
8oo#by!G
,-O.
//////////////////////////////////////////////////////////////////////
MAT SOFT
JAVA REFERENCE GUIDE
371
Day 35: JDBC based Swing Example
Day 36: Master Detailed Form Example
/////////////////////////////////////////////////////////////////////
Day 37: Web Application Development with Servlets
What are Servlets?
Java Servlets are programs that run on a Web or Application server and act as a middle layer between
a request coming from a Web browser or other HTTP client and databases or applications on the HTTP
server.
Using Servlets, you can collect input from users through web page forms, present records from a
database or another source, and create web pages dynamically.
Java Servlets often serve the same purpose as programs implemented using the Common Gateway
Interface (CGI). But Servlets offer several advantages in comparison with the CGI.
Performance is significantly better.
Servlets execute within the address space of a Web server. It is not necessary to create a
separate process to handle each client request.
Servlets are platform-independent because they are written in Java.
Java security manager on the server enforces a set of restrictions to protect the resources on
a server machine. So servlets are trusted.
The full functionality of the Java class libraries is available to a servlet. It can communicate
with applets, databases, or other software via the sockets and RMI mechanisms that you have
seen already.
Servlets Architecture:
Following diagram shows the position of Servelts in a Web Application.
MAT SOFT
JAVA REFERENCE GUIDE
372
Servlets Tasks:
Servlets perform the following major tasks:
1. Read the explicit data sent by the clients (browsers). This includes an HTML form on a Web
page or it could also come from an applet or a custom HTTP client program.
2. Read the implicit HTTP request data sent by the clients (browsers). This includes cookies,
media types and compression schemes the browser understands, and so forth.
3. Process the data and generate the results. This process may require talking to a database,
executing an RMI or CORBA call, invoking a Web service, or computing the response directly.
4. Send the explicit data (i.e., the document) to the clients (browsers). This document can be
sent in a variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc.
5. Send the implicit HTTP response to the clients (browsers). This includes telling the browsers or
other clients what type of document is being returned (e.g., HTML), setting cookies and
caching parameters, and other such tasks.
Servlets Packages:
Java Servlets are Java classes run by a web server that has an interpreter that supports the Java
Servlet specification.
Servlets can be created using the #avax1serv$et and #avax1serv$et1http packages, which are a
standard part of the Java's enterprise edition, an expanded version of the Java class library that
supports large-scale development projects. These classes implement the Java Servlet and JSP
specifications.
Java servlets have been created and compiled just like any other Java class. After you install the
servlet packages and add them to your computer's Classpath, you can compile servlets with the JDK's
Java compiler or any other current compiler.
Servlets - Environment Setup
A development environment is where you would develop your Sevrlet, test them and finally run them.
Like any other Java program, you need to compile a servlet by using the Java compiler #avacand after
compilation the servlet application, it would be deployed in a configured environment to test and run.
This development environment setup involves following steps:
Setting up Java Development Kit
This step involves downloading an implementation of the Java Software Development Kit (SDK) and
setting up PATH environment variable appropriately.
You can downloaded SDK from Oracle's Java site: Java SE Downloads.
MAT SOFT
JAVA REFERENCE GUIDE
373
Once you download your Java implementation, follow the given instructions to install and configure the
setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains
java and javac, typically java_install_dir/bin and java_install_dir respectively.
If you are running Windows and installed the SDK in C:\jdk1.5.0_20, you would put the following line
in your C:\autoexec.bat file.
s!t P0T9,-Oj#<C.H.ET@EObin*WP0TW
s!t J0B0T?M39,-Oj#<C.H.ET@E
Alternatively, on Windows NT/2000/XP, you could also right-click on My Computer, select Properties,
then Advanced, then Environment Variables. Then, you would update the PATH value and press the OK
button.
On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.5.0_20 and you use the C shell,
you would put the following into your .cshrc file.
s!t!nv P0T /usr/local/j#<C.H.ET@E/bin-UP0T
s!t!nv J0B0T?M3 /usr/local/j#<C.H.ET@E
Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse,
IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to confirm that the IDE knows
where you installed Java.
Setting up Web Server: Tomcat
A number of Web Servers that support servlets are available in the market. Some web servers are
freely downloadable and Tomcat is one of them.
Apache Tomcat is an open source software implementation of the Java Servlet and JavaServer Pages
technologies and can act as a standalone server for testing servlets and can be integrated with the
Apache Web Server. Here are the steps to setup Tomcat on your machine:
Download latest version of Tomcat from http://tomcat.apache.org/.
Once you downloaded the installation, unpack the binary distribution into a convenient
location. For example in C:\apache-tomcat-5.5.29 on windows, or /usr/local/apache-tomcat-
5.5.29 on Linux/Unix and create CATALINA_HOME environment variable pointing to these
locations.
Tomcat can be started by executing the following commands on windows machine:
W,0T016=0T?M3WObinOstartup.bat
or
,-Oapach!;tomcat;H.H.@KObinOstartup.bat
Tomcat can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine:
MAT SOFT
JAVA REFERENCE GUIDE
374
U,0T016=0T?M3/bin/startup.sh
or
/usr/local/apach!;tomcat;H.H.@K/bin/startup.sh
After startup, the default web applications included with Tomcat will be available by
visitinghttp:KK$oca$host:PIPIK. If everything is fine then it should display following result:
Further information about configuring and running Tomcat can be found in the documentation included
here, as well as on the Tomcat web site: http://tomcat.apache.org
Tomcat can be stopped by executing the following commands on windows machine:
,-Oapach!;tomcat;H.H.@KObinOshut#own
Tomcat can be stopped by executing the following commands on Unix (Solaris, Linux, etc.) machine:
/usr/local/apach!;tomcat;H.H.@K/bin/shut#own.sh
Setting up CLASSPATH
Since servlets are not part of the Java Platform, Standard Edition, you must identify the servlet classes
to the compiler.
MAT SOFT
JAVA REFERENCE GUIDE
375
If you are running Windows, you need to put the following lines in your C:\autoexec.bat file.
s!t ,0T016=09,-Oapach!;tomcat;H.H.@K
s!t ,10%%P0T9W,0T016=0WOcommonOlibOs!rvl!t;api.jar*W,10%%P0TW
Alternatively, on Windows NT/2000/XP, you could also right-click on My Computer, select Properties,
then Advanced, then Environment Variables. Then, you would update the CLASSPATH value and press
the OK button.
On Unix (Solaris, Linux, etc.), if you are using the C shell, you would put the following lines into
your .cshrc file.
s!t!nv ,0T016=09/usr/local/apach!;tomcat;H.H.@K
s!t!nv ,10%%P0T U,0T016=0/common/lib/s!rvl!t;api.jar-U,10%%P0T
N!T7: Assuming that your development directory is C:\ServletDevel (Windows) or /usr/ServletDevel
(Unix) then you would need to add these directories as well in CLASSPATH in similar way as you have
added above.
MAT SOFT
JAVA REFERENCE GUIDE
376
Day 38: Servlets - Life Cycle
A servlet life cycle can be defined as the entire process from its creation till the destruction. The
following are the paths followed by a servlet
The servlet is initialized by calling the init ,/ method.
The servlet calls service,/ method to process a client's request.
The servlet is terminated by calling the destroy,/ method.
Finally, servlet is garbage collected by the garbage collector of the JVM.
Now let us discuss the life cycle methods in details.
The init() method :
The init method is designed to be called only once. It is called when the servlet is first created, and
not called again for each user request. So, it is used for one-time initializations, just as with the init
method of applets.
The servlet is normally created when a user first invokes a URL corresponding to the servlet, but you
can also specify that the servlet be loaded when the server is first started.
When a user invokes a servlet, a single instance of each servlet gets created, with each user request
resulting in a new thread that is handed off to doGet or doPost as appropriate. The init() method
simply creates or loads some data that will be used throughout the life of the servlet.
The init method definition looks like this:
public voi# init$( throws %!rvl!t3:c!ption {
// 6nitiali/ation co#!...
+
The service() method :
The service() method is the main method to perform the actual task. The servlet container (i.e. web
server) calls the service() method to handle requests coming from the client( browsers) and to write
the formatted response back to the client.
MAT SOFT
JAVA REFERENCE GUIDE
377
Each time the server receives a request for a servlet, the server spawns a new thread and calls
service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls
doGet, doPost, doPut, doDelete, etc. methods as appropriate.
Here is the signature of this method:
public voi# s!rvic!$%!rvl!t7!Pu!st r!Pu!st2
%!rvl!t7!spons! r!spons!(
throws %!rvl!t3:c!ption2 6?3:c!ption{
+
The service () method is called by the container and service method invokes doGe, doPost, doPut,
doDelete, etc. methods as appropriate. So you have nothing to do with service() method but you
override either doGet() or doPost() depending on what type of request you receive from the client.
The doGet() and doPost() are most frequently used methods with in each service request. Here are
the signature of these two methods.
The doGet() Method
A GET request results from a normal request for a URL or from an HTML form that has no METHOD
specified and it should be handled by doGet() method.
public voi# #o8!t$ttp%!rvl!t7!Pu!st r!Pu!st2
ttp%!rvl!t7!spons! r!spons!(
throws %!rvl!t3:c!ption2 6?3:c!ption {
// %!rvl!t co#!
+
The doPost() Method
A POST request results from an HTML form that specifically lists POST as the METHOD and it should be
handled by doPost() method.
public voi# #oPost$ttp%!rvl!t7!Pu!st r!Pu!st2
ttp%!rvl!t7!spons! r!spons!(
throws %!rvl!t3:c!ption2 6?3:c!ption {
// %!rvl!t co#!
+
The destroy() method :
The destroy() method is called only once at the end of the life cycle of a servlet. This method gives
your servlet a chance to close database connections, halt background threads, write cookie lists or hit
counts to disk, and perform other such cleanup activities.
After the destroy() method is called, the servlet object is marked for garbage collection. The destroy
method definition looks like this:
MAT SOFT
JAVA REFERENCE GUIDE
378
public voi# #!stroy$( {
// Finali/ation co#!...
+
Architecture Digram:
The following figure depicts a typical servlet life-cycle scenario.
First the HTTP requests coming to the server are delegated to the servlet container.
The servlet container loads the servlet before invoking the service() method.
Then the servlet container handles multiple requests by spawning multiple threads, each
thread executing the service() method of a single instance of the servlet.
Servlets are Java classes which service HTTP requests and implement
the#avax1serv$et1Serv$et interface. Web application developers typically write servlets that extend
javax.servlet.http.HttpServlet, an abstract class that implements the Servlet interface and is specially
designed to handle HTTP requests.
Sample Code for Hello World:
Following is the sample source code structure of a servlet example to write Hello World:
// 6mport r!Puir!# java librari!s
MAT SOFT
JAVA REFERENCE GUIDE
379
import java.io.**
import java:.s!rvl!t.**
import java:.s!rvl!t.http.**
// 3:t!n# ttp%!rvl!t class
public class !llo"orl# !:t!n#s ttp%!rvl!t {

privat! %tring m!ssag!*
public voi# init$( throws %!rvl!t3:c!ption
{
// 4o r!Puir!# initiali/ation
m!ssag! 9 )!llo "orl#)*
+
public voi# #o8!t$ttp%!rvl!t7!Pu!st r!Pu!st2
ttp%!rvl!t7!spons! r!spons!(
throws %!rvl!t3:c!ption2 6?3:c!ption
{
// %!t r!spons! cont!nt typ!
r!spons!.s!t,ont!ntTyp!$)t!:t/html)(*
// 0ctual logic go!s h!r!.
Print"rit!r out 9 r!spons!.g!t"rit!r$(*
out.println$)NhC.) > m!ssag! > )N/hC.)(*
+

public voi# #!stroy$(
{
// #o nothing.
+
+
Compiling a Servlet:
Let us put above code if HelloWorld.java file and put this file in C:\ServletDevel (Windows) or
/usr/ServletDevel (Unix) then you would need to add these directories as well in CLASSPATH.
Assuming your environment is setup properly, go in Serv$et)eve$ directory and compile
HelloWorld.java as follows:
U javac !llo"orl#.java
If the servlet depends on any other libraries, you have to include those JAR files on your CLASSPATH
as well. I have included only servlet-api.jar JAR file because I'm not using any other library in Hello
World program.
This command line uses the built-in javac compiler that comes with the Sun Microsystems Java
Software Development Kit (JDK). For this command to work properly, you have to include the location
of the Java SDK that you are using in the PATH environment variable.
MAT SOFT
JAVA REFERENCE GUIDE
380
If everything goes fine, above compilation would produce (e$$o9or$d1c$ass file in the same directory.
Next section would explain how a compiled servlet would be deployed in production.
Servlet Deployment:
By default, a servlet application is located at the path <Tomcat-installation-directory>/webapps/ROOT
and the class file would reside in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/classes.
If you have a fully qualified class name of com1myorg1MyServ$et, then this servlet class must be
located in WEB-INF/classes/com/myorg/MyServlet.class.
For now, let us copy HelloWorld.class into <Tomcat-installation-directory>/webapps/ROOT/WEB-
INF/classes and create following entries in 3e"1xm$ file located in <Tomcat-installation-
directory>/webapps/ROOT/WEB-INF/
Ns!rvl!t.
Ns!rvl!t;nam!.!llo"orl#N/s!rvl!t;nam!.
Ns!rvl!t;class.!llo"orl#N/s!rvl!t;class.
N/s!rvl!t.
Ns!rvl!t;mapping.
Ns!rvl!t;nam!.!llo"orl#N/s!rvl!t;nam!.
Nurl;patt!rn./!llo"orl#N/url;patt!rn.
N/s!rvl!t;mapping.
Above entries to be created inside <web-app>...</web-app> tags available in web.xml file. There
could be various entries in this table already available, but never mind.
You are almost done, now let us start tomcat server using <Tomcat-installation-
directory>\bin\startup.bat (on windows) or <Tomcat-installation-directory>/bin/startup.sh (on
Linux/Solaris etc.) and finally type http:KK$oca$host:PIPIK(e$$o9or$d in browser's address box. If
everything goes fine, you would get following result:
MAT SOFT
JAVA REFERENCE GUIDE
381
Servlets - Form Data
You must have come across many situations when you need to pass some information from your
browser to web server and ultimately to your backend program. The browser uses two methods to
pass this information to web server. These methods are GET Method and POST Method.
GET method:
The GET method sends the encoded user information appended to the page request. The page and the
encoded information are separated by the ? character as follows:
http-//www.t!st.com/h!lloS<!yC9valu!C[<!y@9valu!@
The GET method is the defualt method to pass information from browser to web server and it
produces a long string that appears in your browser's Location:box. Never use the GET method if you
have password or other sensitive information to pass to the server. The GET method has size
limtation: only 1024 characters can be in a request string.
This information is passed using QUERY_STRING header and will be accessible through
QUERY_STRING environment variable and Servlet handles this type of requests
using do?et,/method.
POST method:
A generally more reliable method of passing information to a backend program is the POST method.
This packages the information in exactly the same way as GET methods, but instead of sending it as a
text string after a ? in the URL it sends it as a separate message. This message comes to the backend
program in the form of the standard input which you can parse and use for your processing. Servlet
handles this type of requests using doPost,/ method.
Day 39: Reading Form Data using Servlet:
Servlets handles form data parsing automatically using the following methods depending on the
situation:
getParameter,/: You call request.getParameter() method to get the value of a form
parameter.
getParameter*a$es,/: Call this method if the parameter appears more than once and
returns multiple values, for example checkbox.
getParameterNames,/: Call this method if you want a complete list of all parameters in the
current request.
GET Method Example Using URL:
MAT SOFT
JAVA REFERENCE GUIDE
382
Here is a simple URL which will pass two values to HelloForm program using GET method.
http:KK$oca$host:PIPIK(e$$o+ormMfirstGnameQ@%'%:$astGnameQ%0I
Below is (e$$o+orm1#ava servlet program to handle input given by web browser. We are going to
use getParameter,/ method which makes it very easy to access passed information:
// 6mport r!Puir!# java librari!s
import java.io.**
import java:.s!rvl!t.**
import java:.s!rvl!t.http.**
// 3:t!n# ttp%!rvl!t class
public class !lloForm !:t!n#s ttp%!rvl!t {

public voi# #o8!t$ttp%!rvl!t7!Pu!st r!Pu!st2
ttp%!rvl!t7!spons! r!spons!(
throws %!rvl!t3:c!ption2 6?3:c!ption
{
// %!t r!spons! cont!nt typ!
r!spons!.s!t,ont!ntTyp!$)t!:t/html)(*
Print"rit!r out 9 r!spons!.g!t"rit!r$(*
%tring titl! 9 )5sing 83T M!tho# to 7!a# Form 4ata)*
%tring #ocTyp! 9
)NG#octyp! html public O);//wDc//#t# html F.E ) >
)transitional//!nO).On)*
out.println$#ocTyp! >
)Nhtml.On) >
)Nh!a#.Ntitl!.) > titl! > )N/titl!.N/h!a#.On) >
)Nbo#y bgcolor9O)^fEfEfEO).On) >
)NhC align9O)c!nt!rO).) > titl! > )N/hC.On) >
)Nul.On) >
) Nli.Nb.First =am!N/b.- )
> r!Pu!st.g!tParam!t!r$)firstTnam!)( > )On) >
) Nli.Nb.1ast =am!N/b.- )
> r!Pu!st.g!tParam!t!r$)lastTnam!)( > )On) >
)N/ul.On) >
)N/bo#y.N/html.)(*
+
+
Assuming your environment is setup properly, compile HelloForm.java as follows:
U javac !lloForm.java
If everything goes fine, above compilation would produce (e$$o+orm1c$ass file. Next you would have
to copy this class file in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/classes and create
following entries in 3e"1xm$ file located in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/
Ns!rvl!t.
Ns!rvl!t;nam!.!lloFormN/s!rvl!t;nam!.
MAT SOFT
JAVA REFERENCE GUIDE
383
Ns!rvl!t;class.!lloFormN/s!rvl!t;class.
N/s!rvl!t.
Ns!rvl!t;mapping.
Ns!rvl!t;nam!.!lloFormN/s!rvl!t;nam!.
Nurl;patt!rn./!lloFormN/url;patt!rn.
N/s!rvl!t;mapping.
Now type http%@@localhost%ABAB@)ello'ormC$irst1nameD>-.-Elast1nameD-L5 in your browser's
Location:box and make sure you already started tomcat server, before firing above command in the
browser. This would generate following result:
Using GET Method to Read Form Data
+irst Name: ZARA
0ast Name: ALI
GET Method Example Using Form:
Here is a simple example which passes two values using HTML FORM and submit button. We are going
to use same Servlet HelloForm to handle this imput.
Nhtml.
Nbo#y.
Nform action9)!lloForm) m!tho#9)83T).
First =am!- Ninput typ!9)t!:t) nam!9)firstTnam!).
Nbr /.
1ast =am!- Ninput typ!9)t!:t) nam!9)lastTnam!) /.
Ninput typ!9)submit) valu!9)%ubmit) /.
N/form.
N/bo#y.
N/html.
Keep this HTML in a file Hello.htm and put it in <Tomcat-installation-directory>/webapps/ROOT
directory. When you would access http%@@localhost%ABAB@)ello.htm, here is the actual output of the
above form.
First Name:
Last Name:
Try to enter First Name and Last Name and then click submit button to see the result on your local
machine where tomcat is running. Based on the input provided, it will generate similar result as
mentioned in the above example.
MAT SOFT
JAVA REFERENCE GUIDE
384
POST Method Example Using Form:
Let us do little modification in the above servlet, so that it can handle GET as well as POST methods.
Below is (e$$o+orm1#ava servlet program to handle input given by web browser using GET or POST
methods.
// 6mport r!Puir!# java librari!s
import java.io.**
import java:.s!rvl!t.**
import java:.s!rvl!t.http.**
// 3:t!n# ttp%!rvl!t class
public class !lloForm !:t!n#s ttp%!rvl!t {

// M!tho# to han#l! 83T m!tho# r!Pu!st.
public voi# #o8!t$ttp%!rvl!t7!Pu!st r!Pu!st2
ttp%!rvl!t7!spons! r!spons!(
throws %!rvl!t3:c!ption2 6?3:c!ption
{
// %!t r!spons! cont!nt typ!
r!spons!.s!t,ont!ntTyp!$)t!:t/html)(*
Print"rit!r out 9 r!spons!.g!t"rit!r$(*
%tring titl! 9 )5sing 83T M!tho# to 7!a# Form 4ata)*
%tring #ocTyp! 9
)NG#octyp! html public O);//wDc//#t# html F.E ) >
)transitional//!nO).On)*
out.println$#ocTyp! >
)Nhtml.On) >
)Nh!a#.Ntitl!.) > titl! > )N/titl!.N/h!a#.On) >
)Nbo#y bgcolor9O)^fEfEfEO).On) >
)NhC align9O)c!nt!rO).) > titl! > )N/hC.On) >
)Nul.On) >
) Nli.Nb.First =am!N/b.- )
> r!Pu!st.g!tParam!t!r$)firstTnam!)( > )On) >
) Nli.Nb.1ast =am!N/b.- )
> r!Pu!st.g!tParam!t!r$)lastTnam!)( > )On) >
)N/ul.On) >
)N/bo#y.N/html.)(*
+
// M!tho# to han#l! P?%T m!tho# r!Pu!st.
public voi# #oPost$ttp%!rvl!t7!Pu!st r!Pu!st2
ttp%!rvl!t7!spons! r!spons!(
throws %!rvl!t3:c!ption2 6?3:c!ption {
#o8!t$r!Pu!st2 r!spons!(*
+
+
Now compile, deploy the above Servlet and test it using Hello.htm with the POST method as follows:
Nhtml.
Nbo#y.
MAT SOFT
JAVA REFERENCE GUIDE
385
Nform action9)!lloForm) m!tho#9)P?%T).
First =am!- Ninput typ!9)t!:t) nam!9)firstTnam!).
Nbr /.
1ast =am!- Ninput typ!9)t!:t) nam!9)lastTnam!) /.
Ninput typ!9)submit) valu!9)%ubmit) /.
N/form.
N/bo#y.
N/html.
Here is the actual output of the above form, Try to enter First and Last Name and then click submit
button to see the result on your local machine where tomcat is running.
First Name:
Last Name:
Based on the input provided, it would generate similar result as mentioned in the above examples.
Passing Checkbox Data to Servlet Program
Checkboxes are used when more than one option is required to be selected.
Here is example HTML code, CheckBox.htm, for a form with two checkboxes
Nhtml.
Nbo#y.
Nform action9),h!c<Lo:) m!tho#9)P?%T) targ!t9)Tblan<).
Ninput typ!9)ch!c<bo:) nam!9)maths) ch!c<!#9)ch!c<!#) /. Maths
Ninput typ!9)ch!c<bo:) nam!9)physics) /. Physics
Ninput typ!9)ch!c<bo:) nam!9)ch!mistry) ch!c<!#9)ch!c<!#) /.
,h!mistry
Ninput typ!9)submit) valu!9)%!l!ct %ubj!ct) /.
N/form.
N/bo#y.
N/html.
The result of this code is the following form
Maths Physics Chemistry
Below is CheckBox.java servlet program to handle input given by web browser for checkbox button.
// 6mport r!Puir!# java librari!s
import java.io.**
import java:.s!rvl!t.**
import java:.s!rvl!t.http.**
MAT SOFT
JAVA REFERENCE GUIDE
386
// 3:t!n# ttp%!rvl!t class
public class ,h!c<Lo: !:t!n#s ttp%!rvl!t {

// M!tho# to han#l! 83T m!tho# r!Pu!st.
public voi# #o8!t$ttp%!rvl!t7!Pu!st r!Pu!st2
ttp%!rvl!t7!spons! r!spons!(
throws %!rvl!t3:c!ption2 6?3:c!ption
{
// %!t r!spons! cont!nt typ!
r!spons!.s!t,ont!ntTyp!$)t!:t/html)(*
Print"rit!r out 9 r!spons!.g!t"rit!r$(*
%tring titl! 9 )7!a#ing ,h!c<bo: 4ata)*
%tring #ocTyp! 9
)NG#octyp! html public O);//wDc//#t# html F.E ) >
)transitional//!nO).On)*
out.println$#ocTyp! >
)Nhtml.On) >
)Nh!a#.Ntitl!.) > titl! > )N/titl!.N/h!a#.On) >
)Nbo#y bgcolor9O)^fEfEfEO).On) >
)NhC align9O)c!nt!rO).) > titl! > )N/hC.On) >
)Nul.On) >
) Nli.Nb.Maths Flag - N/b.- )
> r!Pu!st.g!tParam!t!r$)maths)( > )On) >
) Nli.Nb.Physics Flag- N/b.- )
> r!Pu!st.g!tParam!t!r$)physics)( > )On) >
) Nli.Nb.,h!mistry Flag- N/b.- )
> r!Pu!st.g!tParam!t!r$)ch!mistry)( > )On) >
)N/ul.On) >
)N/bo#y.N/html.)(*
+
// M!tho# to han#l! P?%T m!tho# r!Pu!st.
public voi# #oPost$ttp%!rvl!t7!Pu!st r!Pu!st2
ttp%!rvl!t7!spons! r!spons!(
throws %!rvl!t3:c!ption2 6?3:c!ption {
#o8!t$r!Pu!st2 r!spons!(*
+
+
For the above example, it would display following result:
Reading Checkbox Data
Maths +$ag : : on
Physics +$ag: : null
Chemistry +$ag: : on
Reading All Form Parameters:
MAT SOFT
JAVA REFERENCE GUIDE
387
Following is the generic example which uses getParameterNames,/ method of HttpServletRequest
to read all the available form parameters. This method returns an Enumeration that contains the
parameter names in an unspecified order.
Once we have an Enumeration, we can loop down the Enumeration in the standard manner,
using has#ore=lements() method to determine when to stop and using next=lement() method to get
each parameter name.
// 6mport r!Puir!# java librari!s
import java.io.**
import java:.s!rvl!t.**
import java:.s!rvl!t.http.**
import java.util.**
// 3:t!n# ttp%!rvl!t class
public class 7!a#Params !:t!n#s ttp%!rvl!t {

// M!tho# to han#l! 83T m!tho# r!Pu!st.
public voi# #o8!t$ttp%!rvl!t7!Pu!st r!Pu!st2
ttp%!rvl!t7!spons! r!spons!(
throws %!rvl!t3:c!ption2 6?3:c!ption
{
// %!t r!spons! cont!nt typ!
r!spons!.s!t,ont!ntTyp!$)t!:t/html)(*
Print"rit!r out 9 r!spons!.g!t"rit!r$(*
%tring titl! 9 )7!a#ing 0ll Form Param!t!rs)*
%tring #ocTyp! 9
)NG#octyp! html public O);//wDc//#t# html F.E ) >
)transitional//!nO).On)*
out.println$#ocTyp! >
)Nhtml.On) >
)Nh!a#.Ntitl!.) > titl! > )N/titl!.N/h!a#.On) >
)Nbo#y bgcolor9O)^fEfEfEO).On) >
)NhC align9O)c!nt!rO).) > titl! > )N/hC.On) >
)Ntabl! wi#th9O)CEEWO) bor#!r9O)CO) align9O)c!nt!rO).On) >
)Ntr bgcolor9O)^KFKFKFO).On) >
)Nth.Param =am!N/th.Nth.Param Balu!$s(N/th.On)>
)N/tr.On)(*
3num!ration param=am!s 9 r!Pu!st.g!tParam!t!r=am!s$(*

whil!$param=am!s.hasMor!3l!m!nts$(( {
%tring param=am! 9 $%tring(param=am!s.n!:t3l!m!nt$(*
out.print$)Ntr.Nt#.) > param=am! > )N/t#.OnNt#.)(*
%tring&' paramBalu!s 9
r!Pu!st.g!tParam!t!rBalu!s$param=am!(*
// 7!a# singl! valu!# #ata
if $paramBalu!s.l!ngth 99 C( {
%tring paramBalu! 9 paramBalu!s&E'*
if $paramBalu!.l!ngth$( 99 E(
out.println$)Ni.=o Balu!N/i.)(*
!ls!
out.println$paramBalu!(*
+ !ls! {
MAT SOFT
JAVA REFERENCE GUIDE
388
// 7!a# multipl! valu!# #ata
out.println$)Nul.)(*
for$int i9E* i N paramBalu!s.l!ngth* i>>( {
out.println$)Nli.) > paramBalu!s&i'(*
+
out.println$)N/ul.)(*
+
+
out.println$)N/tr.OnN/tabl!.OnN/bo#y.N/html.)(*
+
// M!tho# to han#l! P?%T m!tho# r!Pu!st.
public voi# #oPost$ttp%!rvl!t7!Pu!st r!Pu!st2
ttp%!rvl!t7!spons! r!spons!(
throws %!rvl!t3:c!ption2 6?3:c!ption {
#o8!t$r!Pu!st2 r!spons!(*
+
+
Now, try above servlet with the following form:
Nhtml.
Nbo#y.
Nform action9)7!a#Params) m!tho#9)P?%T) targ!t9)Tblan<).
Ninput typ!9)ch!c<bo:) nam!9)maths) ch!c<!#9)ch!c<!#) /. Maths
Ninput typ!9)ch!c<bo:) nam!9)physics) /. Physics
Ninput typ!9)ch!c<bo:) nam!9)ch!mistry) ch!c<!#9)ch!c<!#) /. ,h!m
Ninput typ!9)submit) valu!9)%!l!ct %ubj!ct) /.
N/form.
N/bo#y.
N/html.
Now calling servlet using above form would generate following result:
Reading All Form Parameters
Param Name Param *a$e,s/
maths on
chemistry on
You can try above servlet to read any other form's data which is having other objects like text box,
radio button or drop down box etc.
Servlets - Client HTTP Request
When a browser requests for a web page, it sends lot of information to the web server which can not
be read directly because this information travel as a part of header of HTTP request. You can
check HTTP Protocol for more information on this.
Following is the important header information which comes from browser side and you would use very
frequently in web programming:
MAT SOFT
JAVA REFERENCE GUIDE
389
(eader )escription
Accept This header specifies the MIME types that the browser or other clients
can handle. Values of imageKpng or imageK#peg are the two most
common possibilities.
Accept-Charset This header specifies the character sets the browser can use to display
the information. For example ISO-8859-1.
Accept-Encoding This header specifies the types of encodings that the browser knows
how to handle. Values of g2ip or compress are the two most common
possibilities.
Accept-Language This header specifies the client's preferred languages in case the
servlet can produce results in more than one language. For example
en, en-us, ru, etc.
Authorization This header is used by clients to identify themselves when accessing
password-protected Web pages.
Connection This header indicates whether the client can handle persistent HTTP
connections. Persistent connections permit the client or other browser
to retrieve multiple files with a single request. A value of 6eep&
%$ive means that persistent connections should be used
Content-Length This header is applicable only to POST requests and gives the size of
the POST data in bytes.
Cookie This header returns cookies to servers that previously sent them to the
browser.
Host This header specifies the host and port as given in the original URL.
If-Modified-Since This header indicates that the client wants the page only if it has been
changed after the specified date. The server sends a code, 304 which
means Not Modified header if no newer result is available.
If-Unmodified-Since This header is the reverse of If-Modified-Since; it specifies that the
operation should succeed only if the document is older than the
specified date.
Referer This header indicates the URL of the referring Web page. For example,
if you are at Web page 1 and click on a link to Web page 2, the URL of
Web page 1 is included in the Referer header when the browser
requests Web page 2.
User-Agent This header identifies the browser or other client making the request
and can be used to return different content to different types of
browsers.
Methods to read HTTP Header:
There are following methods which can be used to read HTTP header in your servlet program. These
method are available with )ttp2er!let.e4uest object.
S1N1 Method : )escription
1 Coo=ie-. getCoo=ies,/
MAT SOFT
JAVA REFERENCE GUIDE
390
Returns an array containing all of the Cookie objects the client sent with this request.
2 7nmeration get%ttri"teNames,/
Returns an Enumeration containing the names of the attributes available to this request.
3 7nmeration get(eaderNames,/
Returns an enumeration of all the header names this request contains.
4 7nmeration getParameterNames,/
Returns an Enumeration of String objects containing the names of the parameters contained in
this request.
5 (ttpSession getSession,/
Returns the current session associated with this request, or if the request does not have a
session, creates one.
6 (ttpSession getSession,"oo$ean create/
Returns the current HttpSession associated with this request or, if if there is no current session
and create is true, returns a new session.
7 0oca$e get0oca$e,/
Returns the preferred Locale that the client will accept content in, based on the Accept-
Language header
8 !"#ect get%ttri"te,String name/
Returns the value of the named attribute as an Object, or null if no attribute of the given name
exists.
9 Serv$etInptStream getInptStream,/
Retrieves the body of the request as binary data using a ServletInputStream.
10 String get%thType,/
Returns the name of the authentication scheme used to protect the servlet, for example,
"BASIC" or "SSL," or null if the JSP was not protected
11 String getCharacter7ncoding,/
Returns the name of the character encoding used in the body of this request.
12 String getContentType,/
Returns the MIME type of the body of the request, or null if the type is not known.
13 String getContextPath,/
Returns the portion of the request URI that indicates the context of the request.
14 String get(eader,String name/
Returns the value of the specified request header as a String.
15 String getMethod,/
Returns the name of the HTTP method with which this request was made, for example, GET,
POST, or PUT.
16 String getParameter,String name/
Returns the value of a request parameter as a String, or null if the parameter does not exist.
17 String getPathInfo,/
Returns any extra path information associated with the URL the client sent when it made this
request.
18 String getProtoco$,/
Returns the name and version of the protocol the request.
MAT SOFT
JAVA REFERENCE GUIDE
391
19 String getJeryString,/
Returns the query string that is contained in the request URL after the path.
20 String get'emote%ddr,/
Returns the Internet Protocol (IP) address of the client that sent the request.
21 String get'emote(ost,/
Returns the fully qualified name of the client that sent the request.
22 String get'emoteBser,/
Returns the login of the user making this request, if the user has been authenticated, or null if
the user has not been authenticated.
23 String get'e;estB'I,/
Returns the part of this request's URL from the protocol name up to the query string in the first
line of the HTTP request.
24 String get'e;estedSessionId,/
Returns the session ID specified by the client.
25 String getServ$etPath,/
Returns the part of this request's URL that calls the JSP.
26 String-. getParameter*a$es,String name/
Returns an array of String objects containing all of the values the given request parameter has,
or null if the parameter does not exist.
27 "oo$ean isSecre,/
Returns a boolean indicating whether this request was made using a secure channel, such as
HTTPS.
28 int getContent0ength,/
Returns the length, in bytes, of the request body and made available by the input stream, or -1
if the length is not known.
29 int getInt(eader,String name/
Returns the value of the specified request header as an int.
30 int getServerPort,/
Returns the port number on which this request was received.
HTTP Header Request Example:
Following is the example which uses get(eaderNames,/ method of HttpServletRequest to read the
HTTP header infromation. This method returns an Enumeration that contains the header information
associated with the current HTTP request.
Once we have an Enumeration, we can loop down the Enumeration in the standard manner,
using has#ore=lements() method to determine when to stop and using next=lement() method to get
each parameter name.
// 6mport r!Puir!# java librari!s
import java.io.**
import java:.s!rvl!t.**
import java:.s!rvl!t.http.**
import java.util.**

MAT SOFT
JAVA REFERENCE GUIDE
392
// 3:t!n# ttp%!rvl!t class
public class 4isplay!a#!r !:t!n#s ttp%!rvl!t {

// M!tho# to han#l! 83T m!tho# r!Pu!st.
public voi# #o8!t$ttp%!rvl!t7!Pu!st r!Pu!st2
ttp%!rvl!t7!spons! r!spons!(
throws %!rvl!t3:c!ption2 6?3:c!ption
{
// %!t r!spons! cont!nt typ!
r!spons!.s!t,ont!ntTyp!$)t!:t/html)(*

Print"rit!r out 9 r!spons!.g!t"rit!r$(*
%tring titl! 9 )TTP !a#!r 7!Pu!st 3:ampl!)*
%tring #ocTyp! 9
)NG#octyp! html public O);//wDc//#t# html F.E ) >
)transitional//!nO).On)*
out.println$#ocTyp! >
)Nhtml.On) >
)Nh!a#.Ntitl!.) > titl! > )N/titl!.N/h!a#.On)>
)Nbo#y bgcolor9O)^fEfEfEO).On) >
)NhC align9O)c!nt!rO).) > titl! > )N/hC.On) >
)Ntabl! wi#th9O)CEEWO) bor#!r9O)CO) align9O)c!nt!rO).On) >
)Ntr bgcolor9O)^KFKFKFO).On) >
)Nth.!a#!r =am!N/th.Nth.!a#!r Balu!$s(N/th.On)>
)N/tr.On)(*

3num!ration h!a#!r=am!s 9 r!Pu!st.g!t!a#!r=am!s$(*

whil!$h!a#!r=am!s.hasMor!3l!m!nts$(( {
%tring param=am! 9 $%tring(h!a#!r=am!s.n!:t3l!m!nt$(*
out.print$)Ntr.Nt#.) > param=am! > )N/t#.On)(*
%tring paramBalu! 9 r!Pu!st.g!t!a#!r$param=am!(*
out.println$)Nt#. ) > paramBalu! > )N/t#.N/tr.On)(*
+
out.println$)N/tabl!.OnN/bo#y.N/html.)(*
+
// M!tho# to han#l! P?%T m!tho# r!Pu!st.
public voi# #oPost$ttp%!rvl!t7!Pu!st r!Pu!st2
ttp%!rvl!t7!spons! r!spons!(
throws %!rvl!t3:c!ption2 6?3:c!ption {
#o8!t$r!Pu!st2 r!spons!(*
+
+
Now calling the above servlet would generate following result:
HTTP Header Request Example
(eader Name (eader *a$e,s/
accept */*
accept-language en-us
user-agent Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0;
InfoPath.2; MS-RTC LM 8)
accept-encoding gzip, deflate
MAT SOFT
JAVA REFERENCE GUIDE
393
host localhost:8080
connection Keep-Alive
cache-control no-cache
Servlets - Server HTTP Response
As discussed in previous chapter, when a Web server responds to a HTTP request to the browser, the
response typically consists of a status line, some response headers, a blank line, and the document. A
typical response looks like this:
TTP/C.C @EE ?Y
,ont!nt;Typ!- t!:t/html
!a#!r@- ...
...
!a#!r=- ...
$Llan< 1in!(
NG#octyp! ....
Nhtml.
Nh!a#....N/h!a#.
Nbo#y.
...
N/bo#y.
N/html.
The status line consists of the HTTP version (HTTP/1.1 in the example), a status code (200 in the
example), and a very short message corresponding to the status code (OK in the example).
Following is a summary of the most useful HTTP 1.1 response headers which go back to the browser
from web server side and you would use them very frequently in web programming:
(eader )escription
Allow This header specifies the request methods (GET, POST, etc.) that the
server supports.
Cache-Control This header specifies the circumstances in which the response
document can safely be cached. It can have values p"$ic<
private or no&cache etc. Public means document is cacheable, Private
means document is for a single user and can only be stored in private
(nonshared) caches and no-cache means document should never be
cached.
Connection This header instructs the browser whether to use persistent in HTTP
connections or not. A value of c$ose instructs the browser not to use
persistent HTTP connections and =eep&a$ive means using persistent
connections.
Content-Disposition This header lets you request that the browser ask the user to save the
response to disk in a file of the given name.
MAT SOFT
JAVA REFERENCE GUIDE
394
Content-Encoding This header specifies the way in which the page was encoded during
transmission.
Content-Language This header signifies the language in which the document is written.
For example en, en-us, ru, etc.
Content-Length This header indicates the number of bytes in the response. This
information is needed only if the browser is using a persistent (keep-
alive) HTTP connection.
Content-Type This header gives the MIME (Multipurpose Internet Mail Extension) type
of the response document.
Expires This header specifies the time at which the content should be
considered out-of-date and thus no longer be cached.
Last-Modified This header indicates when the document was last changed. The client
can then cache the document and supply a date by an If&Modified&
Since request header in later requests.
Location This header should be included with all responses that have a status
code in the 300s. This notifies the browser of the document address.
The browser automatically reconnects to this location and retrieves the
new document.
Refresh This header specifies how soon the browser should ask for an updated
page. You can specify time in number of seconds after which a page
would be refreshed.
Retry-After This header can be used in conjunction with a 503 (Service
Unavailable) response to tell the client how soon it can repeat its
request.
Set-Cookie This header specifies a cookie associated with the page.
Methods to Set HTTP Response Header:
There are following methods which can be used to set HTTP response header in your servlet program.
These method are available with )ttp2er!let.esponse object.
S1N1 Method : )escription
1 String encode'edirectB'0,String r$/
Encodes the specified URL for use in the sendRedirect method or, if encoding is not needed,
returns the URL unchanged.
2 String encodeB'0,String r$/
Encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns
the URL unchanged.
3 "oo$ean contains(eader,String name/
Returns a boolean indicating whether the named response header has already been set.
4 "oo$ean isCommitted,/
Returns a boolean indicating if the response has been committed.
5 void addCoo=ie,Coo=ie coo=ie/
Adds the specified cookie to the response.
MAT SOFT
JAVA REFERENCE GUIDE
395
6 void add)ate(eader,String name< $ong date/
Adds a response header with the given name and date-value.
7 void add(eader,String name< String va$e/
Adds a response header with the given name and value.
8 void addInt(eader,String name< int va$e/
Adds a response header with the given name and integer value.
9 void f$shBffer,/
Forces any content in the buffer to be written to the client.
10 void reset,/
Clears any data that exists in the buffer as well as the status code and headers.
11 void resetBffer,/
Clears the content of the underlying buffer in the response without clearing headers or status
code.
12 void send7rror,int sc/
Sends an error response to the client using the specified status code and clearing the buffer.
13 void send7rror,int sc< String msg/
Sends an error response to the client using the specified status.
14 void send'edirect,String $ocation/
Sends a temporary redirect response to the client using the specified redirect location URL.
15 void setBfferSi2e,int si2e/
Sets the preferred buffer size for the body of the response.
16 void setCharacter7ncoding,String charset/
Sets the character encoding (MIME charset) of the response being sent to the client, for
example, to UTF-8.
17 void setContent0ength,int $en/
Sets the length of the content body in the response In HTTP servlets, this method sets the HTTP
Content-Length header.
18 void setContentType,String type/
Sets the content type of the response being sent to the client, if the response has not been
committed yet.
19 void set)ate(eader,String name< $ong date/
Sets a response header with the given name and date-value.
20 void set(eader,String name< String va$e/
Sets a response header with the given name and value.
21 void setInt(eader,String name< int va$e/
Sets a response header with the given name and integer value.
22 void set0oca$e,0oca$e $oc/
Sets the locale of the response, if the response has not been committed yet.
23 void setStats,int sc/
Sets the status code for this response.
HTTP Header Response Example:
MAT SOFT
JAVA REFERENCE GUIDE
396
You already have seen setContentType() method working in previous examples and following example
would also use same method, additionally we would use setInt(eader,/ method to
set'efresh header.
// 6mport r!Puir!# java librari!s
import java.io.**
import java:.s!rvl!t.**
import java:.s!rvl!t.http.**
import java.util.**

// 3:t!n# ttp%!rvl!t class
public class 7!fr!sh !:t!n#s ttp%!rvl!t {

// M!tho# to han#l! 83T m!tho# r!Pu!st.
public voi# #o8!t$ttp%!rvl!t7!Pu!st r!Pu!st2
ttp%!rvl!t7!spons! r!spons!(
throws %!rvl!t3:c!ption2 6?3:c!ption
{
// %!t r!fr!sh2 autoloa# tim! as H s!con#s
r!spons!.s!t6nt!a#!r$)7!fr!sh)2 H(*

// %!t r!spons! cont!nt typ!
r!spons!.s!t,ont!ntTyp!$)t!:t/html)(*

// 8!t curr!nt tim!
,al!n#ar cal!n#ar 9 n!w 8r!gorian,al!n#ar$(*
%tring amTpm*
int hour 9 cal!n#ar.g!t$,al!n#ar.?57(*
int minut! 9 cal!n#ar.g!t$,al!n#ar.M6=5T3(*
int s!con# 9 cal!n#ar.g!t$,al!n#ar.%3,?=4(*
if$cal!n#ar.g!t$,al!n#ar.0MTPM( 99 E(
amTpm 9 )0M)*
!ls!
amTpm 9 )PM)*

%tring ,T 9 hour>)-)> minut! >)-)> s!con# >) )> amTpm*

Print"rit!r out 9 r!spons!.g!t"rit!r$(*
%tring titl! 9 )0uto 7!fr!sh !a#!r %!tting)*
%tring #ocTyp! 9
)NG#octyp! html public O);//wDc//#t# html F.E ) >
)transitional//!nO).On)*
out.println$#ocTyp! >
)Nhtml.On) >
)Nh!a#.Ntitl!.) > titl! > )N/titl!.N/h!a#.On)>
)Nbo#y bgcolor9O)^fEfEfEO).On) >
)NhC align9O)c!nt!rO).) > titl! > )N/hC.On) >
)Np.,urr!nt Tim! is- ) > ,T > )N/p.On)(*
+
// M!tho# to han#l! P?%T m!tho# r!Pu!st.
public voi# #oPost$ttp%!rvl!t7!Pu!st r!Pu!st2
ttp%!rvl!t7!spons! r!spons!(
throws %!rvl!t3:c!ption2 6?3:c!ption {
#o8!t$r!Pu!st2 r!spons!(*
+
MAT SOFT
JAVA REFERENCE GUIDE
397
+
Now calling the above servlet would display current system time after every 5 seconds as follows. Just
run the servlet and wait to see the result:
Auto Refresh Header Setting
Current Time is: 9:44:50 PM
Servlets - Http Status Codes
The format of the HTTP request and HTTP response messages are similar and will have following
structure:
An initial status line + CRLF ( Carriage Return + Line Feed ie. New Line )
Zero or more header lines + CRLF
A blank line ie. a CRLF
An optioanl message body like file, query data or query output.
For example, a server response header looks as follows:
TTP/C.C @EE ?Y
,ont!nt;Typ!- t!:t/html
!a#!r@- ...
...
!a#!r=- ...
$Llan< 1in!(
NG#octyp! ....
Nhtml.
Nh!a#....N/h!a#.
Nbo#y.
...
N/bo#y.
N/html.
The status line consists of the HTTP version (HTTP/1.1 in the example), a status code (200 in the
example), and a very short message corresponding to the status code (OK in the example).
Following is a list of HTTP status codes and associated messages that might be returned from the Web
Server:
Code: Message: )escription:
MAT SOFT
JAVA REFERENCE GUIDE
398
100 Continue Only a part of the request has been received by the server,
but as long as it has not been rejected, the client should
continue with the request
101 Switching Protocols The server switches protocol.
200 OK The request is OK
201 Created The request is complete, and a new resource is created
202 Accepted The request is accepted for processing, but the processing is
not complete.
203 Non-authoritative
Information

204 No Content
205 Reset Content
206 Partial Content
300 Multiple Choices A link list. The user can select a link and go to that location.
Maximum five addresses
301 Moved Permanently The requested page has moved to a new url
302 Found The requested page has moved temporarily to a new url
303 See Other The requested page can be found under a different url
304 Not Modified
305 Use Proxy
306 8nused This code was used in a previous version. It is no longer
used, but the code is reserved.
307 Temporary Redirect The requested page has moved temporarily to a new url.
400 Bad Request The server did not understand the request
401 Unauthorized The requested page needs a username and a password
MAT SOFT
JAVA REFERENCE GUIDE
399
402 Payment Required <ou can not use this code yet
403 Forbidden Access is forbidden to the requested page
404 Not Found The server can not find the requested page.
405 Method Not Allowed The method specified in the request is not allowed.
406 Not Acceptable The server can only generate a response that is not accepted
by the client.
407 Proxy Authentication
Required
You must authenticate with a proxy server before this
request can be served.
408 Request Timeout The request took longer than the server was prepared to
wait.
409 Conflict The request could not be completed because of a conflict.
410 Gone The requested page is no longer available.
411 Length Required The "Content-Length" is not defined. The server will not
accept the request without it.
412 Precondition Failed The precondition given in the request evaluated to false by
the server.
413 Request Entity Too Large The server will not accept the request, because the request
entity is too large.
414 Request-url Too Long The server will not accept the request, because the url is too
long. Occurs when you convert a "post" request to a "get"
request with a long query information.
415 Unsupported Media Type The server will not accept the request, because the media
type is not supported.
417 Expectation Failed
500 Internal Server Error The request was not completed. The server met an
unexpected condition
501 Not Implemented The request was not completed. The server did not support
the functionality required.
MAT SOFT
JAVA REFERENCE GUIDE
400
502 Bad Gateway The request was not completed. The server received an
invalid response from the upstream server
503 Service Unavailable The request was not completed. The server is temporarily
overloading or down.
504 Gateway Timeout The gateway has timed out.
505 HTTP Version Not Supported The server does not support the "http protocol" version.
Methods to Set HTTP Status Code:
There are following methods which can be used to set HTTP Status Code in your servlet program.
These method are available with )ttp2er!let.esponse object.
S1N1 Method : )escription
1 p"$ic void setStats , int statsCode /
This method sets an arbitrary status code. The setStatus method takes an int (the status code)
as an argument. If your response includes a special status code and a document, be sure to call
setStatus before actually returning any of the content with the Print*riter.
2 p"$ic void send'edirect,String r$/
This method generates a 302 response along with a Location header giving the URL of the new
document.
3 p"$ic void send7rror,int code< String message/
This method sends a status code (usually 404) along with a short message that is automatically
formatted inside an HTML document and sent to the client.
HTTP Status Code Example:
Following is the example which would send 407 error code to the client browser and browser would
show you "Need authentication!!!" message.
// 6mport r!Puir!# java librari!s
import java.io.**
import java:.s!rvl!t.**
import java:.s!rvl!t.http.**
import java.util.**
// 3:t!n# ttp%!rvl!t class
public class show3rror !:t!n#s ttp%!rvl!t {

MAT SOFT
JAVA REFERENCE GUIDE
401
// M!tho# to han#l! 83T m!tho# r!Pu!st.
public voi# #o8!t$ttp%!rvl!t7!Pu!st r!Pu!st2
ttp%!rvl!t7!spons! r!spons!(
throws %!rvl!t3:c!ption2 6?3:c!ption
{
// %!t !rror co#! an# r!ason.
r!spons!.s!n#3rror$FEI2 )=!!# auth!nticationGGG) (*
+
// M!tho# to han#l! P?%T m!tho# r!Pu!st.
public voi# #oPost$ttp%!rvl!t7!Pu!st r!Pu!st2
ttp%!rvl!t7!spons! r!spons!(
throws %!rvl!t3:c!ption2 6?3:c!ption {
#o8!t$r!Pu!st2 r!spons!(*
+
+
Now calling the above servlet would display following result:
@TTP S"%".$ 407 ; N113 %."210"#,%"#(0HHH
typ% Status report
m%ssa7% Need authentication!!!
1%s!riptio" The client must first authenticate itself with the proxy (Need authentication!!!).
Apa!h% (om!at9*-*-2&
Day 40: Managing State
MAT SOFT
JAVA REFERENCE GUIDE
402
Servlets - Cookies Handling
Cookies are text files stored on the client computer and they are kept for various information tracking
purpose. Java Servlets transparently supports HTTP cookies.
There are three steps involved in identifying returning users:
Server script sends a set of cookies to the browser. For example name, age, or identification
number etc.
Browser stores this information on local machine for future use.
When next time browser sends any request to web server then it sends those cookies
information to the server and server uses that information to identify the user.
This chapter will teach you how to set or reset cookies, how to access them and how to delete them.
The Anatomy of a Cookie:
Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on a
browser). A servlet that sets a cookie might send headers that look something like this:
TTP/C.C @EE ?Y
4at!- Fri2 EF F!b @EEE @C-ED-DJ 8MT
%!rv!r- 0pach!/C.D.K $5=6R( PP/F.EbD
%!t;,oo<i!- nam!9:y/* !:pir!s9Fri#ay2 EF;F!b;EI @@-ED-DJ 8MT*
path9/* #omain9mat;softspoint.com
,onn!ction- clos!
,ont!nt;Typ!- t!:t/html
As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and a domain.
The name and value will be URL encoded. The expires field is an instruction to the browser to "forget"
the cookie after the given time and date.
If the browser is configured to store cookies, it will then keep this information until the expiry date. If
the user points the browser at any page that matches the path and domain of the cookie, it will resend
the cookie to the server. The browser's headers might look something like this:
83T / TTP/C.E
,onn!ction- Y!!p;0liv!
5s!r;0g!nt- Mo/illa/F.M $RCC* 6* 1inu: @.@.M;CHapmac ppc(
ost- /in<.#!mon.co.u<-CC@M
0cc!pt- imag!/gif2 */*
0cc!pt;3nco#ing- g/ip
0cc!pt;1anguag!- !n
0cc!pt;,hars!t- iso;JJHK;C2*2utf;J
,oo<i!- nam!9:y/
A servlet will then have access to the cookie through the request method re4uest.getCoo(ies()which
returns an array of Coo(ie objects.
MAT SOFT
JAVA REFERENCE GUIDE
403
Servlet Cookies Methods:
Following is the list of useful methods which you can use while manipulating cookies in servlet.
S1N1 Method : )escription
1 p"$ic void set)omain,String pattern/
This method sets the domain to which cookie applies, for example mat-softspoint.com.
2 p"$ic String get)omain,/
This method gets the domain to which cookie applies, for example mat-softspoint.com.
3 p"$ic void setMax%ge,int expiry/
This method sets how much time (in seconds) should elapse before the cookie expires. If you
don't set this, the cookie will last only for the current session.
4 p"$ic int getMax%ge,/
This method returns the maximum age of the cookie, specified in seconds, By default, -1
indicating the cookie will persist until browser shutdown.
5 p"$ic String getName,/
This method returns the name of the cookie. The name cannot be changed after creation.
6 p"$ic void set*a$e,String ne3*a$e/
This method sets the value associated with the cookie.
7 p"$ic String get*a$e,/
This method gets the value associated with the cookie.
8 p"$ic void setPath,String ri/
This method sets the path to which this cookie applies. If you don't specify a path, the cookie is
returned for all URLs in the same directory as the current page as well as all subdirectories.
9 p"$ic String getPath,/
This method gets the path to which this cookie applies.
10 p"$ic void setSecre,"oo$ean f$ag/
This method sets the boolean value indicating whether the cookie should only be sent over
encrypted (i.e. SSL) connections.
11 p"$ic void setComment,String prpose/
This method specifies a comment that describes a cookie's purpose. The comment is useful if
the browser presents the cookie to the user.
12 p"$ic String getComment,/
MAT SOFT
JAVA REFERENCE GUIDE
404
This method returns the comment describing the purpose of this cookie, or null if the cookie has
no comment.
Setting Cookies with Servlet:
Setting cookies with servlet involves three steps:
,4/ Creating a Coo=ie o"#ect: You call the Cookie constructor with a cookie name and a cookie
value, both of which are strings.
,oo<i! coo<i! 9 n!w ,oo<i!$)<!y)2)valu!)(*
Keep in mind, neither the name nor the value should contain white space or any of the following
characters:
& ' $ ( 9 2 ) / S \ - *
,5/ Setting the maximm age: You use setMaxAge to specify how long (in seconds) the cookie
should be valid. Following would set up a cookie for 24 hours.
coo<i!.s!tMa:0g!$ME*ME*@F(*
,E/ Sending the Coo=ie into the (TTP response headers: You use response1addCoo=ieto add
cookies in the HTTP response header as follows:
r!spons!.a##,oo<i!$coo<i!(*
Example:
Let us modify our Form Example to set the cookies for first and last name.
// 6mport r!Puir!# java librari!s
import java.io.**
import java:.s!rvl!t.**
import java:.s!rvl!t.http.**

// 3:t!n# ttp%!rvl!t class
public class !lloForm !:t!n#s ttp%!rvl!t {

public voi# #o8!t$ttp%!rvl!t7!Pu!st r!Pu!st2
ttp%!rvl!t7!spons! r!spons!(
throws %!rvl!t3:c!ption2 6?3:c!ption
{
// ,r!at! coo<i!s for first an# last nam!s.
,oo<i! first=am! 9 n!w ,oo<i!$)firstTnam!)2
r!Pu!st.g!tParam!t!r$)firstTnam!)((*
MAT SOFT
JAVA REFERENCE GUIDE
405
,oo<i! last=am! 9 n!w ,oo<i!$)lastTnam!)2
r!Pu!st.g!tParam!t!r$)lastTnam!)((*
// %!t !:piry #at! aft!r @F rs for both th! coo<i!s.
first=am!.s!tMa:0g!$ME*ME*@F(*
last=am!.s!tMa:0g!$ME*ME*@F(*
// 0## both th! coo<i!s in th! r!spons! h!a#!r.
r!spons!.a##,oo<i!$ first=am! (*
r!spons!.a##,oo<i!$ last=am! (*
// %!t r!spons! cont!nt typ!
r!spons!.s!t,ont!ntTyp!$)t!:t/html)(*

Print"rit!r out 9 r!spons!.g!t"rit!r$(*
%tring titl! 9 )%!tting ,oo<i!s 3:ampl!)*
%tring #ocTyp! 9
)NG#octyp! html public O);//wDc//#t# html F.E ) >
)transitional//!nO).On)*
out.println$#ocTyp! >
)Nhtml.On) >
)Nh!a#.Ntitl!.) > titl! > )N/titl!.N/h!a#.On) >
)Nbo#y bgcolor9O)^fEfEfEO).On) >
)NhC align9O)c!nt!rO).) > titl! > )N/hC.On) >
)Nul.On) >
) Nli.Nb.First =am!N/b.- )
> r!Pu!st.g!tParam!t!r$)firstTnam!)( > )On) >
) Nli.Nb.1ast =am!N/b.- )
> r!Pu!st.g!tParam!t!r$)lastTnam!)( > )On) >
)N/ul.On) >
)N/bo#y.N/html.)(*
+
+
Compile above servlet (e$$o+orm and create appropriate entry in web.xml file and finally try following
HTML page to call servlet.

Nhtml.
Nbo#y.
Nform action9)!lloForm) m!tho#9)83T).
First =am!- Ninput typ!9)t!:t) nam!9)firstTnam!).
Nbr /.
1ast =am!- Ninput typ!9)t!:t) nam!9)lastTnam!) /.
Ninput typ!9)submit) valu!9)%ubmit) /.
N/form.
N/bo#y.
N/html.
Keep above HTML content in a file Hello.htm and put it in <Tomcat-installation-
directory>/webapps/ROOT directory. When you would access http%@@localhost%ABAB@)ello.htm, here is
the actual output of the above form.
MAT SOFT
JAVA REFERENCE GUIDE
406
First Name:
Last Name:
Try to enter First Name and Last Name and then click submit button. This would display first name and
last name on your screen and same time it would set two cookies firstName and lastName which
would be passed back to the server when next time you would press Submit button.
Next section would explain you how you would access these cookies back in your web application.
Reading Cookies with Servlet:
To read cookies, you need to create an array of ja!ax.ser!let.http.Coo(ie objects by calling
thegetCoo=ies, / method of )ttp2er!let.e4uest. Then cycle through the array, and use getName()
and getValue() methods to access each cookie and associated value.
Example:
Let us read cookies which we have set in previous example:
// 6mport r!Puir!# java librari!s
import java.io.**
import java:.s!rvl!t.**
import java:.s!rvl!t.http.**

// 3:t!n# ttp%!rvl!t class
public class 7!a#,oo<i!s !:t!n#s ttp%!rvl!t {

public voi# #o8!t$ttp%!rvl!t7!Pu!st r!Pu!st2
ttp%!rvl!t7!spons! r!spons!(
throws %!rvl!t3:c!ption2 6?3:c!ption
{
,oo<i! coo<i! 9 null*
,oo<i!&' coo<i!s 9 null*
// 8!t an array of ,oo<i!s associat!# with this #omain
coo<i!s 9 r!Pu!st.g!t,oo<i!s$(*

// %!t r!spons! cont!nt typ!
r!spons!.s!t,ont!ntTyp!$)t!:t/html)(*

Print"rit!r out 9 r!spons!.g!t"rit!r$(*
%tring titl! 9 )7!a#ing ,oo<i!s 3:ampl!)*
%tring #ocTyp! 9
)NG#octyp! html public O);//wDc//#t# html F.E ) >
)transitional//!nO).On)*
out.println$#ocTyp! >
)Nhtml.On) >
)Nh!a#.Ntitl!.) > titl! > )N/titl!.N/h!a#.On) >
)Nbo#y bgcolor9O)^fEfEfEO).On) (*
if$ coo<i!s G9 null ({
out.println$)Nh@. Foun# ,oo<i!s =am! an# Balu!N/h@.)(*
MAT SOFT
JAVA REFERENCE GUIDE
407
for $int i 9 E* i N coo<i!s.l!ngth* i>>({
coo<i! 9 coo<i!s&i'*
out.print$)=am! - ) > coo<i!.g!t=am!$ ( > )2 )(*
out.print$)Balu!- ) > coo<i!.g!tBalu!$ (>) Nbr/.)(*
+
+!ls!{
out.println$
)Nh@.=o coo<i!s foun#sN/h@.)(*
+
out.println$)N/bo#y.)(*
out.println$)N/html.)(*
+
+
Compile above servlet 'eadCoo=ies and create appropriate entry in web.xml file. If you would have
set first_name cookie as "John" and last_name cookie as "Player" then
runninghttp%@@localhost%ABAB@.eadCoo(ies would display the following result:
Found Cookies Name and Value
Name : first_name, Value: John
Name : last_name, Value: Player
Delete Cookies with Servlet:
To delete cookies is very simple. If you want to delete a cookie then you simply need to follow up
following three steps:
1. Read an already exsiting cookie and store it in Cookie object.
2. Set cookie age as zero using setMax%ge,/ method to delete an existing cookie.
3. Add this cookie back into response header.
Example:
Following example would delete and existing cookie named "first_name" and when you would run
ReadCookies servlet next time it would return null value for first_name.
// 6mport r!Puir!# java librari!s
import java.io.**
import java:.s!rvl!t.**
import java:.s!rvl!t.http.**

// 3:t!n# ttp%!rvl!t class
public class 4!l!t!,oo<i!s !:t!n#s ttp%!rvl!t {

public voi# #o8!t$ttp%!rvl!t7!Pu!st r!Pu!st2
MAT SOFT
JAVA REFERENCE GUIDE
408
ttp%!rvl!t7!spons! r!spons!(
throws %!rvl!t3:c!ption2 6?3:c!ption
{
,oo<i! coo<i! 9 null*
,oo<i!&' coo<i!s 9 null*
// 8!t an array of ,oo<i!s associat!# with this #omain
coo<i!s 9 r!Pu!st.g!t,oo<i!s$(*

// %!t r!spons! cont!nt typ!
r!spons!.s!t,ont!ntTyp!$)t!:t/html)(*

Print"rit!r out 9 r!spons!.g!t"rit!r$(*
%tring titl! 9 )4!l!t! ,oo<i!s 3:ampl!)*
%tring #ocTyp! 9
)NG#octyp! html public O);//wDc//#t# html F.E ) >
)transitional//!nO).On)*
out.println$#ocTyp! >
)Nhtml.On) >
)Nh!a#.Ntitl!.) > titl! > )N/titl!.N/h!a#.On) >
)Nbo#y bgcolor9O)^fEfEfEO).On) (*
if$ coo<i!s G9 null ({
out.println$)Nh@. ,oo<i!s =am! an# Balu!N/h@.)(*
for $int i 9 E* i N coo<i!s.l!ngth* i>>({
coo<i! 9 coo<i!s&i'*
if$$coo<i!.g!t=am!$ ((.compar!To$)firstTnam!)( 99 E ({
coo<i!.s!tMa:0g!$E(*
r!spons!.a##,oo<i!$coo<i!(*
out.print$)4!l!t!# coo<i! - ) >
coo<i!.g!t=am!$ ( > )Nbr/.)(*
+
out.print$)=am! - ) > coo<i!.g!t=am!$ ( > )2 )(*
out.print$)Balu!- ) > coo<i!.g!tBalu!$ (>) Nbr/.)(*
+
+!ls!{
out.println$
)Nh@.=o coo<i!s foun#sN/h@.)(*
+
out.println$)N/bo#y.)(*
out.println$)N/html.)(*
+
+
Compile above servlet )e$eteCoo=ies and create appropriate entry in web.xml file. Now
running http%@@localhost%ABAB@6eleteCoo(ies would display the following result:
MAT SOFT
JAVA REFERENCE GUIDE
409
Cookies Name and Value
Deleted cookie : first_name
Name : first_name, Value: John
Name : last_name, Value: Player
Now try to run http%@@localhost%ABAB@.eadCoo(ies and it would display only one cookie as follows:
Found Cookies Name and Value
Name : last_name, Value: Player
You can delete your cookies in Internet Explorer manually. Start at the Tools menu and select Internet
Options. To delete all cookies, press Delete Cookies.
Servlets - Session Tracking
HTTP is a "stateless" protocol which means each time a client retrieves a Web page, the client opens a
separate connection to the Web server and the server automatically does not keep any record of
previous client request.
Still there are following three ways to maintain session between web client and web server:
(1) Cookies:
A webserver can assign a unique session ID as a cookie to each web client and for subsequent
requests from the client they can be recognized using the recieved cookie.
This may not be an effective way because many time browser does not support a cookie, so I would
not recommend to use this procedure to maintain the sessions.
(2) Hidden Form Fields:
A web server can send a hidden HTML form field along with a unique session ID as follows:
Ninput typ!9)hi##!n) nam!9)s!ssioni#) valu!9)C@DFH).
This entry means that, when the form is submitted, the specified name and value are automatically
included in the GET or POST data. Each time when web browser sends request back, then session_id
value can be used to keep the track of different web browsers.
MAT SOFT
JAVA REFERENCE GUIDE
410
This could be an effective way of keeping track of the session but clicking on a regular (<A HREF...>)
hypertext link does not result in a form submission, so hidden form fields also cannot support general
session tracking.
(3) URL Rewriting:
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.
For example, with http://mat-softspoint.com/file.htm;sessionid=12345, the session identifier is
attached as sessionid=12345 which can be accessed at the web server to identify the client.
URL rewriting is a better way to maintain sessions and works for the browsers when they don't
support cookies but here drawback is that you would have generate every URL dynamically to assign a
session ID though page is simple static HTML page.
The HttpSession Object:
Apart from the above mentioned three ways, servlet provides HttpSession Interface which provides a
way to identify a user across more than one page request or visit to a Web site and to store
information about that user.
The servlet container uses this interface to create a session between an HTTP client and an HTTP
server. The session persists for a specified time period, across more than one connection or page
request from the user.
You would get HttpSession object by calling the public method getSession,/ of HttpServletRequest,
as below:
ttp%!ssion s!ssion 9 r!Pu!st.g!t%!ssion$(*
You need to call re4uest.get2ession() before you send any document content to the client. Here is a
summary of the important methods available through HttpSession object:
S1N1 Method : )escription
1 p"$ic !"#ect get%ttri"te,String name/
This method returns the object bound with the specified name in this session, or null if no object
is bound under the name.
2 p"$ic 7nmeration get%ttri"teNames,/
This method returns an Enumeration of String objects containing the names of all the objects
bound to this session.
3 p"$ic $ong getCreationTime,/
This method returns the time when this session was created, measured in milliseconds since
midnight January 1, 1970 GMT.
MAT SOFT
JAVA REFERENCE GUIDE
411
4 p"$ic String getId,/
This method returns a string containing the unique identifier assigned to this session.
5 p"$ic $ong get0ast%ccessedTime,/
This method returns the last time the client sent a request associated with this session, as the
number of milliseconds since midnight January 1, 1970 GMT.
6 p"$ic int getMaxInactiveInterva$,/
This method returns the maximum time interval, in seconds, that the servlet container will keep
this session open between client accesses.
7 p"$ic void inva$idate,/
This method invalidates this session and unbinds any objects bound to it.
8 p"$ic "oo$ean isNe3,
This method returns true if the client does not yet know about the session or if the client
chooses not to join the session.
9 p"$ic void remove%ttri"te,String name/
This method removes the object bound with the specified name from this session.
10 p"$ic void set%ttri"te,String name< !"#ect va$e/
This method binds an object to this session, using the name specified.
11 p"$ic void setMaxInactiveInterva$,int interva$/
This method specifies the time, in seconds, between client requests before the servlet container
will invalidate this session.
Session Tracking Example:
This example describes how to use the HttpSession object to find out the creation time and the last-
accessed time for a session. We would associate a new session with the request if one does not
already exist.
// 6mport r!Puir!# java librari!s
import java.io.**
import java:.s!rvl!t.**
import java:.s!rvl!t.http.**
import java.util.**

// 3:t!n# ttp%!rvl!t class
public class %!ssionTrac< !:t!n#s ttp%!rvl!t {

public voi# #o8!t$ttp%!rvl!t7!Pu!st r!Pu!st2
ttp%!rvl!t7!spons! r!spons!(
throws %!rvl!t3:c!ption2 6?3:c!ption
{
MAT SOFT
JAVA REFERENCE GUIDE
412
// ,r!at! a s!ssion obj!ct if it is alr!a#y not cr!at!#.
ttp%!ssion s!ssion 9 r!Pu!st.g!t%!ssion$tru!(*
// 8!t s!ssion cr!ation tim!.
4at! cr!at!Tim! 9 n!w 4at!$s!ssion.g!t,r!ationTim!$((*
// 8!t last acc!ss tim! of this w!b pag!.
4at! last0cc!ssTim! 9
n!w 4at!$s!ssion.g!t1ast0cc!ss!#Tim!$((*
%tring titl! 9 )"!lcom! Lac< to my w!bsit!)*
6nt!g!r visit,ount 9 n!w 6nt!g!r$E(*
%tring visit,ountY!y 9 n!w %tring$)visit,ount)(*
%tring us!r64Y!y 9 n!w %tring$)us!r64)(*
%tring us!r64 9 n!w %tring$)0L,4)(*
// ,h!c< if this is n!w com!r on your w!b pag!.
if $s!ssion.is=!w$(({
titl! 9 )"!lcom! to my w!bsit!)*
s!ssion.s!t0ttribut!$us!r64Y!y2 us!r64(*
+ !ls! {
visit,ount 9 $6nt!g!r(s!ssion.g!t0ttribut!$visit,ountY!y(*
visit,ount 9 visit,ount > C*
us!r64 9 $%tring(s!ssion.g!t0ttribut!$us!r64Y!y(*
+
s!ssion.s!t0ttribut!$visit,ountY!y2 visit,ount(*
// %!t r!spons! cont!nt typ!
r!spons!.s!t,ont!ntTyp!$)t!:t/html)(*
Print"rit!r out 9 r!spons!.g!t"rit!r$(*
%tring #ocTyp! 9
)NG#octyp! html public O);//wDc//#t# html F.E ) >
)transitional//!nO).On)*
out.println$#ocTyp! >
)Nhtml.On) >
)Nh!a#.Ntitl!.) > titl! > )N/titl!.N/h!a#.On) >
)Nbo#y bgcolor9O)^fEfEfEO).On) >
)NhC align9O)c!nt!rO).) > titl! > )N/hC.On) >
)Nh@ align9O)c!nt!rO).%!ssion 6nfomationN/h@.On) >
)Ntabl! bor#!r9O)CO) align9O)c!nt!rO).On) >
)Ntr bgcolor9O)^KFKFKFO).On) >
) Nth.%!ssion infoN/th.Nth.valu!N/th.N/tr.On) >
)Ntr.On) >
) Nt#.i#N/t#.On) >
) Nt#.) > s!ssion.g!t6#$( > )N/t#.N/tr.On) >
)Ntr.On) >
) Nt#.,r!ation Tim!N/t#.On) >
) Nt#.) > cr!at!Tim! >
) N/t#.N/tr.On) >
)Ntr.On) >
) Nt#.Tim! of 1ast 0cc!ssN/t#.On) >
) Nt#.) > last0cc!ssTim! >
) N/t#.N/tr.On) >
)Ntr.On) >
) Nt#.5s!r 64N/t#.On) >
) Nt#.) > us!r64 >
MAT SOFT
JAVA REFERENCE GUIDE
413
) N/t#.N/tr.On) >
)Ntr.On) >
) Nt#.=umb!r of visitsN/t#.On) >
) Nt#.) > visit,ount > )N/t#.N/tr.On) >
)N/tabl!.On) >
)N/bo#y.N/html.)(*
+
+
Compile above servlet SessionTrac= and create appropriate entry in web.xml file. Now
runninghttp%@@localhost%ABAB@2essionTrac( would display the following result when you would run for
the first time:
Welcome to my website
Session Infomation
Session info va$e
id 0AE3EC93FF44E3C525B4351B77ABB2D5
Creation Time Tue Jun 08 17:26:40 GMT+04:00 2010
Time of Last Access Tue Jun 08 17:26:40 GMT+04:00 2010
User ID ABCD
Number of visits 0
Now try to run the same servlet for second time, it would display following result.
Welcome Back to my website
Session Infomation
info type va$e
id 0AE3EC93FF44E3C525B4351B77ABB2D5
Creation Time Tue Jun 08 17:26:40 GMT+04:00 2010
Time of Last Access Tue Jun 08 17:26:40 GMT+04:00 2010
User ID ABCD
MAT SOFT
JAVA REFERENCE GUIDE
414
Number of visits 1
Deleting Session Data:
When you are done with a user's session data, you have several options:
.. 'emove a partic$ar attri"te: You can call public !oid remo!e-ttribute(2tring
name)method to delete the value associated with a particular key.
/. )e$ete the 3ho$e session: You can call public !oid in!alidate() method to discard an entire
session.
0. Setting Session timeot: You can call public !oid set#ax5nacti!e5nter!al(int inter!al)method
to set the timeout for a session individually.
@. 0og the ser ot: The servers that support servlets 2.4, you can call $ogot to log the client
out of the Web server and invalidate all sessions belonging to all the users.
A. 3e"1xm$ Configration: If you are using Tomcat, apart from the above mentioned methods,
you can configure session time out in web.xml file as follows.
Ns!ssion;config.
Ns!ssion;tim!out.CHN/s!ssion;tim!out.
N/s!ssion;config.
The timeout is expressed as minutes, and overrides the default timeout which is 30 minutes in
Tomcat.
The getMaxInactiveInterval( ) method in a servlet returns the timeout period for that session in
seconds. So if your session is configured in web.xml for 15 minutes, getMaxInactiveInterval( ) returns
900.
MAT SOFT
JAVA REFERENCE GUIDE
415
Day 41: Servlets - Database Access
To start with basic concept, let us create a simple table and create few records in that table as follows:
Create Table
To create the 7mp$oyees table in TEST database, use the following steps:
Step 1:
Open a Command Prompt and change to the installation directory as follows:
,-O.
,-O.c# Program Fil!sOMy%X1Obin
,-OProgram Fil!sOMy%X1Obin.
Step 2:
Login to database as follows
,-OProgram Fil!sOMy%X1Obin.mysPl ;u root ;p
3nt!r passwor#- ********
mysPl.
Step 3:
Create the table 7mp$oyee in T7ST database as follows:
mysPl. us! T3%T*
mysPl. cr!at! tabl! 3mploy!!s
$
i# int not null2
ag! int not null2
first varchar $@HH(2
last varchar $@HH(
(*
Xu!ry ?Y2 E rows aff!ct!# $E.EJ s!c(
mysPl.
Create Data Records
Finally you create few records in Employee table as follows:
mysPl. 6=%37T 6=T? 3mploy!!s B0153% $CEE2 CJ2 'Vara'2 '0li'(*
Xu!ry ?Y2 C row aff!ct!# $E.EH s!c(
MAT SOFT
JAVA REFERENCE GUIDE
416

mysPl. 6=%37T 6=T? 3mploy!!s B0153% $CEC2 @H2 'Mahna/'2 'Fatma'(*
Xu!ry ?Y2 C row aff!ct!# $E.EE s!c(

mysPl. 6=%37T 6=T? 3mploy!!s B0153% $CE@2 DE2 'Vai#'2 'Yhan'(*
Xu!ry ?Y2 C row aff!ct!# $E.EE s!c(

mysPl. 6=%37T 6=T? 3mploy!!s B0153% $CED2 @J2 '%umit'2 'Mittal'(*
Xu!ry ?Y2 C row aff!ct!# $E.EE s!c(

mysPl.
Accessing a Database:
Here is an example which shows how to access TEST database using Servlet.
// 1oa#ing r!Puir!# librari!s
import java.io.**
import java.util.**
import java:.s!rvl!t.**
import java:.s!rvl!t.http.**
import java.sPl.**

public class 4atabas!0cc!ss !:t!n#s ttp%!rvl!t{

public voi# #o8!t$ttp%!rvl!t7!Pu!st r!Pu!st2
ttp%!rvl!t7!spons! r!spons!(
throws %!rvl!t3:c!ption2 6?3:c!ption
{
// J4L, #riv!r nam! an# #atabas! 571
static final %tring J4L,T476B379)com.mysPl.j#bc.4riv!r)*
static final %tring 4LT5719)j#bc-mysPl-//localhost/T3%T)*
// 4atabas! cr!#!ntials
static final %tring 5%37 9 )root)*
static final %tring P0%% 9 )passwor#)*
// %!t r!spons! cont!nt typ!
r!spons!.s!t,ont!ntTyp!$)t!:t/html)(*
Print"rit!r out 9 r!spons!.g!t"rit!r$(*
%tring titl! 9 )4atabas! 7!sult)*
%tring #ocTyp! 9
)NG#octyp! html public O);//wDc//#t# html F.E ) >
)transitional//!nO).On)*
out.println$#ocTyp! >
)Nhtml.On) >
)Nh!a#.Ntitl!.) > titl! > )N/titl!.N/h!a#.On) >
)Nbo#y bgcolor9O)^fEfEfEO).On) >
)NhC align9O)c!nt!rO).) > titl! > )N/hC.On)(*
try{
// 7!gist!r J4L, #riv!r
,lass.for=am!$)com.mysPl.j#bc.4riv!r)(*
MAT SOFT
JAVA REFERENCE GUIDE
417
// ?p!n a conn!ction
conn 9 4riv!rManag!r.g!t,onn!ction$4LT57125%372P0%%(*
// 3:!cut! %X1 Pu!ry
stmt 9 conn.cr!at!%tat!m!nt$(*
%tring sPl*
sPl 9 )%313,T i#2 first2 last2 ag! F7?M 3mploy!!s)*
7!sult%!t rs 9 stmt.!:!cut!Xu!ry$sPl(*
// 3:tract #ata from r!sult s!t
whil!$rs.n!:t$(({
//7!tri!v! by column nam!
int i# 9 rs.g!t6nt$)i#)(*
int ag! 9 rs.g!t6nt$)ag!)(*
%tring first 9 rs.g!t%tring$)first)(*
%tring last 9 rs.g!t%tring$)last)(*
//4isplay valu!s
out.println$)64- ) > i# > )Nbr.)(*
out.println$)2 0g!- ) > ag! > )Nbr.)(*
out.println$)2 First- ) > first > )Nbr.)(*
out.println$)2 1ast- ) > last > )Nbr.)(*
+
out.println$)N/bo#y.N/html.)(*
// ,l!an;up !nvironm!nt
rs.clos!$(*
stmt.clos!$(*
conn.clos!$(*
+catch$%X13:c!ption s!({
//an#l! !rrors for J4L,
s!.print%tac<Trac!$(*
+catch$3:c!ption !({
//an#l! !rrors for ,lass.for=am!
!.print%tac<Trac!$(*
+finally{
//finally bloc< us!# to clos! r!sourc!s
try{
if$stmtG9null(
stmt.clos!$(*
+catch$%X13:c!ption s!@({
+// nothing w! can #o
try{
if$connG9null(
conn.clos!$(*
+catch$%X13:c!ption s!({
s!.print%tac<Trac!$(*
+//!n# finally try
+ //!n# try
+
+
Now let us compile above servlet and create following entries in web.xml
MAT SOFT
JAVA REFERENCE GUIDE
418
....
Ns!rvl!t.
Ns!rvl!t;nam!.4atabas!0cc!ssN/s!rvl!t;nam!.
Ns!rvl!t;class.4atabas!0cc!ssN/s!rvl!t;class.
N/s!rvl!t.

Ns!rvl!t;mapping.
Ns!rvl!t;nam!.4atabas!0cc!ssN/s!rvl!t;nam!.
Nurl;patt!rn./4atabas!0cc!ssN/url;patt!rn.
N/s!rvl!t;mapping.
....
Now call this servlet using URL http://localhost:8080/DatabaseAccess which would display following
response:
Database Result
64- CEE2 0g!- CJ2 First- Vara2 1ast- 0li
64- CEC2 0g!- @H2 First- Mahna/2 1ast- Fatma
64- CE@2 0g!- DE2 First- Vai#2 1ast- Yhan
64- CED2 0g!- @J2 First- %umit2 1ast- Mittal
Servlets - File Uploading
A Servlet can be used with an HTML form tag to allow users to upload files to the server. An uploaded
file could be a text file or image file or any document.
Creating a File Upload Form:
The following HTM code below creates an uploader form. Following are the important points to be
noted down:
The form method attribute should be set to P!ST method and GET method can not be used.
The form enctype attribute should be set to m$tipartKform&data.
The form action attribute should be set to a servlet file which would handle file uploading at
backend server. Following example is using Bp$oadServ$et servlet to upload file.
To upload a single file you should use a single <input .../> tag with attribute type="file". To
allow multiple files uploading, include more than one input tags with different values for the
name attribute. The browser associates a Browse button with each of them.

Nhtml.
Nh!a#.
MAT SOFT
JAVA REFERENCE GUIDE
419
Ntitl!.Fil! 5ploa#ing FormN/titl!.
N/h!a#.
Nbo#y.
NhD.Fil! 5ploa#-N/hD.
%!l!ct a fil! to uploa#- Nbr /.
Nform action9)5ploa#%!rvl!t) m!tho#9)post)
!nctyp!9)multipart/form;#ata).
Ninput typ!9)fil!) nam!9)fil!) si/!9)HE) /.
Nbr /.
Ninput typ!9)submit) valu!9)5ploa# Fil!) /.
N/form.
N/bo#y.
N/html.
This will display following result which would allow to select a file from local PC and when user would
click at "Upload File", form would be submitted along with the selected file:

File Upload:
%!l!ct a fil! to uploa#-





=?T3- This is just #ummy form an# woul# not wor<.
Writing Backend Servlet:
Following is the servlet Bp$oadServ$et which would take care of accepting uploaded file and to store
it in directory <Tomcat-installation-directory>/webapps/data. This directory name could also be added
using an external configuration such as a context&param element in web.xml as follows:

Nw!b;app.
....
Ncont!:t;param.
N#!scription.1ocation to stor! uploa#!# fil!N/#!scription.
Nparam;nam!.fil!;uploa#N/param;nam!.
Nparam;valu!.
c-Oapach!;tomcat;H.H.@KOw!bappsO#ataO
N/param;valu!.
N/cont!:t;param.
....
N/w!b;app.
Following is the source code for UploadServlet which can handle multiple file uploading at a time.
Before procedding you have make sure the followings:
MAT SOFT
JAVA REFERENCE GUIDE
420
Following example depends on FileUpload, so make sure you have the latest version
ofcommons&fi$ep$oad1x1x1#ar file in your classpath. You can download it
fromhttp://commons.apache.org/fileupload/.
FileUpload depends on Commons IO, so make sure you have the latest version ofcommons&
io&x1x1#ar file in your classpath. You can download it fromhttp://commons.apache.org/io/.
While testing following example, you should upload a file which has less size
thanmax'ile2i/e otherwise file would not be uploaded.
Make sure you have created directories c:\temp and c:\apache-tomcat-5.5.29\webapps\data
well in advance.
// 6mport r!Puir!# java librari!s
import java.io.**
import java.util.**

import java:.s!rvl!t.%!rvl!t,onfig*
import java:.s!rvl!t.%!rvl!t3:c!ption*
import java:.s!rvl!t.http.ttp%!rvl!t*
import java:.s!rvl!t.http.ttp%!rvl!t7!Pu!st*
import java:.s!rvl!t.http.ttp%!rvl!t7!spons!*

import org.apach!.commons.fil!uploa#.Fil!6t!m*
import org.apach!.commons.fil!uploa#.Fil!5ploa#3:c!ption*
import org.apach!.commons.fil!uploa#.#is<.4is<Fil!6t!mFactory*
import org.apach!.commons.fil!uploa#.s!rvl!t.%!rvl!tFil!5ploa#*
import org.apach!.commons.io.output.**
public class 5ploa#%!rvl!t !:t!n#s ttp%!rvl!t {

privat! bool!an isMultipart*
privat! %tring fil!Path*
privat! int ma:Fil!%i/! 9 HE * CE@F*
privat! int ma:M!m%i/! 9 F * CE@F*
privat! Fil! fil! *
public voi# init$ ({
// 8!t th! fil! location wh!r! it woul# b! stor!#.
fil!Path 9
g!t%!rvl!t,ont!:t$(.g!t6nitParam!t!r$)fil!;uploa#)(*
+
public voi# #oPost$ttp%!rvl!t7!Pu!st r!Pu!st2
ttp%!rvl!t7!spons! r!spons!(
throws %!rvl!t3:c!ption2 java.io.6?3:c!ption {
// ,h!c< that w! hav! a fil! uploa# r!Pu!st
isMultipart 9 %!rvl!tFil!5ploa#.isMultipart,ont!nt$r!Pu!st(*
r!spons!.s!t,ont!ntTyp!$)t!:t/html)(*
java.io.Print"rit!r out 9 r!spons!.g!t"rit!r$ (*
if$ GisMultipart ({
out.println$)Nhtml.)(*
out.println$)Nh!a#.)(*
out.println$)Ntitl!.%!rvl!t uploa#N/titl!.)(*
out.println$)N/h!a#.)(*
out.println$)Nbo#y.)(*
out.println$)Np.=o fil! uploa#!#N/p.)(*
MAT SOFT
JAVA REFERENCE GUIDE
421
out.println$)N/bo#y.)(*
out.println$)N/html.)(*
r!turn*
+
4is<Fil!6t!mFactory factory 9 n!w 4is<Fil!6t!mFactory$(*
// ma:imum si/! that will b! stor!# in m!mory
factory.s!t%i/!Thr!shol#$ma:M!m%i/!(*
// 1ocation to sav! #ata that is larg!r than ma:M!m%i/!.
factory.s!t7!pository$n!w Fil!$)c-OOt!mp)((*
// ,r!at! a n!w fil! uploa# han#l!r
%!rvl!tFil!5ploa# uploa# 9 n!w %!rvl!tFil!5ploa#$factory(*
// ma:imum fil! si/! to b! uploa#!#.
uploa#.s!t%i/!Ma:$ ma:Fil!%i/! (*
try{
// Pars! th! r!Pu!st to g!t fil! it!ms.
1ist fil!6t!ms 9 uploa#.pars!7!Pu!st$r!Pu!st(*
// Proc!ss th! uploa#!# fil! it!ms
6t!rator i 9 fil!6t!ms.it!rator$(*
out.println$)Nhtml.)(*
out.println$)Nh!a#.)(*
out.println$)Ntitl!.%!rvl!t uploa#N/titl!.)(*
out.println$)N/h!a#.)(*
out.println$)Nbo#y.)(*
whil! $ i.has=!:t $( (
{
Fil!6t!m fi 9 $Fil!6t!m(i.n!:t$(*
if $ Gfi.isFormFi!l# $( (
{
// 8!t th! uploa#!# fil! param!t!rs
%tring fi!l#=am! 9 fi.g!tFi!l#=am!$(*
%tring fil!=am! 9 fi.g!t=am!$(*
%tring cont!ntTyp! 9 fi.g!t,ont!ntTyp!$(*
bool!an is6nM!mory 9 fi.is6nM!mory$(*
long si/!6nLyt!s 9 fi.g!t%i/!$(*
// "rit! th! fil!
if$ fil!=am!.last6n#!:?f$)OO)( .9 E ({
fil! 9 n!w Fil!$ fil!Path >
fil!=am!.substring$ fil!=am!.last6n#!:?f$)OO)((( *
+!ls!{
fil! 9 n!w Fil!$ fil!Path >
fil!=am!.substring$fil!=am!.last6n#!:?f$)OO)(>C(( *
+
fi.writ!$ fil! ( *
out.println$)5ploa#!# Fil!nam!- ) > fil!=am! > )Nbr.)(*
+
+
out.println$)N/bo#y.)(*
out.println$)N/html.)(*
+catch$3:c!ption !:( {
%yst!m.out.println$!:(*
+
MAT SOFT
JAVA REFERENCE GUIDE
422
+
public voi# #o8!t$ttp%!rvl!t7!Pu!st r!Pu!st2
ttp%!rvl!t7!spons! r!spons!(
throws %!rvl!t3:c!ption2 java.io.6?3:c!ption {

throw n!w %!rvl!t3:c!ption$)83T m!tho# us!# with ) >
g!t,lass$ (.g!t=am!$ (>)- P?%T m!tho# r!Puir!#.)(*
+
+
Compile and Running Servlet:
Compile above servlet UploadServlet and create required entry in web.xml file as follows.

Ns!rvl!t.
Ns!rvl!t;nam!.5ploa#%!rvl!tN/s!rvl!t;nam!.
Ns!rvl!t;class.5ploa#%!rvl!tN/s!rvl!t;class.
N/s!rvl!t.
Ns!rvl!t;mapping.
Ns!rvl!t;nam!.5ploa#%!rvl!tN/s!rvl!t;nam!.
Nurl;patt!rn./5ploa#%!rvl!tN/url;patt!rn.
N/s!rvl!t;mapping.
Now try to upload files using the HTML form which you created above. When you would try
http://localhost:8080/UploadFile.htm, it would display following result which would help you uploading
any file from your local machine.

File Upload:
%!l!ct a fil! to uploa#-




If your servelt script works fine, your file should be uploaded in c:\apache-tomcat-
5.5.29\webapps\data\ directory.
Servlets - Handling Date
MAT SOFT
JAVA REFERENCE GUIDE
423
One of the most important advantages of using Servlet is that you can use most of the methods
available in core Java. This mat-soft would take you through Java provided )ate class which is
available in #ava1ti$ package, this class encapsulates the current date and time.
The Date class supports two constructors. The first constructor initializes the object with the current
date and time.
4at!$ (
The following constructor accepts one argument that equals the number of milliseconds that have
elapsed since midnight, January 1, 1970
4at!$long millis!c(
Once you have a Date object available, you can call any of the following support methods to play with
dates:
SN Methods 3ith )escription
1 "oo$ean after,)ate date/
Returns true if the invoking Date object contains a date that is later than the one specified by
date, otherwise, it returns false.
2 "oo$ean "efore,)ate date/
Returns true if the invoking Date object contains a date that is earlier than the one specified by
date, otherwise, it returns false.
3 !"#ect c$one, /
Duplicates the invoking Date object.
4 int compareTo,)ate date/
Compares the value of the invoking object with that of date. Returns 0 if the values are equal.
Returns a negative value if the invoking object is earlier than date. Returns a positive value if the
invoking object is later than date.
5 int compareTo,!"#ect o"#/
Operates identically to compareTo(Date) if obj is of class Date. Otherwise, it throws a
ClassCastException.
6 "oo$ean e;a$s,!"#ect date/
Returns true if the invoking Date object contains the same time and date as the one specified by
date, otherwise, it returns false.
7 $ong getTime, /
Returns the number of milliseconds that have elapsed since January 1, 1970.
MAT SOFT
JAVA REFERENCE GUIDE
424
8 int hashCode, /
Returns a hash code for the invoking object.
9 void setTime,$ong time/
Sets the time and date as specified by time, which represents an elapsed time in milliseconds
from midnight, January 1, 1970
10 String toString, /
Converts the invoking Date object into a string and returns the result.
Getting Current Date & Time
This is very easy to get current date and time in Java Servlet. You can use a simple Date object
with to2tring() method to print current date and time as follows:
// 6mport r!Puir!# java librari!s
import java.io.**
import java.util.4at!*
import java:.s!rvl!t.**
import java:.s!rvl!t.http.**

// 3:t!n# ttp%!rvl!t class
public class ,urr!nt4at! !:t!n#s ttp%!rvl!t {

public voi# #o8!t$ttp%!rvl!t7!Pu!st r!Pu!st2
ttp%!rvl!t7!spons! r!spons!(
throws %!rvl!t3:c!ption2 6?3:c!ption
{
// %!t r!spons! cont!nt typ!
r!spons!.s!t,ont!ntTyp!$)t!:t/html)(*

Print"rit!r out 9 r!spons!.g!t"rit!r$(*
%tring titl! 9 )4isplay ,urr!nt 4at! [ Tim!)*
4at! #at! 9 n!w 4at!$(*
%tring #ocTyp! 9
)NG#octyp! html public O);//wDc//#t# html F.E ) >
)transitional//!nO).On)*
out.println$#ocTyp! >
)Nhtml.On) >
)Nh!a#.Ntitl!.) > titl! > )N/titl!.N/h!a#.On) >
)Nbo#y bgcolor9O)^fEfEfEO).On) >
)NhC align9O)c!nt!rO).) > titl! > )N/hC.On) >
)Nh@ align9O)c!nt!rO).) > #at!.to%tring$( > )N/h@.On) >
)N/bo#y.N/html.)(*
+
+
Now let us compile above servlet and create appropriate entries in web.xml and then call this servlet
using URL http://localhost:8080/CurrentDate. This would produce following result:
MAT SOFT
JAVA REFERENCE GUIDE
425
Display Current Date & Time
Mon Jun 21 21:46:49 GMT+04:00 2010
Try to refersh URL http://localhost:8080/CurrentDate and you would find difference in seconds
everytime you would refresh.
Date Comparison:
As I mentioned above you can use all the available Java methods in your Servlet. In case you need to
compare two dates, following are the methods:
You can use getTime( ) to obtain the number of milliseconds that have elapsed since midnight,
January 1, 1970, for both objects and then compare these two values.
You can use the methods before( ), after( ), and equals( ). Because the 12th of the month
comes before the 18th, for example, new Date(99, 2, 12).before(new Date (99, 2, 18))
returns true.
You can use the compareTo( ) method, which is defined by the Comparable interface and
implemented by Date.
Date Formatting using SimpleDateFormat:
SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner.
SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting.
Let us modify above example as follows:
// 6mport r!Puir!# java librari!s
import java.io.**
import java.t!:t.**
import java.util.4at!*
import java:.s!rvl!t.**
import java:.s!rvl!t.http.**

// 3:t!n# ttp%!rvl!t class
public class ,urr!nt4at! !:t!n#s ttp%!rvl!t {

public voi# #o8!t$ttp%!rvl!t7!Pu!st r!Pu!st2
ttp%!rvl!t7!spons! r!spons!(
throws %!rvl!t3:c!ption2 6?3:c!ption
{
// %!t r!spons! cont!nt typ!
r!spons!.s!t,ont!ntTyp!$)t!:t/html)(*

Print"rit!r out 9 r!spons!.g!t"rit!r$(*
%tring titl! 9 )4isplay ,urr!nt 4at! [ Tim!)*
4at! #=ow 9 n!w 4at!$ (*
MAT SOFT
JAVA REFERENCE GUIDE
426
%impl!4at!Format ft 9
n!w %impl!4at!Format $)3 yyyy.MM.## 'at' hh-mm-ss a ///)(*
%tring #ocTyp! 9
)NG#octyp! html public O);//wDc//#t# html F.E ) >
)transitional//!nO).On)*
out.println$#ocTyp! >
)Nhtml.On) >
)Nh!a#.Ntitl!.) > titl! > )N/titl!.N/h!a#.On) >
)Nbo#y bgcolor9O)^fEfEfEO).On) >
)NhC align9O)c!nt!rO).) > titl! > )N/hC.On) >
)Nh@ align9O)c!nt!rO).) > ft.format$#=ow( > )N/h@.On) >
)N/bo#y.N/html.)(*
+
+
Compile above servlet once again and then call this servlet using URL
http://localhost:8080/CurrentDate. This would produce following result:
Display Current Date & Time
Mon 2010.06.21 at 10:06:44 PM GMT+04:00
Simple DateFormat format codes:
To specify the time format use a time pattern string. In this pattern, all ASCII letters are reserved as
pattern letters, which are defined as the following:
Character )escription 7xamp$e
G Era designator AD
y Year in four digits 2001
M Month in year July or 07
d Day in month 10
h Hour in A.M./P.M. (1~12) 12
H Hour in day (0~23) 22
m Minute in hour 30
s Second in minute 55
MAT SOFT
JAVA REFERENCE GUIDE
427
S Millisecond 234
E Day in week Tuesday
D Day in year 360
F Day of week in month 2 (second Wed. in July)
w Week in year 40
W Week in month 1
a A.M./P.M. marker PM
k Hour in day (1~24) 24
K Hour in A.M./P.M. (0~11) 10
z Time zone Eastern Standard Time
' Escape for text Delimiter
" Single quote `
For a complete list of constant available methods to manipulate date, you can refer to standard Java
documentation.
Servlets - Page Redirection
Page redirection is generally used when a document moves to a new location and we need to send the
client to this new location or may be because of load balancing, or for simple randomization.
The simplest way of redirecting a request to another page is using method send'edirect,/ of
response object. Following is the signature of this method:
MAT SOFT
JAVA REFERENCE GUIDE
428
public voi# ttp%!rvl!t7!spons!.s!n#7!#ir!ct$%tring location(
throws 6?3:c!ption
This method sends back the response to the browser along with the status code and new page
location. You can also use setStatus() and setHeader() methods together to achieve the same:
....
%tring sit! 9 )http-//www.n!wpag!.com) *
r!spons!.s!t%tatus$r!spons!.%,TM?B34TT3MP?70761A(*
r!spons!.s!t!a#!r$)1ocation)2 sit!(*
....
Example:
This example shows how a servlet performs page redirection to an another location:
import java.io.**
import java.sPl.4at!*
import java.util.**
import java:.s!rvl!t.**
import java:.s!rvl!t.http.**
public class Pag!7!#ir!ct !:t!n#s ttp%!rvl!t{

public voi# #o8!t$ttp%!rvl!t7!Pu!st r!Pu!st2
ttp%!rvl!t7!spons! r!spons!(
throws %!rvl!t3:c!ption2 6?3:c!ption
{
// %!t r!spons! cont!nt typ!
r!spons!.s!t,ont!ntTyp!$)t!:t/html)(*
// =!w location to b! r!#ir!ct!#
%tring sit! 9 n!w %tring$)http-//www.photofuntoos.com)(*
r!spons!.s!t%tatus$r!spons!.%,TM?B34TT3MP?70761A(*
r!spons!.s!t!a#!r$)1ocation)2 sit!(*
+
+
Now let us compile above servlet and create following entries in web.xml
....
Ns!rvl!t.
Ns!rvl!t;nam!.Pag!7!#ir!ctN/s!rvl!t;nam!.
Ns!rvl!t;class.Pag!7!#ir!ctN/s!rvl!t;class.
N/s!rvl!t.
Ns!rvl!t;mapping.
Ns!rvl!t;nam!.Pag!7!#ir!ctN/s!rvl!t;nam!.
Nurl;patt!rn./Pag!7!#ir!ctN/url;patt!rn.
MAT SOFT
JAVA REFERENCE GUIDE
429
N/s!rvl!t;mapping.
....
Now call this servlet using URL http://localhost:8080/PageRedirect. This would take you given URL
http://www.photofuntoos.com.
Servlets - Hits Counter
Hit Counter for a Web Page:
Many times you would be interested in knowing total number of hits on a particular page of your
website. It is very simple to count these hits using a servlet because the life cycle of a servlet is
controlled by the container in which it runs.
Following are the steps to be taken to implement a simple page hit counter which is based on Servlet
Life Cycle:
Initialize a global variable in init() method.
Increase global variable every time either doGet() or doPost() method is called.
If required, you can use a database table to store the value of global variable in destroy()
method. This value can be read inside init() method when servlet would be initialized next
time. This step is optional.
If you want to count only unique page hits with-in a session then you can use isNew() method
to check if same page already have been hit with-in that session. This step is optional.
You can display value of the global counter to show total number of hits on your web site. This
step is also optional.
Here I'm assuming that the web container will not be restarted. If it is restarted or servlet destroyed,
the hit counter will be reset.
Example:
This example shows how to implement a simple page hit counter:
import java.io.**
import java.sPl.4at!*
import java.util.**
import java:.s!rvl!t.**
import java:.s!rvl!t.http.**
public class Pag!it,ount!r !:t!n#s ttp%!rvl!t{

MAT SOFT
JAVA REFERENCE GUIDE
430
privat! int hit,ount*

public voi# init$(
{
// 7!s!t hit count!r.
hit,ount 9 E*
+
public voi# #o8!t$ttp%!rvl!t7!Pu!st r!Pu!st2
ttp%!rvl!t7!spons! r!spons!(
throws %!rvl!t3:c!ption2 6?3:c!ption
{
// %!t r!spons! cont!nt typ!
r!spons!.s!t,ont!ntTyp!$)t!:t/html)(*
// This m!tho# !:!cut!s wh!n!v!r th! s!rvl!t is hit
// incr!m!nt hit,ount
hit,ount>>*
Print"rit!r out 9 r!spons!.g!t"rit!r$(*
%tring titl! 9 )Total =umb!r of its)*
%tring #ocTyp! 9
)NG#octyp! html public O);//wDc//#t# html F.E ) >
)transitional//!nO).On)*
out.println$#ocTyp! >
)Nhtml.On) >
)Nh!a#.Ntitl!.) > titl! > )N/titl!.N/h!a#.On) >
)Nbo#y bgcolor9O)^fEfEfEO).On) >
)NhC align9O)c!nt!rO).) > titl! > )N/hC.On) >
)Nh@ align9O)c!nt!rO).) > hit,ount > )N/h@.On) >
)N/bo#y.N/html.)(*
+
public voi# #!stroy$(
{
// This is optional st!p but if you li<! you
// can writ! hit,ount valu! in your #atabas!.
+
+
Now let us compile above servlet and create following entries in web.xml
....
Ns!rvl!t.
Ns!rvl!t;nam!.Pag!it,ount!rN/s!rvl!t;nam!.
Ns!rvl!t;class.Pag!it,ount!rN/s!rvl!t;class.
N/s!rvl!t.
Ns!rvl!t;mapping.
Ns!rvl!t;nam!.Pag!it,ount!rN/s!rvl!t;nam!.
Nurl;patt!rn./Pag!it,ount!rN/url;patt!rn.
N/s!rvl!t;mapping.
....
Now call this servlet using URL http://localhost:8080/PageHitCounter. This would increase counter by
one every time this page gets refreshed and it would display following result:
MAT SOFT
JAVA REFERENCE GUIDE
431
Total Number of Hits
6
Hit Counter for a Website:
Many times you would be interested in knowing total number of hits on your whole website. This is
also very simple in Servlet and we can achieve this using filters.
Following are the steps to be taken to implement a simple website hit counter which is based on Filter
Life Cycle:
Initialize a global variable in init() method of a filter.
Increase global variable every time doFilter method is called.
If required, you can use a database table to store the value of global variable in destroy()
method of filter. This value can be read inside init() method when filter would be initialized
next time. This step is optional.
Here I'm assuming that the web container will not be restarted. If it is restarted or servlet destroyed,
the hit counter will be reset.
Example:
This example shows how to implement a simple website hit counter:
// 6mport r!Puir!# java librari!s
import java.io.**
import java:.s!rvl!t.**
import java:.s!rvl!t.http.**
import java.util.**
public class %it!it,ount!r impl!m!nts Filt!r{

privat! int hit,ount*

public voi# init$Filt!r,onfig config(
throws %!rvl!t3:c!ption{
// 7!s!t hit count!r.
hit,ount 9 E*
+
public voi# #oFilt!r$%!rvl!t7!Pu!st r!Pu!st2
%!rvl!t7!spons! r!spons!2
Filt!r,hain chain(
throws java.io.6?3:c!ption2 %!rvl!t3:c!ption {
// incr!as! count!r by on!
MAT SOFT
JAVA REFERENCE GUIDE
432
hit,ount>>*
// Print th! count!r.
%yst!m.out.println$)%it! visits count -)> hit,ount (*
// Pass r!Pu!st bac< #own th! filt!r chain
chain.#oFilt!r$r!Pu!st2r!spons!(*
+
public voi# #!stroy$(
{
// This is optional st!p but if you li<! you
// can writ! hit,ount valu! in your #atabas!.
+
+
Now let us compile above servlet and create following entries in web.xml
....
Nfilt!r.
Nfilt!r;nam!.%it!it,ount!rN/filt!r;nam!.
Nfilt!r;class.%it!it,ount!rN/filt!r;class.
N/filt!r.
Nfilt!r;mapping.
Nfilt!r;nam!.%it!it,ount!rN/filt!r;nam!.
Nurl;patt!rn./*N/url;patt!rn.
N/filt!r;mapping.
....
Now call any URL like URL http://localhost:8080/. This would increase counter by one every time any
page gets a hit and it would display following message in the log:
%it! visits count - C
%it! visits count - @
%it! visits count - D
%it! visits count - F
%it! visits count - H
..................
Servlets - Auto Page Refresh
Consider a webpage which is displaying live game score or stock market status or currency exchange
ration. For all such type of pages, you would need to refresh your web page regularly using referesh or
reload button with your browser.
Java Servlet makes this job easy by providing you a mechanism where you can make a webpage in
such a way that it would refresh automatically after a given interval.
MAT SOFT
JAVA REFERENCE GUIDE
433
The simplest way of refreshing a web page is using method setInt(eader,/ of response object.
Following is the signature of this method:
public voi# s!t6nt!a#!r$%tring h!a#!r2 int h!a#!rBalu!(
This method sends back header "Refresh" to the browser along with an integer value which indicates
time interval in seconds.
Auto Page Refresh Example:
This example shows how a servlet performs auto page refresh using setInt(eader,/ method to
set 'efresh header.
// 6mport r!Puir!# java librari!s
import java.io.**
import java:.s!rvl!t.**
import java:.s!rvl!t.http.**
import java.util.**

// 3:t!n# ttp%!rvl!t class
public class 7!fr!sh !:t!n#s ttp%!rvl!t {

// M!tho# to han#l! 83T m!tho# r!Pu!st.
public voi# #o8!t$ttp%!rvl!t7!Pu!st r!Pu!st2
ttp%!rvl!t7!spons! r!spons!(
throws %!rvl!t3:c!ption2 6?3:c!ption
{
// %!t r!fr!sh2 autoloa# tim! as H s!con#s
r!spons!.s!t6nt!a#!r$)7!fr!sh)2 H(*

// %!t r!spons! cont!nt typ!
r!spons!.s!t,ont!ntTyp!$)t!:t/html)(*

// 8!t curr!nt tim!
,al!n#ar cal!n#ar 9 n!w 8r!gorian,al!n#ar$(*
%tring amTpm*
int hour 9 cal!n#ar.g!t$,al!n#ar.?57(*
int minut! 9 cal!n#ar.g!t$,al!n#ar.M6=5T3(*
int s!con# 9 cal!n#ar.g!t$,al!n#ar.%3,?=4(*
if$cal!n#ar.g!t$,al!n#ar.0MTPM( 99 E(
amTpm 9 )0M)*
!ls!
amTpm 9 )PM)*

%tring ,T 9 hour>)-)> minut! >)-)> s!con# >) )> amTpm*

Print"rit!r out 9 r!spons!.g!t"rit!r$(*
%tring titl! 9 )0uto Pag! 7!fr!sh using %!rvl!t)*
%tring #ocTyp! 9
)NG#octyp! html public O);//wDc//#t# html F.E ) >
)transitional//!nO).On)*
out.println$#ocTyp! >
MAT SOFT
JAVA REFERENCE GUIDE
434
)Nhtml.On) >
)Nh!a#.Ntitl!.) > titl! > )N/titl!.N/h!a#.On)>
)Nbo#y bgcolor9O)^fEfEfEO).On) >
)NhC align9O)c!nt!rO).) > titl! > )N/hC.On) >
)Np.,urr!nt Tim! is- ) > ,T > )N/p.On)(*
+
// M!tho# to han#l! P?%T m!tho# r!Pu!st.
public voi# #oPost$ttp%!rvl!t7!Pu!st r!Pu!st2
ttp%!rvl!t7!spons! r!spons!(
throws %!rvl!t3:c!ption2 6?3:c!ption {
#o8!t$r!Pu!st2 r!spons!(*
+
+
Now let us compile above servlet and create following entries in web.xml
....
Ns!rvl!t.
Ns!rvl!t;nam!.7!fr!shN/s!rvl!t;nam!.
Ns!rvl!t;class.7!fr!shN/s!rvl!t;class.
N/s!rvl!t.

Ns!rvl!t;mapping.
Ns!rvl!t;nam!.7!fr!shN/s!rvl!t;nam!.
Nurl;patt!rn./7!fr!shN/url;patt!rn.
N/s!rvl!t;mapping.
....
Now call this servlet using URL http://localhost:8080/Refresh which would display current system time
after every 5 seconds as follows. Just run the servlet and wait to see the result:
Auto Page Refresh using Servlet
Current Time is: 9:44:50 PM
Servlets - Sending Email
To send an email using your a Servlet is simple enough but to start with you should haveJavaMai$
%PI and Java %ctivation +rame3or= ,J%+/ installed on your machine.
You can download latest version of JavaMail (Version 1.2) from Java's standard website.
You can download latest version of JAF (Version 1.1.1) from Java's standard website.
MAT SOFT
JAVA REFERENCE GUIDE
435
Download and unzip these files, in the newly created top level directories you will find a number of jar
files for both the applications. You need to add mai$1#ar and activation1#ar files in your CLASSPATH.
Send a Simple Email:
Here is an example to send a simple email from your machine. Here it is assumed that
your$oca$host is connected to the internet and capable enough to send an email. Same time make
sure all the jar files from Java Email API package and JAF package ara available in CLASSPATH.
// Fil! =am! %!n#3mail.java
import java.io.**
import java.util.**
import java:.s!rvl!t.**
import java:.s!rvl!t.http.**
import java:.mail.**
import java:.mail.int!rn!t.**
import java:.activation.**

public class %!n#3mail !:t!n#s ttp%!rvl!t{

public voi# #o8!t$ttp%!rvl!t7!Pu!st r!Pu!st2
ttp%!rvl!t7!spons! r!spons!(
throws %!rvl!t3:c!ption2 6?3:c!ption
{
// 7!cipi!nt's !mail 64 n!!#s to b! m!ntion!#.
%tring to 9 )abc#\gmail.com)*

// %!n#!r's !mail 64 n!!#s to b! m!ntion!#
%tring from 9 )w!b\gmail.com)*

// 0ssuming you ar! s!n#ing !mail from localhost
%tring host 9 )localhost)*

// 8!t syst!m prop!rti!s
Prop!rti!s prop!rti!s 9 %yst!m.g!tProp!rti!s$(*

// %!tup mail s!rv!r
prop!rti!s.s!tProp!rty$)mail.smtp.host)2 host(*

// 8!t th! #!fault %!ssion obj!ct.
%!ssion s!ssion 9 %!ssion.g!t4!fault6nstanc!$prop!rti!s(*

// %!t r!spons! cont!nt typ!
r!spons!.s!t,ont!ntTyp!$)t!:t/html)(*
Print"rit!r out 9 r!spons!.g!t"rit!r$(*
try{
// ,r!at! a #!fault Mim!M!ssag! obj!ct.
Mim!M!ssag! m!ssag! 9 n!w Mim!M!ssag!$s!ssion(*
// %!t From- h!a#!r fi!l# of th! h!a#!r.
m!ssag!.s!tFrom$n!w 6nt!rn!t0##r!ss$from((*
// %!t To- h!a#!r fi!l# of th! h!a#!r.
m!ssag!.a##7!cipi!nt$M!ssag!.7!cipi!ntTyp!.T?2
n!w 6nt!rn!t0##r!ss$to((*
MAT SOFT
JAVA REFERENCE GUIDE
436
// %!t %ubj!ct- h!a#!r fi!l#
m!ssag!.s!t%ubj!ct$)This is th! %ubj!ct 1in!G)(*
// =ow s!t th! actual m!ssag!
m!ssag!.s!tT!:t$)This is actual m!ssag!)(*
// %!n# m!ssag!
Transport.s!n#$m!ssag!(*
%tring titl! 9 )%!n# 3mail)*
%tring r!s 9 )%!nt m!ssag! succ!ssfully....)*
%tring #ocTyp! 9
)NG#octyp! html public O);//wDc//#t# html F.E ) >
)transitional//!nO).On)*
out.println$#ocTyp! >
)Nhtml.On) >
)Nh!a#.Ntitl!.) > titl! > )N/titl!.N/h!a#.On) >
)Nbo#y bgcolor9O)^fEfEfEO).On) >
)NhC align9O)c!nt!rO).) > titl! > )N/hC.On) >
)Np align9O)c!nt!rO).) > r!s > )N/p.On) >
)N/bo#y.N/html.)(*
+catch $M!ssaging3:c!ption m!:( {
m!:.print%tac<Trac!$(*
+
+
+
Now let us compile above servlet and create following entries in web.xml
....
Ns!rvl!t.
Ns!rvl!t;nam!.%!n#3mailN/s!rvl!t;nam!.
Ns!rvl!t;class.%!n#3mailN/s!rvl!t;class.
N/s!rvl!t.

Ns!rvl!t;mapping.
Ns!rvl!t;nam!.%!n#3mailN/s!rvl!t;nam!.
Nurl;patt!rn./%!n#3mailN/url;patt!rn.
N/s!rvl!t;mapping.
....
Now call this servlet using URL http://localhost:8080/SendEmail which would send an email to given
email ID abcdFgmail.com and would display following response:
Send Email
Sent message successfully....
If you want to send an email to multiple recipients then following methods would be used to specify
multiple email IDs:
voi# a##7!cipi!nts$M!ssag!.7!cipi!ntTyp! typ!2
0##r!ss&' a##r!ss!s(
throws M!ssaging3:c!ption
MAT SOFT
JAVA REFERENCE GUIDE
437
Here is the description of the parameters:
type: This would be set to TO, CC or BCC. Here CC represents Carbon Copy and BCC
represents Black Carbon Copy. Example #essage..ecipientType.TO
addresses: This is the array of email ID. You would need to use InternetAddress() method
while specifying email IDs
Send an HTML Email:
Here is an example to send an HTML email from your machine. Here it is assumed that
your$oca$host is connected to the internet and capable enough to send an email. Same time make
sure all the jar files from Java Email API package and JAF package ara available in CLASSPATH.
This example is very similar to previous one, except here we are using setContent() method to set
content whose second argument is "text/html" to specify that the HTML content is included in the
message.
Using this example, you can send as big as HTML content you like.
// Fil! =am! %!n#3mail.java
import java.io.**
import java.util.**
import java:.s!rvl!t.**
import java:.s!rvl!t.http.**
import java:.mail.**
import java:.mail.int!rn!t.**
import java:.activation.**

public class %!n#3mail !:t!n#s ttp%!rvl!t{

public voi# #o8!t$ttp%!rvl!t7!Pu!st r!Pu!st2
ttp%!rvl!t7!spons! r!spons!(
throws %!rvl!t3:c!ption2 6?3:c!ption
{
// 7!cipi!nt's !mail 64 n!!#s to b! m!ntion!#.
%tring to 9 )abc#\gmail.com)*

// %!n#!r's !mail 64 n!!#s to b! m!ntion!#
%tring from 9 )w!b\gmail.com)*

// 0ssuming you ar! s!n#ing !mail from localhost
%tring host 9 )localhost)*

// 8!t syst!m prop!rti!s
Prop!rti!s prop!rti!s 9 %yst!m.g!tProp!rti!s$(*

// %!tup mail s!rv!r
prop!rti!s.s!tProp!rty$)mail.smtp.host)2 host(*

// 8!t th! #!fault %!ssion obj!ct.
%!ssion s!ssion 9 %!ssion.g!t4!fault6nstanc!$prop!rti!s(*

// %!t r!spons! cont!nt typ!
MAT SOFT
JAVA REFERENCE GUIDE
438
r!spons!.s!t,ont!ntTyp!$)t!:t/html)(*
Print"rit!r out 9 r!spons!.g!t"rit!r$(*
try{
// ,r!at! a #!fault Mim!M!ssag! obj!ct.
Mim!M!ssag! m!ssag! 9 n!w Mim!M!ssag!$s!ssion(*
// %!t From- h!a#!r fi!l# of th! h!a#!r.
m!ssag!.s!tFrom$n!w 6nt!rn!t0##r!ss$from((*
// %!t To- h!a#!r fi!l# of th! h!a#!r.
m!ssag!.a##7!cipi!nt$M!ssag!.7!cipi!ntTyp!.T?2
n!w 6nt!rn!t0##r!ss$to((*
// %!t %ubj!ct- h!a#!r fi!l#
m!ssag!.s!t%ubj!ct$)This is th! %ubj!ct 1in!G)(*
// %!n# th! actual TM1 m!ssag!2 as big as you li<!
m!ssag!.s!t,ont!nt$)NhC.This is actual m!ssag!N/hC.)2
)t!:t/html) (*
// %!n# m!ssag!
Transport.s!n#$m!ssag!(*
%tring titl! 9 )%!n# 3mail)*
%tring r!s 9 )%!nt m!ssag! succ!ssfully....)*
%tring #ocTyp! 9
)NG#octyp! html public O);//wDc//#t# html F.E ) >
)transitional//!nO).On)*
out.println$#ocTyp! >
)Nhtml.On) >
)Nh!a#.Ntitl!.) > titl! > )N/titl!.N/h!a#.On) >
)Nbo#y bgcolor9O)^fEfEfEO).On) >
)NhC align9O)c!nt!rO).) > titl! > )N/hC.On) >
)Np align9O)c!nt!rO).) > r!s > )N/p.On) >
)N/bo#y.N/html.)(*
+catch $M!ssaging3:c!ption m!:( {
m!:.print%tac<Trac!$(*
+
+
+
Compile and run above servlet to send HTML message on a given email ID.
Send Attachment in Email:
Here is an example to send an email with attachment from your machine. Here it is assumed that
your $oca$host is connected to the internet and capable enough to send an email.
// Fil! =am! %!n#3mail.java
import java.io.**
import java.util.**
import java:.s!rvl!t.**
import java:.s!rvl!t.http.**
import java:.mail.**
import java:.mail.int!rn!t.**
import java:.activation.**
MAT SOFT
JAVA REFERENCE GUIDE
439

public class %!n#3mail !:t!n#s ttp%!rvl!t{

public voi# #o8!t$ttp%!rvl!t7!Pu!st r!Pu!st2
ttp%!rvl!t7!spons! r!spons!(
throws %!rvl!t3:c!ption2 6?3:c!ption
{
// 7!cipi!nt's !mail 64 n!!#s to b! m!ntion!#.
%tring to 9 )abc#\gmail.com)*

// %!n#!r's !mail 64 n!!#s to b! m!ntion!#
%tring from 9 )w!b\gmail.com)*

// 0ssuming you ar! s!n#ing !mail from localhost
%tring host 9 )localhost)*

// 8!t syst!m prop!rti!s
Prop!rti!s prop!rti!s 9 %yst!m.g!tProp!rti!s$(*

// %!tup mail s!rv!r
prop!rti!s.s!tProp!rty$)mail.smtp.host)2 host(*

// 8!t th! #!fault %!ssion obj!ct.
%!ssion s!ssion 9 %!ssion.g!t4!fault6nstanc!$prop!rti!s(*

// %!t r!spons! cont!nt typ!
r!spons!.s!t,ont!ntTyp!$)t!:t/html)(*
Print"rit!r out 9 r!spons!.g!t"rit!r$(*
try{
// ,r!at! a #!fault Mim!M!ssag! obj!ct.
Mim!M!ssag! m!ssag! 9 n!w Mim!M!ssag!$s!ssion(*

// %!t From- h!a#!r fi!l# of th! h!a#!r.
m!ssag!.s!tFrom$n!w 6nt!rn!t0##r!ss$from((*

// %!t To- h!a#!r fi!l# of th! h!a#!r.
m!ssag!.a##7!cipi!nt$M!ssag!.7!cipi!ntTyp!.T?2
n!w 6nt!rn!t0##r!ss$to((*

// %!t %ubj!ct- h!a#!r fi!l#
m!ssag!.s!t%ubj!ct$)This is th! %ubj!ct 1in!G)(*

// ,r!at! th! m!ssag! part
Lo#yPart m!ssag!Lo#yPart 9 n!w Mim!Lo#yPart$(*

// Fill th! m!ssag!
m!ssag!Lo#yPart.s!tT!:t$)This is m!ssag! bo#y)(*

// ,r!at! a multipar m!ssag!
Multipart multipart 9 n!w Mim!Multipart$(*

// %!t t!:t m!ssag! part
multipart.a##Lo#yPart$m!ssag!Lo#yPart(*

MAT SOFT
JAVA REFERENCE GUIDE
440
// Part two is attachm!nt
m!ssag!Lo#yPart 9 n!w Mim!Lo#yPart$(*
%tring fil!nam! 9 )fil!.t:t)*
4ata%ourc! sourc! 9 n!w Fil!4ata%ourc!$fil!nam!(*
m!ssag!Lo#yPart.s!t4ataan#l!r$n!w 4ataan#l!r$sourc!((*
m!ssag!Lo#yPart.s!tFil!=am!$fil!nam!(*
multipart.a##Lo#yPart$m!ssag!Lo#yPart(*

// %!n# th! compl!t! m!ssag! parts
m!ssag!.s!t,ont!nt$multipart (*

// %!n# m!ssag!
Transport.s!n#$m!ssag!(*
%tring titl! 9 )%!n# 3mail)*
%tring r!s 9 )%!nt m!ssag! succ!ssfully....)*
%tring #ocTyp! 9
)NG#octyp! html public O);//wDc//#t# html F.E ) >
)transitional//!nO).On)*
out.println$#ocTyp! >
)Nhtml.On) >
)Nh!a#.Ntitl!.) > titl! > )N/titl!.N/h!a#.On) >
)Nbo#y bgcolor9O)^fEfEfEO).On) >
)NhC align9O)c!nt!rO).) > titl! > )N/hC.On) >
)Np align9O)c!nt!rO).) > r!s > )N/p.On) >
)N/bo#y.N/html.)(*
+catch $M!ssaging3:c!ption m!:( {
m!:.print%tac<Trac!$(*
+
+
+
Compile and run above servlet to send a file as an attachement along with a message on a given email
ID.If it is required to provide user ID and Password to the email server for authentication purpose then
you can set these properties as follows:
props.s!tProp!rty$)mail.us!r)2 )myus!r)(*
props.s!tProp!rty$)mail.passwor#)2 )mypw#)(*
Day 41: Servlets - Writing Filters
Servlet Filters are Java classes that can be used in Servlet Programming for the following purposes:
To intercept requests from a client before they access a resource at back end.
To manipulate responses from server before they are sent back to the client.
There are are various types of filters suggested by the specifications:
Authentication Filters.
Data compression Filters
Encryption Filters .
MAT SOFT
JAVA REFERENCE GUIDE
441
Filters that trigger resource access events.
Image Conversion Filters .
Logging and Auditing Filters.
MIME-TYPE Chain Filters.
Tokenizing Filters .
XSL/T Filters That Transform XML Content.
Filters are deployed in the deployment descriptor file 3e"1xm$ and then map to either servlet names
or URL patterns in your application's deployment descriptor.
When the web container starts up your web application, it creates an instance of each filter that you
have declared in the deployment descriptor. The filters execute in the order that they are declared in
the deployment descriptor.
Servlet Filter Methods:
A filter is simply a Java class that implements the javax.servlet.Filter interface. The javax.servlet.Filter
interface defines three methods:
S1N1 Method : )escription
1 p"$ic void do+i$ter ,Serv$et'e;est< Serv$et'esponse< +i$terChain/
This method is called by the container each time a request/response pair is passed through the
chain due to a client request for a resource at the end of the chain.
2 p"$ic void init,+i$terConfig fi$terConfig/
This method is called by the web container to indicate to a filter that it is being placed into
service.
3 p"$ic void destroy,/
This method is called by the web container to indicate to a filter that it is being taken out of
service.
Servlet Filter Example:
Following is the Servlet Filter Example that would print the clients IP address and current date time.
This example would give you basic understanding of Servlet Filter, but you can write more
sophisticated filter applications using the same concept:
// 6mport r!Puir!# java librari!s
import java.io.**
import java:.s!rvl!t.**
import java:.s!rvl!t.http.**
import java.util.**
// 6mpl!m!nts Filt!r class
public class 1ogFilt!r impl!m!nts Filt!r {
MAT SOFT
JAVA REFERENCE GUIDE
442
public voi# init$Filt!r,onfig config(
throws %!rvl!t3:c!ption{
// 8!t init param!t!r
%tring t!stParam 9 config.g!t6nitParam!t!r$)t!st;param)(*
//Print th! init param!t!r
%yst!m.out.println$)T!st Param- ) > t!stParam(*
+
public voi# #oFilt!r$%!rvl!t7!Pu!st r!Pu!st2
%!rvl!t7!spons! r!spons!2
Filt!r,hain chain(
throws java.io.6?3:c!ption2 %!rvl!t3:c!ption {
// 8!t th! 6P a##r!ss of cli!nt machin!.
%tring ip0##r!ss 9 r!Pu!st.g!t7!mot!0##r$(*
// 1og th! 6P a##r!ss an# curr!nt tim!stamp.
%yst!m.out.println$)6P )> ip0##r!ss > )2 Tim! )
> n!w 4at!$(.to%tring$((*
// Pass r!Pu!st bac< #own th! filt!r chain
chain.#oFilt!r$r!Pu!st2r!spons!(*
+
public voi# #!stroy$ ({
/* ,all!# b!for! th! Filt!r instanc! is r!mov!#
from s!rvic! by th! w!b contain!r*/
+
+
Compile 0og+i$ter1#ava in usual way and put your class file in <Tomcat-installation-
directory>/webapps/ROOT/WEB-INF/classes.
Servlet Filter Mapping in Web.xml:
Filters are defined and then mapped to a URL or Servlet, in much the same way as Servlet is defined
and then mapped to a URL pattern. Create the following entry for filter tag in the deployment
descriptor file 3e"1xm$
Nfilt!r.
Nfilt!r;nam!.1ogFilt!rN/filt!r;nam!.
Nfilt!r;class.1ogFilt!rN/filt!r;class.
Ninit;param.
Nparam;nam!.t!st;paramN/param;nam!.
Nparam;valu!.6nitiali/ation Paramt!rN/param;valu!.
N/init;param.
N/filt!r.
Nfilt!r;mapping.
Nfilt!r;nam!.1ogFilt!rN/filt!r;nam!.
Nurl;patt!rn./*N/url;patt!rn.
N/filt!r;mapping.
MAT SOFT
JAVA REFERENCE GUIDE
443
The above filter would apply to all the servlets because we specified KR in our configuration. You can
specicy a particular servlet path if you want to apply filter on few servlets only.
Now try to call any servlet in usual way and you would see generated log in your web server log. You
can use Log4J logger to log above log in a separate file.
Using Multiple Filters:
Your web application may define several different filters with a specific purpose. Consider, you define
two filters -uthen'ilter and Log'ilter. Rest of the process would remain as explained above except you
need to create a different mapping as mentioned below:
Nfilt!r.
Nfilt!r;nam!.1ogFilt!rN/filt!r;nam!.
Nfilt!r;class.1ogFilt!rN/filt!r;class.
Ninit;param.
Nparam;nam!.t!st;paramN/param;nam!.
Nparam;valu!.6nitiali/ation Paramt!rN/param;valu!.
N/init;param.
N/filt!r.
Nfilt!r.
Nfilt!r;nam!.0uth!nFilt!rN/filt!r;nam!.
Nfilt!r;class.0uth!nFilt!rN/filt!r;class.
Ninit;param.
Nparam;nam!.t!st;paramN/param;nam!.
Nparam;valu!.6nitiali/ation Paramt!rN/param;valu!.
N/init;param.
N/filt!r.
Nfilt!r;mapping.
Nfilt!r;nam!.1ogFilt!rN/filt!r;nam!.
Nurl;patt!rn./*N/url;patt!rn.
N/filt!r;mapping.
Nfilt!r;mapping.
Nfilt!r;nam!.0uth!nFilt!rN/filt!r;nam!.
Nurl;patt!rn./*N/url;patt!rn.
N/filt!r;mapping.
Filters Application Order:
The order of filter-mapping elements in web.xml determines the order in which the web container
applies the filter to the servlet. To reverse the order of the filter, you just need to reverse the filter-
mapping elements in the web.xml file.
For example, above example would apply LogFilter first and then it would apply AuthenFilter to any
servlet but the following example would reverse the order:
Nfilt!r;mapping.
Nfilt!r;nam!.0uth!nFilt!rN/filt!r;nam!.
MAT SOFT
JAVA REFERENCE GUIDE
444
Nurl;patt!rn./*N/url;patt!rn.
N/filt!r;mapping.
Nfilt!r;mapping.
Nfilt!r;nam!.1ogFilt!rN/filt!r;nam!.
Nurl;patt!rn./*N/url;patt!rn.
N/filt!r;mapping.
Servlets - Exception Handling
When a servlet throws an exception, the web container searches the configurations in 3e"1xm$that
use the exception-type element for a match with the thrown exception type.
You would have to use the error&page element in web.xml to specify the invocation of servlets in
response to certain exceptions or HTTP stats codes.
web.xml Confguration:
Consider, you have an =rror)andler servelt which would be called whenever there is any defined
exception or error. Following would be the entry created in web.xml.
NG;; s!rvl!t #!finition ;;.
Ns!rvl!t.
Ns!rvl!t;nam!.3rroran#l!rN/s!rvl!t;nam!.
Ns!rvl!t;class.3rroran#l!rN/s!rvl!t;class.
N/s!rvl!t.
NG;; s!rvl!t mappings ;;.
Ns!rvl!t;mapping.
Ns!rvl!t;nam!.3rroran#l!rN/s!rvl!t;nam!.
Nurl;patt!rn./3rroran#l!rN/url;patt!rn.
N/s!rvl!t;mapping.
NG;; !rror;co#! r!lat!# !rror pag!s ;;.
N!rror;pag!.
N!rror;co#!.FEFN/!rror;co#!.
Nlocation./3rroran#l!rN/location.
N/!rror;pag!.
N!rror;pag!.
N!rror;co#!.FEDN/!rror;co#!.
Nlocation./3rroran#l!rN/location.
N/!rror;pag!.
NG;; !:c!ption;typ! r!lat!# !rror pag!s ;;.
N!rror;pag!.
N!:c!ption;typ!.
java:.s!rvl!t.%!rvl!t3:c!ption
N/!:c!ption;typ! .
Nlocation./3rroran#l!rN/location.
N/!rror;pag!.
N!rror;pag!.
MAT SOFT
JAVA REFERENCE GUIDE
445
N!:c!ption;typ!.java.io.6?3:c!ptionN/!:c!ption;typ! .
Nlocation./3rroran#l!rN/location.
N/!rror;pag!.
If you want to have a generic Error Handler for all the exceptions then you should define following
error-page instead of defining separate error-page elements for every exception:
N!rror;pag!.
N!:c!ption;typ!.java.lang.Throwabl!N/!:c!ption;typ! .
Nlocation./3rroran#l!rN/location.
N/!rror;pag!.
Following are the points to be noted about above web.xml for Exception Handling:
The servelt ErrorHandler is defined in usual way as any other servlet and configured in
web.xml.
If there is any error with status code either 404 ( Not Found) or 403 ( Forbidden ), then
ErrorHandler servlet would be called.
If the web application throws either 2er!let=xception or 5O=xception, then the web container
invokes the /ErrorHandler servlet.
You can define different Error Handlers to handle different type of errors or exceptions. Above
example is very much generic and hope it serve the purpose to explain you the basic concept.
Request Attributes - Errors/Exceptions:
Following is the list of request attributes that an error-handling servlet can access to analyse the
nature of error/exception.
S1N1 %ttri"te : )escription
1 #avax1serv$et1error1statsGcode
This attribute give status code which can be stored and analysed after storing in a
java.lang.Integer data type.
2 #avax1serv$et1error1exceptionGtype
This attribute gives information about exception type which can be stored and analysed after
storing in a java.lang.Class data type.
3 #avax1serv$et1error1message
This attribute gives information exact error message which can be stored and analysed after
storing in a java.lang.String data type.
4 #avax1serv$et1error1re;estGri
This attribute gives information about URL calling the servlet and it can be stored and analysed
after storing in a java.lang.String data type.
5 #avax1serv$et1error1exception
This attribute gives information the exception raised which can be stored and analysed after
storing in a java.lang.Throwable data type.
6 #avax1serv$et1error1serv$etGname
MAT SOFT
JAVA REFERENCE GUIDE
446
This attribute gives servlet name which can be stored and analysed after storing in a
java.lang.String data type.
Error Handler Servlet Example:
Following is the Servlet Example that would be used as Error Handler in case of any error or exception
occurs with your any of the servlet defined.This example would give you basic understanding of
Exception Handling in Servlet, but you can write more sophisticated filter applications using the same
concept:
import java.io.**
import java:.s!rvl!t.**
import java:.s!rvl!t.http.**
import java.util.**
public class 3rroran#l!r !:t!n#s ttp%!rvl!t {

public voi# #o8!t$ttp%!rvl!t7!Pu!st r!Pu!st2 ttp%!rvl!t7!spons!
r!spons!( throws %!rvl!t3:c!ption2 6?3:c!ption
{
Throwabl! throwabl! 9 $Throwabl!(
r!Pu!st.g!t0ttribut!$)java:.s!rvl!t.!rror.!:c!ption)(*
6nt!g!r status,o#! 9 $6nt!g!r(
r!Pu!st.g!t0ttribut!$)java:.s!rvl!t.!rror.statusTco#!)(*
%tring s!rvl!t=am! 9 $%tring(
r!Pu!st.g!t0ttribut!$)java:.s!rvl!t.!rror.s!rvl!tTnam!)(*
if $s!rvl!t=am! 99 null({ s!rvl!t=am! 9 )5n<nown)* +
%tring r!Pu!st5ri 9 $%tring(
r!Pu!st.g!t0ttribut!$)java:.s!rvl!t.!rror.r!Pu!stTuri)(*
if $r!Pu!st5ri 99 null({ r!Pu!st5ri 9 )5n<nown)* +
r!spons!.s!t,ont!ntTyp!$)t!:t/html)(*

Print"rit!r out 9 r!spons!.g!t"rit!r$(*
%tring titl! 9 )3rror/3:c!ption 6nformation)*
%tring #ocTyp! 9
)NG#octyp! html public O);//wDc//#t# html F.E ) >
)transitional//!nO).On)*
out.println$#ocTyp! >
)Nhtml.On) >
)Nh!a#.Ntitl!.) > titl! > )N/titl!.N/h!a#.On) >
)Nbo#y bgcolor9O)^fEfEfEO).On)(*
if $throwabl! 99 null [[ status,o#! 99 null({
out.println$)Nh@.3rror information is missingN/h@.)(*
out.println$)Pl!as! r!turn to th! Na hr!f9O)) >
r!spons!.!nco#!571$)http-//localhost-JEJE/)( >
)O).om! Pag!N/a..)(*
+!ls! if $status,o#! G9 null({
out.println$)Th! status co#! - ) > status,o#!(*
+!ls!{
out.println$)Nh@.3rror informationN/h@.)(*
out.println$)%!rvl!t =am! - ) > s!rvl!t=am! > _N/br.N/br.)(*
out.println$)3:c!ption Typ! - ) >
MAT SOFT
JAVA REFERENCE GUIDE
447
throwabl!.g!t,lass$ (.g!t=am!$ ( >` N/br.N/br.)(*
out.println$)Th! r!Pu!st 576- ) > r!Pu!st5ri > _Nbr.Nbr.)(*
out.println$)Th! !:c!ption m!ssag!- ) >
throwabl!.g!tM!ssag!$ ((*
+
out.println$)N/bo#y.)(*
out.println$)N/html.)(*
+
public voi# #oPost$ttp%!rvl!t7!Pu!st r!Pu!st2
ttp%!rvl!t7!spons! r!spons!(
throws %!rvl!t3:c!ption2 6?3:c!ption {
#o8!t$r!Pu!st2 r!spons!(*
+
+
Compile 7rror(and$er1#ava in usual way and put your class file in <Tomcat-installation-
directory>/webapps/ROOT/WEB-INF/classes. Let us add the following configuration in web.xml to
handle exceptions:
Ns!rvl!t.
Ns!rvl!t;nam!.3rroran#l!rN/s!rvl!t;nam!.
Ns!rvl!t;class.3rroran#l!rN/s!rvl!t;class.
N/s!rvl!t.
NG;; s!rvl!t mappings ;;.
Ns!rvl!t;mapping.
Ns!rvl!t;nam!.3rroran#l!rN/s!rvl!t;nam!.
Nurl;patt!rn./3rroran#l!rN/url;patt!rn.
N/s!rvl!t;mapping.
N!rror;pag!.
N!rror;co#!.FEFN/!rror;co#!.
Nlocation./3rroran#l!rN/location.
N/!rror;pag!.
N!rror;pag!.
N!:c!ption;typ!.java.lang.Throwabl!N/!:c!ption;typ! .
Nlocation./3rroran#l!rN/location.
N/!rror;pag!.
Now try to use a servlet which raise any exception or type a wrong URL, this would trigger Web
Container to call 7rror(and$er servlet and display an appropriate message as programmed. For
example, if you type a wrong URL then it would display the following result:
Th! status co#! - FEF
Servlets - Internationalization
Before we proceed, let me explain three important terms:
Internationa$i2ation ,i4Pn/: This means enabling a web site to provide different versions of
content translated into the visitor's language or nationality.
0oca$i2ation ,$4In/: This means adding resources to a web site to adapt it to a particular
geographical or cultural region for example Hindi translation to a web site.
MAT SOFT
JAVA REFERENCE GUIDE
448
$oca$e: This is a particular cultural or geographical region. It is usually referred to as a
language symbol followed by a country symbol which are separated by an underscore. For
example "en_US" represents english locale for US.
There are number of items which should be taken care while building up a global website. This mat-
soft would not give you complete detail on this but it would give you a good example on how you can
offer your web page in different languages to internet community by differentiating their location ie.
locale.
A servlet can pickup appropriate version of the site based on the requester's locale and provide
appropriate site version according to the local language, culture and requirements. Following is the
method of request object which returns Locale object.
java.util.1ocal! r!Pu!st.g!t1ocal!$(
Detecting Locale:
Following are the important locale methods which you can use to detect requester's location, language
and of course locale. All the below methods display country name and language name set in
requester's browser.
S1N1 Method : )escription
1 String getContry,/
This method returns the country/region code in upper case for this locale in ISO 3166 2-letter
format.
2 String get)isp$ayContry,/
This method returns a name for the locale's country that is appropriate for display to the user.
3 String get0angage,/
This method returns the language code in lower case for this locale in ISO 639 format.
4 String get)isp$ay0angage,/
This method returns a name for the locale's language that is appropriate for display to the user.
5 String getIS!EContry,/
This method returns a three-letter abbreviation for this locale's country.
6 String getIS!E0angage,/
This method returns a three-letter abbreviation for this locale's language.
Example:
This example shows how you display a language and associated country for a request:
import java.io.**
import java:.s!rvl!t.**
import java:.s!rvl!t.http.**
MAT SOFT
JAVA REFERENCE GUIDE
449
import java.util.1ocal!*
public class 8!t1ocal! !:t!n#s ttp%!rvl!t{

public voi# #o8!t$ttp%!rvl!t7!Pu!st r!Pu!st2
ttp%!rvl!t7!spons! r!spons!(
throws %!rvl!t3:c!ption2 6?3:c!ption
{
//8!t th! cli!nt's 1ocal!
1ocal! local! 9 r!Pu!st.g!t1ocal!$(*
%tring languag! 9 local!.g!t1anguag!$(*
%tring country 9 local!.g!t,ountry$(*
// %!t r!spons! cont!nt typ!
r!spons!.s!t,ont!ntTyp!$)t!:t/html)(*
Print"rit!r out 9 r!spons!.g!t"rit!r$(*
%tring titl! 9 )4!t!cting 1ocal!)*
%tring #ocTyp! 9
)NG#octyp! html public O);//wDc//#t# html F.E ) >
)transitional//!nO).On)*
out.println$#ocTyp! >
)Nhtml.On) >
)Nh!a#.Ntitl!.) > titl! > )N/titl!.N/h!a#.On) >
)Nbo#y bgcolor9O)^fEfEfEO).On) >
)NhC align9O)c!nt!rO).) > languag! > )N/hC.On) >
)Nh@ align9O)c!nt!rO).) > country > )N/h@.On) >
)N/bo#y.N/html.)(*
+
+
Languages Setting:
A servlet can output a page written in a Western European language such as English, Spanish,
German, French, Italian, Dutch etc. Here it is important to set Content-Language header to display all
the characters properly.
Second point is to display all the special characters using HTML entities, For example, "&#241;"
represents "", and "&#161;" represents "" as follows:
import java.io.**
import java:.s!rvl!t.**
import java:.s!rvl!t.http.**
import java.util.1ocal!*
public class 4isplay%panish !:t!n#s ttp%!rvl!t{

public voi# #o8!t$ttp%!rvl!t7!Pu!st r!Pu!st2
ttp%!rvl!t7!spons! r!spons!(
throws %!rvl!t3:c!ption2 6?3:c!ption
{
// %!t r!spons! cont!nt typ!
MAT SOFT
JAVA REFERENCE GUIDE
450
r!spons!.s!t,ont!ntTyp!$)t!:t/html)(*
Print"rit!r out 9 r!spons!.g!t"rit!r$(*
// %!t spanish languag! co#!.
r!spons!.s!t!a#!r$),ont!nt;1anguag!)2 )!s)(*
%tring titl! 9 )3n 3spa[ntil#!*ol)*
%tring #ocTyp! 9
)NG#octyp! html public O);//wDc//#t# html F.E ) >
)transitional//!nO).On)*
out.println$#ocTyp! >
)Nhtml.On) >
)Nh!a#.Ntitl!.) > titl! > )N/titl!.N/h!a#.On) >
)Nbo#y bgcolor9O)^fEfEfEO).On) >
)NhC.) > )3n 3spa[ntil#!*ol-) > )N/hC.On) >
)NhC.) > )[i!:cl*ola Mun#oG) > )N/hC.On) >
)N/bo#y.N/html.)(*
+
+
Locale Specifc Dates:
You can use the java.text.DateFormat class and its static getDateTimeInstance( ) method to format
date and time specific to locale. Following is the example which shows how to format dates specific to
a given locale:
import java.io.**
import java:.s!rvl!t.**
import java:.s!rvl!t.http.**
import java.util.1ocal!*
import java.t!:t.4at!Format*
import java.util.4at!*
public class 4at!1ocal! !:t!n#s ttp%!rvl!t{

public voi# #o8!t$ttp%!rvl!t7!Pu!st r!Pu!st2
ttp%!rvl!t7!spons! r!spons!(
throws %!rvl!t3:c!ption2 6?3:c!ption
{
// %!t r!spons! cont!nt typ!
r!spons!.s!t,ont!ntTyp!$)t!:t/html)(*
Print"rit!r out 9 r!spons!.g!t"rit!r$(*
//8!t th! cli!nt's 1ocal!
1ocal! local! 9 r!Pu!st.g!t1ocal!$ (*
%tring #at! 9 4at!Format.g!t4at!Tim!6nstanc!$
4at!Format.F5112
4at!Format.%?7T2
local!(.format$n!w 4at!$ ((*
%tring titl! 9 )1ocal! %p!cific 4at!s)*
%tring #ocTyp! 9
)NG#octyp! html public O);//wDc//#t# html F.E ) >
)transitional//!nO).On)*
out.println$#ocTyp! >
MAT SOFT
JAVA REFERENCE GUIDE
451
)Nhtml.On) >
)Nh!a#.Ntitl!.) > titl! > )N/titl!.N/h!a#.On) >
)Nbo#y bgcolor9O)^fEfEfEO).On) >
)NhC align9O)c!nt!rO).) > #at! > )N/hC.On) >
)N/bo#y.N/html.)(*
+
+
Locale Specifc Currency
You can use the java.txt.NumberFormat class and its static getCurrencyInstance( ) method to format a
number, such as a long or double type, in a locale specific curreny. Following is the example which
shows how to format currency specific to a given locale:
import java.io.**
import java:.s!rvl!t.**
import java:.s!rvl!t.http.**
import java.util.1ocal!*
import java.t!:t.=umb!rFormat*
import java.util.4at!*
public class ,urr!ncy1ocal! !:t!n#s ttp%!rvl!t{

public voi# #o8!t$ttp%!rvl!t7!Pu!st r!Pu!st2
ttp%!rvl!t7!spons! r!spons!(
throws %!rvl!t3:c!ption2 6?3:c!ption
{
// %!t r!spons! cont!nt typ!
r!spons!.s!t,ont!ntTyp!$)t!:t/html)(*
Print"rit!r out 9 r!spons!.g!t"rit!r$(*
//8!t th! cli!nt's 1ocal!
1ocal! local! 9 r!Pu!st.g!t1ocal!$ (*
=umb!rFormat nft 9 =umb!rFormat.g!t,urr!ncy6nstanc!$local!(*
%tring formatt!#,urr 9 nft.format$CEEEEEE(*
%tring titl! 9 )1ocal! %p!cific ,urr!ncy)*
%tring #ocTyp! 9
)NG#octyp! html public O);//wDc//#t# html F.E ) >
)transitional//!nO).On)*
out.println$#ocTyp! >
)Nhtml.On) >
)Nh!a#.Ntitl!.) > titl! > )N/titl!.N/h!a#.On) >
)Nbo#y bgcolor9O)^fEfEfEO).On) >
)NhC align9O)c!nt!rO).) > formatt!#,urr > )N/hC.On) >
)N/bo#y.N/html.)(*
+
+
Locale Specifc Percentage
MAT SOFT
JAVA REFERENCE GUIDE
452
You can use the java.txt.NumberFormat class and its static getPercentInstance( ) method to get locale
specific percentage. Following is the example which shows how to format percentage specific to a
given locale:
import java.io.**
import java:.s!rvl!t.**
import java:.s!rvl!t.http.**
import java.util.1ocal!*
import java.t!:t.=umb!rFormat*
import java.util.4at!*
public class P!rc!ntag!1ocal! !:t!n#s ttp%!rvl!t{

public voi# #o8!t$ttp%!rvl!t7!Pu!st r!Pu!st2
ttp%!rvl!t7!spons! r!spons!(
throws %!rvl!t3:c!ption2 6?3:c!ption
{
// %!t r!spons! cont!nt typ!
r!spons!.s!t,ont!ntTyp!$)t!:t/html)(*
Print"rit!r out 9 r!spons!.g!t"rit!r$(*
//8!t th! cli!nt's 1ocal!
1ocal! local! 9 r!Pu!st.g!t1ocal!$ (*
=umb!rFormat nft 9 =umb!rFormat.g!tP!rc!nt6nstanc!$local!(*
%tring formatt!#P!rc 9 nft.format$E.HC(*
%tring titl! 9 )1ocal! %p!cific P!rc!ntag!)*
%tring #ocTyp! 9
)NG#octyp! html public O);//wDc//#t# html F.E ) >
)transitional//!nO).On)*
out.println$#ocTyp! >
)Nhtml.On) >
)Nh!a#.Ntitl!.) > titl! > )N/titl!.N/h!a#.On) >
)Nbo#y bgcolor9O)^fEfEfEO).On) >
)NhC align9O)c!nt!rO).) > formatt!#P!rc > )N/hC.On) >
)N/bo#y.N/html.)(*
+
+
Day 43: JSP - An Overview
What is JavaServer Pages?
MAT SOFT
JAVA REFERENCE GUIDE
453
JavaServer Pages (JSP) is a technology for developing web pages that support dynamic content which
helps developers insert java code in HTML pages by making use of special JSP tags, most of which
start with <% and end with %>.
A JavaServer Pages component is a type of Java servlet that is designed to fulfill the role of a user
interface for a Java web application. Web developers write JSPs as text files that combine HTML or
XHTML code, XML elements, and embedded JSP actions and commands. Using JSP, you can collect
input from users through web page forms, present records from a database or another source, and
create web pages dynamically.JSP tags can be used for a variety of purposes, such as retrieving
information from a database or registering user preferences, accessing JavaBeans components,
passing control between pages and sharing information between requests, pages etc.
Why Use JSP?
JavaServer Pages often serve the same purpose as programs implemented using the Common
Gateway Interface (CGI). But JSP offer several advantages in comparison with the CGI.
Performance is significantly better because JSP allows embedding Dynamic Elements in HTML
Pages itself instead of having a separate CGI files.
JSP are always compiled before it's processed by the server unlike CGI/Perl which requires the
server to load an interpreter and the target script each time the page is requested.
JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP also has
access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP etc.
JSP pages can be used in combination with servlets that handle the business logic, the model
supported by Java servlet template engines.
Finally, JSP is an integral part of J2EE, a complete platform for enterprise class applications. This
means that JSP can play a part in the simplest applications to the most complex and demanding.
Advantages of JSP:
Following is the list of other advantages of using JSP over other technologies:
vs1 %ctive Server Pages ,%SP/: The advantages of JSP are twofold. First, the dynamic part
is written in Java, not Visual Basic or other MS specific language, so it is more powerful and
easier to use. Second, it is portable to other operating systems and non-Microsoft Web
servers.
vs1 Pre Serv$ets: It is more convenient to write (and to modify!) regular HTML than to have
plenty of println statements that generate the HTML.
vs1 Server&Side Inc$des ,SSI/: SSI is really only intended for simple inclusions, not for
"real" programs that use form data, make database connections, and the like.
vs1 JavaScript: JavaScript can generate HTML dynamically on the client but can hardly
interact with the web server to perform complex tasks like database access and image
processing etc.
vs1 Static (TM0: Regular HTML, of course, cannot contain dynamic information.
MAT SOFT
JAVA REFERENCE GUIDE
454
JSP - Architecture
The web server needs a JSP engine ie. container to process JSP pages. The JSP container is
responsible for intercepting requests for JSP pages. This material makes use of Apache which has
built-in JSP container to support JSP pages development.
A JSP container works with the Web server to provide the runtime environment and other services a
JSP needs. It knows how to understand the special elements that are part of JSPs.
Following diagram shows the position of JSP container and JSP files in a Web Application.
JSP Processing:
The following steps explain how the web server creates the web page using JSP:
As with a normal page, your browser sends an HTTP request to the web server.
The web server recognizes that the HTTP request is for a JSP page and forwards it to a JSP
engine. This is done by using the URL or JSP page which ends with 1#sp instead of .html.
The JSP engine loads the JSP page from disk and converts it into a servlet content. This
conversion is very simple in which all template text is converted to println( ) statements and
all JSP elements are converted to Java code that implements the corresponding dynamic
behavior of the page.
The JSP engine compiles the servlet into an executable class and forwards the original request
to a servlet engine.
A part of the web server called the servlet engine loads the Servlet class and executes it.
During execution, the servlet produces an output in HTML format, which the servlet engine
passes to the web server inside an HTTP response.
The web server forwards the HTTP response to your browser in terms of static HTML content.
Finally web browser handles the dynamically generated HTML page inside the HTTP response
exactly as if it were a static page.
MAT SOFT
JAVA REFERENCE GUIDE
455
All the above mentioned steps can be shown below in the following diagram:
Typically, the JSP engine checks to see whether a servlet for a JSP file already exists and whether the
modification date on the JSP is older than the servlet. If the JSP is older than its generated servlet, the
JSP container assumes that the JSP hasn't changed and that the generated servlet still matches the
JSP's contents. This makes the process more efficient than with other scripting languages (such as
PHP) and therefore faster.
So in a way, a JSP page is really just another way to write a servlet without having to be a Java
programming wiz. Except for the translation phase, a JSP page is handled exactly like a regular servlet
JSP - Life Cycle
The key to understanding the low-level functionality of JSP is to understand the simple life cycle they
follow.
A JSP life cycle can be defined as the entire process from its creation till the destruction which is
similar to a servlet life cycle with an additional step which is required to compile a JSP into servlet.
The following are the paths followed by a JSP
Compilation
Initialization
Execution
Cleanup
The three major phases of JSP life cycle are very similar to Servlet Life Cycle and they are as follows:
MAT SOFT
JAVA REFERENCE GUIDE
456
(1) JSP Compilation:
When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the
page. If the page has never been compiled, or if the JSP has been modified since it was last compiled,
the JSP engine compiles the page.
The compilation process involves three steps:
1. Parsing the JSP.
2. Turning the JSP into a servlet.
3. Compiling the servlet.
(2) JSP Initialization:
When a container loads a JSP it invokes the jspInit() method before servicing any requests. If you
need to perform JSP-specific initialization, override the jspInit() method:
public voi# jsp6nit$({
// 6nitiali/ation co#!...
+
Typically initialization is performed only once and as with the servlet init method, you generally
initialize database connections, open files, and create lookup tables in the jspInit method.
MAT SOFT
JAVA REFERENCE GUIDE
457
(3) JSP Execution:
This phase of the JSP life cycle represents all interactions with requests until the JSP is destroyed.
Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine
invokes the G#spService,/ method in the JSP.
The _jspService() method takes an (ttpServ$et'e;est and an (ttpServ$et'esponse as its
parameters as follows:
voi# Tjsp%!rvic!$ttp%!rvl!t7!Pu!st r!Pu!st2
ttp%!rvl!t7!spons! r!spons!(
{
// %!rvic! han#ling co#!...
+
The _jspService() method of a JSP is invoked once per a request and is responsible for generating the
response for that request and this method is also responsible for generating responses to all seven of
the HTTP methods ie. GET, POST, DELETE etc.
(4) JSP Cleanup:
The destruction phase of the JSP life cycle represents when a JSP is being removed from use by a
container.
The #sp)estroy,/ method is the JSP equivalent of the destroy method for servlets. Override
jspDestroy when you need to perform any cleanup, such as releasing database connections or closing
open files.
The jspDestroy() method has the following form:
public voi# jsp4!stroy$(
{
// Aour cl!anup co#! go!s h!r!.
+
MAT SOFT
JAVA REFERENCE GUIDE
458
Day 44: JSP - Syntax
The Scriptlet:
A scriptlet can contain any number of JAVA language statements, variable or method declarations, or
expressions that are valid in the page scripting language.
Following is the syntax of Scriptlet:
NW co#! fragm!nt W.
You can write XML equivalent of the above syntax as follows:
Njsp-scriptl!t.
co#! fragm!nt
N/jsp-scriptl!t.
Any text, HTML tags, or JSP elements you write must be outside the scriptlet. Following is the simple
and first example for JSP:
Nhtml.
Nh!a#.Ntitl!.!llo "orl#N/titl!.N/h!a#.
Nbo#y.
!llo "orl#GNbr/.
NW
out.println$)Aour 6P a##r!ss is ) > r!Pu!st.g!t7!mot!0##r$((*
W.
N/bo#y.
N/html.
N!T7: Assuming that Apache Tomcat is installed in C:\apache-tomcat-7.0.2 and your environment is
setup. Let us keep above code in JSP file hello.jsp and put this file in C:Sapache&tomcat&
T1I15S3e"appsS'!!T directory and try to browse it by giving URL http://localhost:8080/hello.jsp.
This would generate following result:
MAT SOFT
JAVA REFERENCE GUIDE
459
JSP Declarations:
A declaration declares one or more variables or methods that you can use in Java code later in the JSP
file. You must declare the variable or method before you use it in the JSP file.
Following is the syntax of JSP Declarations:
NWG #!claration* & #!claration* '> ... W.
You can write XML equivalent of the above syntax as follows:
Njsp-#!claration.
co#! fragm!nt
N/jsp-#!claration.
Following is the simple example for JSP Comments:
NWG int i 9 E* W.
NWG int a2 b2 c* W.
NWG ,ircl! a 9 n!w ,ircl!$@.E(* W.
JSP Expression:
A JSP expression element contains a scripting language expression that is evaluated, converted to a
String, and inserted where the expression appears in the JSP file.
Because the value of an expression is converted to a String, you can use an expression within a line of
text, whether or not it is tagged with HTML, in a JSP file.
The expression element can contain any expression that is valid according to the Java Language
Specification but you cannot use a semicolon to end an expression.
Following is the syntax of JSP Expression:
NW9 !:pr!ssion W.
You can write XML equivalent of the above syntax as follows:
Njsp-!:pr!ssion.
!:pr!ssion
N/jsp-!:pr!ssion.
Following is the simple example for JSP Expression:
Nhtml.
Nh!a#.Ntitl!.0 ,omm!nt T!stN/titl!.N/h!a#.
MAT SOFT
JAVA REFERENCE GUIDE
460
Nbo#y.
Np.
To#ay's #at!- NW9 $n!w java.util.4at!$((.to1ocal!%tring$(W.
N/p.
N/bo#y.
N/html.
This would generate following result:
Today's date: 11-Sep-2010 21:24:25
JSP Comments:
JSP comment marks text or statements that the JSP container should ignore. A JSP comment is useful
when you want to hide or "comment out" part of your JSP page.
Following is the syntax of JSP comments:
NW;; This is J%P comm!nt ;;W.
Following is the simple example for JSP Comments:
Nhtml.
Nh!a#.Ntitl!.0 ,omm!nt T!stN/titl!.N/h!a#.
Nbo#y.
Nh@.0 T!st of ,omm!ntsN/h@.
NW;; This comm!nt will not b! visibl! in th! pag! sourc! ;;W.
N/bo#y.
N/html.
This would generate following result:
A Test of Comments
There are a small number of special constructs you can use in various cases to insert comments or
characters that would otherwise be treated specially. Here's a summary:
Syntax Prpose
<%-- comment --%> A JSP comment. Ignored by the JSP engine.
<!-- comment --> An HTML comment. Ignored by the browser.
MAT SOFT
JAVA REFERENCE GUIDE
461
<\% Represents static <% literal.
%\> Represents static %> literal.
\' A single quote in an attribute that uses single quotes.
\" A double quote in an attribute that uses double quotes.
JSP Directives:
A JSP directive affects the overall structure of the servlet class. It usually has the following form:
NW\ #ir!ctiv! attribut!9)valu!) W.
There are three types of directive tag:
)irective )escription
<%@ page ... %> Defines page-dependent attributes, such as scripting language, error
page, and buffering requirements.
<%@ include ... %> Includes a file during the translation phase.
<%@ taglib ... %> Declares a tag library, containing custom actions, used in the page
We would explain JSP directive in separate chapter JSP - Directives
JSP Actions:
JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can
dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate
HTML for the Java plugin.
There is only one syntax for the Action element, as it conforms to the XML standard:
Njsp-actionTnam! attribut!9)valu!) /.
Action elements are basically predefined functions and there are following JSP actions available:
Syntax Prpose
jsp:include Includes a file at the time the page is requested
MAT SOFT
JAVA REFERENCE GUIDE
462
jsp:include Includes a file at the time the page is requested
jsp:useBean Finds or instantiates a JavaBean
jsp:setProperty Sets the property of a JavaBean
jsp:getProperty Inserts the property of a JavaBean into the output
jsp:forward Forwards the requester to a new page
jsp:plugin Generates browser-specific code that makes an OBJECT or EMBED tag
for the Java plugin
jsp:element Defines XML elements dynamically.
jsp:attribute Defines dynamically defined XML element's attribute.
jsp:body Defines dynamically defined XML element's body.
jsp:text Use to write template text in JSP pages and documents.
We would explain JSP actions in separate chapter JSP - Actions
JSP Implicit Objects:
JSP supports nine automatically defined variables, which are also called implicit objects. These
variables are:
!"#ects )escription
request This is the (ttpServ$et'e;est object associated with the request.
response This is the (ttpServ$et'esponse object associated with the response
to the client.
out This is the Print9riter object used to send output to the client.
session This is the (ttpSession object associated with the request.
application This is the Serv$etContext object associated with application context.
MAT SOFT
JAVA REFERENCE GUIDE
463
config This is the Serv$etConfig object associated with the page.
pageContext This encapsulates use of server-specific features like higher
performance Jsp9riters.
page This is simply a synonym for this, and is used to call the methods
defined by the translated servlet class.
Exception The 7xception object allows the exception data to be accessed by
designated JSP.
We would explain JSP Implicit Objects in separate chapter JSP - Implicit Objects.
Control-Flow Statements:
JSP provides full power of Java to be embeded in your web application. You can use all the APIs and
building blocks of Java in your JSP programming including decision making statements, loops etc.
Decision-Making Statements:
The if111e$se block starts out like an ordinary Scriptlet, but the Scriptlet is closed at each line with
HTML text included between Scriptlet tags.
NWG int #ay 9 D* W.
Nhtml.
Nh!a#.Ntitl!.6F...31%3 3:ampl!N/titl!.N/h!a#.
Nbo#y.
NW if $#ay 99 C a #ay 99 I( { W.
Np. To#ay is w!!<!n#N/p.
NW + !ls! { W.
Np. To#ay is not w!!<!n#N/p.
NW + W.
N/bo#y.
N/html.
This would produce following result:
Today is not weekend
Now look at the following s3itch111case block which has been written a bit differentlty
usingot1print$n,/ and inside Scriptletas:
MAT SOFT
JAVA REFERENCE GUIDE
464
NWG int #ay 9 D* W.
Nhtml.
Nh!a#.Ntitl!.%"6T,...,0%3 3:ampl!N/titl!.N/h!a#.
Nbo#y.
NW
switch$#ay( {
cas! E-
out.println$)6tO's %un#ay.)(*
br!a<*
cas! C-
out.println$)6tO's Mon#ay.)(*
br!a<*
cas! @-
out.println$)6tO's Tu!s#ay.)(*
br!a<*
cas! D-
out.println$)6tO's "!#n!s#ay.)(*
br!a<*
cas! F-
out.println$)6tO's Thurs#ay.)(*
br!a<*
cas! H-
out.println$)6tO's Fri#ay.)(*
br!a<*
#!fault-
out.println$)6t's %atur#ay.)(*
+
W.
N/bo#y.
N/html.
This would produce following result:
It's Wednesday.
Loop Statements:
You can also use three basic types of looping blocks in Java: for< 3hi$e<and doU3hi$e blocks in your
JSP programming.
Let us look at the following for loop example:
NWG int font%i/!* W.
Nhtml.
Nh!a#.Ntitl!.F?7 1??P 3:ampl!N/titl!.N/h!a#.
Nbo#y.
NWfor $ font%i/! 9 C* font%i/! N9 D* font%i/!>>({ W.
Nfont color9)gr!!n) si/!9)NW9 font%i/! W.).
J%P Tutorial
N/font.Nbr /.
MAT SOFT
JAVA REFERENCE GUIDE
465
NW+W.
N/bo#y.
N/html.
This would produce following result:
JSP Tutorial
JSP Tutorial
JSP Tutorial
Above example can be written using 3hi$e loop as follows:
NWG int font%i/!* W.
Nhtml.
Nh!a#.Ntitl!."613 1??P 3:ampl!N/titl!.N/h!a#.
Nbo#y.
NWwhil! $ font%i/! N9 D({ W.
Nfont color9)gr!!n) si/!9)NW9 font%i/! W.).
J%P Tutorial
N/font.Nbr /.
NWfont%i/!>>*W.
NW+W.
N/bo#y.
N/html.
This would also produce following result:
JSP Tutorial
JSP Tutorial
JSP Tutorial
JSP Operators:
JSP supports all the logical and arithmatic operators supported by Java. Following table give a list of all
the operators with the highest precedence appear at the top of the table, those with the lowest appear
at the bottom.
Within an expression, higher precedenace operators will be evaluated first.
Category !perator %ssociativity
Postfix () [] . (dot operator) Left to right
Unary ++ - - ! ~ Right to left
MAT SOFT
JAVA REFERENCE GUIDE
466
Multiplicative * / % Left to right
Additive + - Left to right
Shift >> >>> << Left to right
Relational > >= < <= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left
Comma , Left to right
JSP Literals: The JSP expression $angage defines the fo$$o3ing $itera$s:
Boo$ean: true and false
Integer: as in Java
+$oating point: as in Java
String: with single and double quotes; " is escaped as \", ' is escaped as \', and \ is escaped
as \\.
N$$: null
JSP - Directives
JSP directives provide directions and instructions to the container, telling it how to handle certain
aspects of JSP processing.
MAT SOFT
JAVA REFERENCE GUIDE
467
A JSP directive affects the overall structure of the servlet class. It usually has the following form:
NW\ #ir!ctiv! attribut!9)valu!) W.
Directives can have a number of attributes which you can list down as key-value pairs and separated
by commas.
The blanks between the @ symbol and the directive name, and between the last attribute and the
closing %>, are optional.
There are three types of directive tag:
)irective )escription
<%@ page ... %> Defines page-dependent attributes, such as scripting language, error
page, and buffering requirements.
<%@ include ... %> Includes a file during the translation phase.
<%@ taglib ... %> Declares a tag library, containing custom actions, used in the page
The page Directive:
The page directive is used to provide instructions to the container that pertain to the current JSP
page. You may code page directives anywhere in your JSP page. By convention, page directives are
coded at the top of the JSP page.
Following is the basic syntax of page directive:
NW\ pag! attribut!9)valu!) W.
You can write XML equivalent of the above syntax as follows:
Njsp-#ir!ctiv!.pag! attribut!9)valu!) /.
Attributes:
Following is the list of attributes associated with page directive:
%ttri"te Prpose
buffer Specifies a buffering model for the output stream.
autoFlush Controls the behavior of the servlet output buffer.
MAT SOFT
JAVA REFERENCE GUIDE
468
contentType Defines the character encoding scheme.
errorPage Defines the URL of another JSP that reports on Java unchecked runtime
exceptions.
isErrorPage Indicates if this JSP page is a URL specified by another JSP page's
errorPage attribute.
extends Specifies a superclass that the generated servlet must extend
import Specifies a list of packages or classes for use in the JSP as the Java
import statement does for Java classes.
info Defines a string that can be accessed with the servlet's
getServletInfo() method.
isThreadSafe Defines the threading model for the generated servlet.
language Defines the programming language used in the JSP page.
session Specifies whether or not the JSP page participates in HTTP sessions
isELIgnored Specifies whether or not EL expression within the JSP page will be
ignored.
isScriptingEnabled Determines if scripting elements are allowed for use.
Check more detail related to all the above attributes at Page Directive.
The include Directive:
The inc$de directive is used to includes a file during the translation phase. This directive tells the
container to merge the content of other external files with the current JSP during the translation
phase. You may code include directives anywhere in your JSP page.
The general usage form of this directive is as follows:
NW\ inclu#! fil!9)r!lativ! url) .
The filename in the include directive is actually a relative URL. If you just specify a filename with no
associated path, the JSP compiler assumes that the file is in the same directory as your JSP.
MAT SOFT
JAVA REFERENCE GUIDE
469
You can write XML equivalent of the above syntax as follows:
Njsp-#ir!ctiv!.inclu#! fil!9)r!lativ! url) /.
Check more detail related to include directive at Include Directive.
The taglib Directive:
The JavaServer Pages API allows you to define custom JSP tags that look like HTML or XML tags and a
tag library is a set of user-defined tags that implement custom behavior.
The tag$i" directive declares that your JSP page uses a set of custom tags, identifies the location of
the library, and provides a means for identifying the custom tags in your JSP page.
The taglib directive follows the following syntax:
NW\ taglib uri9)uri) pr!fi:9)pr!fi:?fTag) .
Where the ri attribute value resolves to a location the container understands and the prefixattribute
informs a container what bits of markup are custom actions.
You can write XML equivalent of the above syntax as follows:
Njsp-#ir!ctiv!.taglib uri9)uri) pr!fi:9)pr!fi:?fTag) /.
Check more detail related to taglib directive at Taglib Directive.
JSP - Implicit Objects
JSP Implicit Objects are the Java objects that the JSP Container makes available to developers in each
page and developer can call them directly without being explicitly declared. JSP Implicit Objects are
also called pre-defined variables.
JSP supports nine Implicit Objects which are listed below:
!"#ect )escription
request This is the (ttpServ$et'e;est object associated with the request.
response This is the (ttpServ$et'esponse object associated with the response
to the client.
out This is the Print9riter object used to send output to the client.
session This is the (ttpSession object associated with the request.
MAT SOFT
JAVA REFERENCE GUIDE
470
application This is the Serv$etContext object associated with application context.
config This is the Serv$etConfig object associated with the page.
pageContext This encapsulates use of server-specific features like higher
performance Jsp9riters.
page This is simply a synonym for this, and is used to call the methods
defined by the translated servlet class.
Exception The 7xception object allows the exception data to be accessed by
designated JSP.
The request Object:
The request object is an instance of a javax.servlet.http.HttpServletRequest object. Each time a client
requests a page the JSP engine creates a new object to represent that request.
The request object provides methods to get HTTP header information including form data, cookies,
HTTP methods etc.
We would see complete set of methods associated with request object in coming chapter: JSP - Client
Request.
The response Object:
The response object is an instance of a javax.servlet.http.HttpServletResponse object. Just as the
server creates the request object, it also creates an object to represent the response to the client.
The response object also defines the interfaces that deal with creating new HTTP headers. Through
this object the JSP programmer can add new cookies or date stamps, HTTP status codes etc.
We would see complete set of methods associated with response object in coming chapter: JSP -
Server Response.
The out Object:
The out implicit object is an instance of a javax.servlet.jsp.JspWriter object and is used to send
content in a response.
The initial JspWriter object is instantiated differently depending on whether the page is buffered or
not. Buffering can be easily turned off by using the buffered='false' attribute of the page directive.
The JspWriter object contains most of the same methods as the java.io.PrintWriter class. However,
JspWriter has some additional methods designed to deal with buffering. Unlike the PrintWriter object,
JspWriter throws IOExceptions.
Following are the important methods which we would use to write boolean char, int, double, object,
String etc.
MAT SOFT
JAVA REFERENCE GUIDE
471
Method )escription
ot1print,dataType dt/ Print a data type value
ot1print$n,dataType dt/ Print a data type value then terminate the line with new line
character.
ot1f$sh,/ Flush the stream.
The session Object:
The session object is an instance of javax.servlet.http.HttpSession and behaves exactly the same way
that session objects behave under Java Servlets.
The session object is used to track client session between client requests. We would see complete
usage of session object in coming chapter: JSP - Session Tracking.
The application Object:
The application object is direct wrapper around the ServletContext object for the generated Servlet
and in reality an instance of a javax.servlet.ServletContext object.
This object is a representation of the JSP page through its entire lifecycle. This object is created when
the JSP page is initialized and will be removed when the JSP page is removed by the jspDestroy()
method.
By adding an attribute to application, you can ensure that all JSP files that make up your web
application have access to it.
You can check a simple use of Application Object in chapter: JSP - Hits Counter
The confg Object:
The config object is an instantiation of javax.servlet.ServletConfig and is a direct wrapper around the
ServletConfig object for the generated servlet.
This object allows the JSP programmer access to the Servlet or JSP engine initialization parameters
such as the paths or file locations etc.
The following config method is the only one you might ever use, and its usage is trivial:

config.g!t%!rvl!t=am!$(*
This returns the servlet name, which is the string contained in the <servlet-name> element defined in
the WEB-INF\web.xml file
The pageContext Object:
MAT SOFT
JAVA REFERENCE GUIDE
472
The pageContext object is an instance of a javax.servlet.jsp.PageContext object. The pageContext
object is used to represent the entire JSP page.
This object is intended as a means to access information about the page while avoiding most of the
implementation details.
This object stores references to the request and response objects for each request. The application,
config, session, and out objects are derived by accessing attributes of this object.
The pageContext object also contains information about the directives issued to the JSP page,
including the buffering information, the errorPageURL, and page scope.
The PageContext class defines several fields, including PAGE_SCOPE, REQUEST_SCOPE,
SESSION_SCOPE, and APPLICATION_SCOPE, which identify the four scopes. It also supports more
than 40 methods, about half of which are inherited from the javax.servlet.jsp. JspContext class.
One of the important methods is remove%ttri"te, which accepts either one or two arguments. For
example, pageContext.removeAttribute ("attrName") removes the attribute from all scopes, while the
following code only removes it from the page scope:

pag!,ont!:t.r!mov!0ttribut!$)attr=am!)2 P083T%,?P3(*
You can check a very good usage of pageContext in coming chapter: JSP - File Uploading.
The page Object:
This object is an actual reference to the instance of the page. It can be thought of as an object that
represents the entire JSP page.
The page object is really a direct synonym for the this object.
Day 45: JSP - Actions
JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can
dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate
HTML for the Java plugin.
MAT SOFT
JAVA REFERENCE GUIDE
473
There is only one syntax for the Action element, as it conforms to the XML standard:
Njsp-actionTnam! attribut!9)valu!) /.
Action elements are basically predefined functions and there are following JSP actions available:
Syntax Prpose
jsp:include Includes a file at the time the page is requested
jsp:include Includes a file at the time the page is requested
jsp:useBean Finds or instantiates a JavaBean
jsp:setProperty Sets the property of a JavaBean
jsp:getProperty Inserts the property of a JavaBean into the output
jsp:forward Forwards the requester to a new page
jsp:plugin Generates browser-specific code that makes an OBJECT or EMBED tag
for the Java plugin
jsp:element Defines XML elements dynamically.
jsp:attribute Defines dynamically defined XML element's attribute.
jsp:body Defines dynamically defined XML element's body.
jsp:text Use to write template text in JSP pages and documents.
Common Attributes:
There are two attributes that are common to all Action elements: the id attribute and
the scopeattribute.
Id attri"te: The id attribute uniquely identifies the Action element, and allows the action to
be referenced inside the JSP page. If the Action creates an instance of an object the id value
can be used to reference it through the implicit object PageContext
Scope attri"te: This attribute identifies the lifecycle of the Action element. The id attribute
and the scope attribute are directly related, as the scope attribute determines the lifespan of
the object associated with the id. The scope attribute has four possible values: (a) page,
(b)request, (c)session, and (d) application.
MAT SOFT
JAVA REFERENCE GUIDE
474
The <jsp:include> Action
This action lets you insert files into the page being generated. The syntax looks like this:
Njsp-inclu#! pag!9)r!lativ! 571) flush9)tru!) /.
Unlike the inc$de directive, which inserts the file at the time the JSP page is translated into a servlet,
this action inserts the file at the time the page is requested.
Following is the list of attributes associated with include action:
%ttri"te )escription
page The relative URL of the page to be included.
flush The boolean attribute determines whether the included resource has its
buffer flushed before it is included.
Example:
Let us define following two files (a)date.jps and (b) main.jsp as follows:
Following is the content of date.jsp file:
Np.
To#ay's #at!- NW9 $n!w java.util.4at!$((.to1ocal!%tring$(W.
N/p.
Here is the content of main.jsp file:
Nhtml.
Nh!a#.
Ntitl!.Th! inclu#! 0ction 3:ampl!N/titl!.
N/h!a#.
Nbo#y.
Nc!nt!r.
Nh@.Th! inclu#! action 3:ampl!N/h@.
Njsp-inclu#! pag!9)#at!.jsp) flush9)tru!) /.
N/c!nt!r.
N/bo#y.
N/html.
Now let us keep all these files in root directory and try to access main.jsp. This would display result
something like this:
MAT SOFT
JAVA REFERENCE GUIDE
475
The include action Example
Today's date: 12-Sep-2010 14:54:22
The <jsp:useBean> Action
The seBean action is quite versatile. It first searches for an existing object utilizing the id and scope
variables. If an object is not found, it then tries to create the specified object.
The simplest way to load a bean is as follows:
Njsp-us!L!an i#9)nam!) class9)pac<ag!.class) /.
Once a bean class is loaded, you can use #sp:setProperty and #sp:getProperty actions to modify
and retrieve bean properties.
Following is the list of attributes associated with useBean action:
%ttri"te )escription
class Designates the full package name of the bean.
type Specifies the type of the variable that will refer to the object.
beanName Gives the name of the bean as specified by the instantiate () method of
the java.beans.Beans class.
Let us discuss about #sp:setProperty and #sp:getProperty actions before giving a valid example
related to these actions.
The <jsp:setProperty> Action
The setProperty action sets the properties of a Bean. The Bean must have been previously defined
before this action. There are two basic ways to use the setProperty action:
You can use jsp:setProperty after, but outside of, a jsp:useBean element, as below:
Njsp-us!L!an i#9)my=am!) ... /.
...
Njsp-s!tProp!rty nam!9)my=am!) prop!rty9)som!Prop!rty) .../.
In this case, the jsp:setProperty is executed regardless of whether a new bean was instantiated or an
existing bean was found.
MAT SOFT
JAVA REFERENCE GUIDE
476
A second context in which jsp:setProperty can appear is inside the body of a jsp:useBean element, as
below:
Njsp-us!L!an i#9)my=am!) ... .
...
Njsp-s!tProp!rty nam!9)my=am!) prop!rty9)som!Prop!rty) .../.
N/jsp-us!L!an.
Here, the jsp:setProperty is executed only if a new object was instantiated, not if an existing one was
found.
Following is the list of attributes associated with setProperty action:
%ttri"te )escription
name Designates the bean whose property will be set. The Bean must have
been previously defined.
property Indicates the property you want to set. A value of "*" means that all
request parameters whose names match bean property names will be
passed to the appropriate setter methods.
value The value that is to be assigned to the given property. The the
parameter's value is null, or the parameter does not exist, the
setProperty action is ignored.
param The param attribute is the name of the request parameter whose value
the property is to receive. You can't use both value and param, but it is
permissible to use neither.
The <jsp:getProperty> Action
The getProperty action is used to retrieve the value of a given property and converts it to a string,
and finally inserts it into the output.
The getProperty action has only two attributes, both of which are required ans simple syntax is as
follows:
Njsp-us!L!an i#9)my=am!) ... /.
...
Njsp-g!tProp!rty nam!9)my=am!) prop!rty9)som!Prop!rty) .../.
Following is the list of required attributes associated with setProperty action:
%ttri"te )escription
MAT SOFT
JAVA REFERENCE GUIDE
477
name The name of the Bean that has a property to be retrieved. The Bean
must have been previously defined.
property The property attribute is the name of the Bean property to be
retrieved.
Example:
Let us define a test bean which we will use in our example:
/* Fil!- T!stL!an.java */
pac<ag! action*

public class T!stL!an {
privat! %tring m!ssag! 9 )=o m!ssag! sp!cifi!#)*

public %tring g!tM!ssag!$( {
r!turn$m!ssag!(*
+
public voi# s!tM!ssag!$%tring m!ssag!( {
this.m!ssag! 9 m!ssag!*
+
+
Compile above code to generated TestBean.class file and make sure that you copied TestBean.class in
C:\apache-tomcat-7.0.2\webapps\WEB-INF\classes\action folder and CLASSPATH variable should also
be set to this folder:
Now use the following code in main.jsp file which loads the bean and sets/gets a simple String
parameter:
Nhtml.
Nh!a#.
Ntitl!.5sing JavaL!ans in J%PN/titl!.
N/h!a#.
Nbo#y.
Nc!nt!r.
Nh@.5sing JavaL!ans in J%PN/h@.

Njsp-us!L!an i#9)t!st) class9)action.T!stL!an) /.

Njsp-s!tProp!rty nam!9)t!st)
prop!rty9)m!ssag!)
valu!9)!llo J%P...) /.

Np.8ot m!ssag!....N/p.

Njsp-g!tProp!rty nam!9)t!st) prop!rty9)m!ssag!) /.

N/c!nt!r.
MAT SOFT
JAVA REFERENCE GUIDE
478
N/bo#y.
N/html.
Now try to access main.jsp, it would display following result:
Using JavaBeans in JSP
Got message....
Hello JSP...
The <jsp:forward> Action
The for3ard action terminates the action of the current page and forwards the request to another
resource such as a static page, another JSP page, or a Java Servlet.
The simple syntax of this action is as follows:
Njsp-forwar# pag!9)7!lativ! 571) /.
Following is the list of required attributes associated with forward action:
%ttri"te )escription
page Should consist of a relative URL of another resource such as a static
page, another JSP page, or a Java Servlet.
Example:
Let us reuse following two files (a) date.jps and (b) main.jsp as follows:
Following is the content of date.jsp file:
Np.
To#ay's #at!- NW9 $n!w java.util.4at!$((.to1ocal!%tring$(W.
N/p.
Here is the content of main.jsp file:
Nhtml.
Nh!a#.
Ntitl!.Th! inclu#! 0ction 3:ampl!N/titl!.
N/h!a#.
Nbo#y.
MAT SOFT
JAVA REFERENCE GUIDE
479
Nc!nt!r.
Nh@.Th! inclu#! action 3:ampl!N/h@.
Njsp-forwar# pag!9)#at!.jsp) /.
N/c!nt!r.
N/bo#y.
N/html.
Now let us keep all these files in root directory and try to access main.jsp. This would display result
something like as below. Here it discarded content from main page and displayed content from
forwarded page only.
Today's date: 12-Sep-2010 14:54:22
The <jsp:plugin> Action
The p$gin action is used to insert Java components into a JSP page. It determines the type of
browser and inserts the <object> or <embed> tags as needed.
If the needed plugin is not present, it downloads the plugin and then executes the Java component.
The Java component can be either an Applet or a JavaBean.
The plugin action has several attributes that correspond to common HTML tags used to format Java
components. The <param> element can also be used to send parameters to the Applet or Bean.
Following is the typical syntax of using plugin action:
Njsp-plugin typ!9)appl!t) co#!bas!9)#irnam!) co#!9)My0ppl!t.class)
wi#th9)ME) h!ight9)JE).
Njsp-param nam!9)fontcolor) valu!9)r!#) /.
Njsp-param nam!9)bac<groun#) valu!9)blac<) /.

Njsp-fallbac<.
5nabl! to initiali/! Java Plugin
N/jsp-fallbac<.

N/jsp-plugin.
You can try this action using some applet if you are interested. A new element, the <fallback>
element, can be used to specify an error string to be sent to the user in case the component fails.
The <jsp:element> Action
The <jsp:attribute> Action
The <jsp:body> Action
MAT SOFT
JAVA REFERENCE GUIDE
480
The <jsp:element>, lt;jsp:attribute> and <jsp:body> actions are used to define XML elements
dynamically. The word dynamically is important, because it means that the XML elements can be
generated at request time rather than statically at compile time.
Following is a simple example to define XML elements dynamically:
NW\pag! languag!9)java) cont!ntTyp!9)t!:t/html)W.
Nhtml :mlns9)http-//www.wDc.org/CKKK/:html)
:mlns-jsp9)http-//java.sun.com/J%P/Pag!).
Nh!a#.Ntitl!.8!n!rat! RM1 3l!m!ntN/titl!.N/h!a#.
Nbo#y.
Njsp-!l!m!nt nam!9):ml3l!m!nt).
Njsp-attribut! nam!9):ml3l!m!nt0ttr).
Balu! for th! attribut!
N/jsp-attribut!.
Njsp-bo#y.
Lo#y for RM1 !l!m!nt
N/jsp-bo#y.
N/jsp-!l!m!nt.
N/bo#y.
N/html.
This would produce following HTML code at run time:
Nhtml :mlns9)http-//www.wDc.org/CKKK/:html)
:mlns-jsp9)http-//java.sun.com/J%P/Pag!).

Nh!a#.Ntitl!.8!n!rat! RM1 3l!m!ntN/titl!.N/h!a#.
Nbo#y.
N:ml3l!m!nt :ml3l!m!nt0ttr9)Balu! for th! attribut!).
Lo#y for RM1 !l!m!nt
N/:ml3l!m!nt.
N/bo#y.
N/html.
The <jsp:text> Action
The <jsp:text> action can be used to write template text in JSP pages and documents. Following is
the simple syntax for this action:
Njsp-t!:t.T!mplat! #ataN/jsp-t!:t.
The body fo the template cannot contain other elements; it can only contain text and EL expressions
( Note: EL expressions are explained in subsequent chapter). Note that in XML files, you cannot use
expressions such as ${whatever > 0}, because the greater than signs are illegal. Instead, use the gt
form, such as ${whatever gt 0} or an alternative is to embed the value in a CDATA section.
Njsp-t!:t.NG&,40T0&Nbr.''.N/jsp-t!:t.
MAT SOFT
JAVA REFERENCE GUIDE
481
If you need to include a DOCTYPE declaration, for instance for XHTML, you must also use the
<jsp:text> element as follows:
Njsp-t!:t.NG&,40T0&NG4?,TAP3 html
P5L16, );//"D,//4T4 RTM1 C.E %trict//3=)
)4T4/:htmlC;strict.#t#).''.
N/jsp-t!:t.
Nh!a#.Ntitl!.jsp-t!:t actionN/titl!.N/h!a#.
Nbo#y.
Nboo<s.Nboo<.Njsp-t!:t.
"!lcom! to J%P Programming
N/jsp-t!:t.N/boo<.N/boo<s.
N/bo#y.
N/html.
Try above example with and without <jsp:text> action.
JSP - Client Request
When a browser requests for a web page, it sends lot of information to the web server which can not
be read directly because this information travel as a part of header of HTTP request. You can
check HTTP Protocol for more information on this.
Following is the important header information which comes from browser side and you would use very
frequently in web programming:
(eader )escription
Accept This header specifies the MIME types that the browser or other clients
can handle. Values of imageKpng or imageK#peg are the two most
common possibilities.
MAT SOFT
JAVA REFERENCE GUIDE
482
Accept-Charset This header specifies the character sets the browser can use to display
the information. For example ISO-8859-1.
Accept-Encoding This header specifies the types of encodings that the browser knows
how to handle. Values of g2ip or compress are the two most common
possibilities.
Accept-Language This header specifies the client's preferred languages in case the
servlet can produce results in more than one language. For example
en, en-us, ru, etc.
Authorization This header is used by clients to identify themselves when accessing
password-protected Web pages.
Connection This header indicates whether the client can handle persistent HTTP
connections. Persistent connections permit the client or other browser
to retrieve multiple files with a single request. A value of 6eep&
%$ive means that persistent connections should be used
Content-Length This header is applicable only to POST requests and gives the size of
the POST data in bytes.
Cookie This header returns cookies to servers that previously sent them to the
browser.
Host This header specifies the host and port as given in the original URL.
If-Modified-Since This header indicates that the client wants the page only if it has been
changed after the specified date. The server sends a code, 304 which
means Not Modified header if no newer result is available.
If-Unmodified-Since This header is the reverse of If-Modified-Since; it specifies that the
operation should succeed only if the document is older than the
specified date.
Referer This header indicates the URL of the referring Web page. For example,
if you are at Web page 1 and click on a link to Web page 2, the URL of
Web page 1 is included in the Referer header when the browser
requests Web page 2.
User-Agent This header identifies the browser or other client making the request
and can be used to return different content to different types of
browsers.
The HttpServletRequest Object:
The request object is an instance of a javax.servlet.http.HttpServletRequest object. Each time a client
requests a page the JSP engine creates a new object to represent that request.
The request object provides methods to get HTTP header information including form data, cookies,
HTTP methods etc.
There are following important methods which can be used to read HTTP header in your JSP program.
These method are available with )ttp2er!let.e4uest object which represents client request to
webserver.
MAT SOFT
JAVA REFERENCE GUIDE
483
S1N1 Method : )escription
MAT SOFT
JAVA REFERENCE GUIDE
484
1 Coo=ie-. getCoo=ies,/
Returns an array containing all of the Cookie objects the client sent with this request.
2 7nmeration get%ttri"teNames,/
Returns an Enumeration containing the names of the attributes available to this request.
3 7nmeration get(eaderNames,/
Returns an enumeration of all the header names this request contains.
4 7nmeration getParameterNames,/
Returns an Enumeration of String objects containing the names of the parameters contained in
this request.
5 (ttpSession getSession,/
Returns the current session associated with this request, or if the request does not have a
session, creates one.
6 (ttpSession getSession,"oo$ean create/
Returns the current HttpSession associated with this request or, if if there is no current session
and create is true, returns a new session.
7 0oca$e get0oca$e,/
Returns the preferred Locale that the client will accept content in, based on the Accept-
Language header
8 !"#ect get%ttri"te,String name/
Returns the value of the named attribute as an Object, or null if no attribute of the given name
exists.
9 Serv$etInptStream getInptStream,/
Retrieves the body of the request as binary data using a ServletInputStream.
10 String get%thType,/
Returns the name of the authentication scheme used to protect the servlet, for example,
"BASIC" or "SSL," or null if the JSP was not protected
11 String getCharacter7ncoding,/
Returns the name of the character encoding used in the body of this request.
12 String getContentType,/
Returns the MIME type of the body of the request, or null if the type is not known.
13 String getContextPath,/
Returns the portion of the request URI that indicates the context of the request.
14 String get(eader,String name/
Returns the value of the specified request header as a String.
15 String getMethod,/
Returns the name of the HTTP method with which this request was made, for example, GET,
POST, or PUT.
16 String getParameter,String name/
Returns the value of a request parameter as a String, or null if the parameter does not exist.
17 String getPathInfo,/
Returns any extra path information associated with the URL the client sent when it made this
request.
18 String getProtoco$,/
Returns the name and version of the protocol the request.
MAT SOFT
JAVA REFERENCE GUIDE
485
19 String getJeryString,/
Returns the query string that is contained in the request URL after the path.
20 String get'emote%ddr,/
Returns the Internet Protocol (IP) address of the client that sent the request.
21 String get'emote(ost,/
Returns the fully qualified name of the client that sent the request.
22 String get'emoteBser,/
Returns the login of the user making this request, if the user has been authenticated, or null if
the user has not been authenticated.
23 String get'e;estB'I,/
Returns the part of this request's URL from the protocol name up to the query string in the first
line of the HTTP request.
24 String get'e;estedSessionId,/
Returns the session ID specified by the client.
25 String getServ$etPath,/
Returns the part of this request's URL that calls the JSP.
26 String-. getParameter*a$es,String name/
Returns an array of String objects containing all of the values the given request parameter has,
or null if the parameter does not exist.
27 "oo$ean isSecre,/
Returns a boolean indicating whether this request was made using a secure channel, such as
HTTPS.
28 int getContent0ength,/
Returns the length, in bytes, of the request body and made available by the input stream, or -1
if the length is not known.
29 int getInt(eader,String name/
Returns the value of the specified request header as an int.
30 int getServerPort,/
Returns the port number on which this request was received.
HTTP Header Request Example:
Following is the example which uses get(eaderNames,/ method of HttpServletRequest to read the
HTTP header infromation. This method returns an Enumeration that contains the header information
associated with the current HTTP request.
Once we have an Enumeration, we can loop down the Enumeration in the standard manner,
using has#ore=lements() method to determine when to stop and using next=lement() method to get
each parameter name.
NW\ pag! import9)java.io.*2java.util.*) W.
Nhtml.
Nh!a#.
Ntitl!.TTP !a#!r 7!Pu!st 3:ampl!N/titl!.
N/h!a#.
Nbo#y.
MAT SOFT
JAVA REFERENCE GUIDE
486
Nc!nt!r.
Nh@.TTP !a#!r 7!Pu!st 3:ampl!N/h@.
Ntabl! wi#th9)CEEW) bor#!r9)C) align9)c!nt!r).
Ntr bgcolor9)^KFKFKF).
Nth.!a#!r =am!N/th.Nth.!a#!r Balu!$s(N/th.
N/tr.
NW
3num!ration h!a#!r=am!s 9 r!Pu!st.g!t!a#!r=am!s$(*
whil!$h!a#!r=am!s.hasMor!3l!m!nts$(( {
%tring param=am! 9 $%tring(h!a#!r=am!s.n!:t3l!m!nt$(*
out.print$)Ntr.Nt#.) > param=am! > )N/t#.On)(*
%tring paramBalu! 9 r!Pu!st.g!t!a#!r$param=am!(*
out.println$)Nt#. ) > paramBalu! > )N/t#.N/tr.On)(*
+
W.
N/tabl!.
N/c!nt!r.
N/bo#y.
N/html.
Now put the above code in main.jsp and try to access it. This would produce result something as
follows:
HTTP Header Request Example
(eader Name (eader *a$e,s/
accept */*
accept-language en-us
user-agent Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0;
InfoPath.2; MS-RTC LM 8)
accept-encoding gzip, deflate
host localhost:8080
connection Keep-Alive
cache-control no-cache
To become more comfortable with other methods you can try few more above listed methods in the
same fashion.
JSP - Server Response
When a Web server responds to a HTTP request to the browser, the response typically consists of a
status line, some response headers, a blank line, and the document. A typical response looks like this:
TTP/C.C @EE ?Y
,ont!nt;Typ!- t!:t/html
!a#!r@- ...
...
!a#!r=- ...
MAT SOFT
JAVA REFERENCE GUIDE
487
$Llan< 1in!(
NG#octyp! ....
Nhtml.
Nh!a#....N/h!a#.
Nbo#y.
...
N/bo#y.
N/html.
The status line consists of the HTTP version (HTTP/1.1 in the example), a status code (200 in the
example), and a very short message corresponding to the status code (OK in the example).
Following is a summary of the most useful HTTP 1.1 response headers which go back to the browser
from web server side and you would use them very frequently in web programming:
(eader )escription
Allow This header specifies the request methods (GET, POST, etc.) that the
server supports.
Cache-Control This header specifies the circumstances in which the response
document can safely be cached. It can have values p"$ic<
private or no&cache etc. Public means document is cacheable, Private
means document is for a single user and can only be stored in private
(nonshared) caches and no-cache means document should never be
cached.
Connection This header instructs the browser whether to use persistent in HTTP
connections or not. A value of c$ose instructs the browser not to use
persistent HTTP connections and =eep&a$ive means using persistent
connections.
Content-Disposition This header lets you request that the browser ask the user to save the
response to disk in a file of the given name.
Content-Encoding This header specifies the way in which the page was encoded during
transmission.
Content-Language This header signifies the language in which the document is written.
For example en, en-us, ru, etc.
Content-Length This header indicates the number of bytes in the response. This
information is needed only if the browser is using a persistent (keep-
alive) HTTP connection.
Content-Type This header gives the MIME (Multipurpose Internet Mail Extension) type
of the response document.
Expires This header specifies the time at which the content should be
considered out-of-date and thus no longer be cached.
Last-Modified This header indicates when the document was last changed. The client
can then cache the document and supply a date by an If&Modified&
Since request header in later requests.
Location This header should be included with all responses that have a status
code in the 300s. This notifies the browser of the document address.
The browser automatically reconnects to this location and retrieves the
MAT SOFT
JAVA REFERENCE GUIDE
488
new document.
Refresh This header specifies how soon the browser should ask for an updated
page. You can specify time in number of seconds after which a page
would be refreshed.
Retry-After This header can be used in conjunction with a 503 (Service
Unavailable) response to tell the client how soon it can repeat its
request.
Set-Cookie This header specifies a cookie associated with the page.
The HttpServletResponse Object:
The response object is an instance of a javax.servlet.http.HttpServletRequest object. Just as the
server creates the request object, it also creates an object to represent the response to the client.
The response object also defines the interfaces that deal with creating new HTTP headers. Through
this object the JSP programmer can add new cookies or date stamps, HTTP status codes etc.
There are following methods which can be used to set HTTP response header in your servlet program.
These method are available with )ttp2er!let.esponse object which represents server response.
S1N1 Method : )escription
1 String encode'edirectB'0,String r$/
Encodes the specified URL for use in the sendRedirect method or, if encoding is not needed,
returns the URL unchanged.
2 String encodeB'0,String r$/
Encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns
the URL unchanged.
3 "oo$ean contains(eader,String name/
Returns a boolean indicating whether the named response header has already been set.
4 "oo$ean isCommitted,/
Returns a boolean indicating if the response has been committed.
5 void addCoo=ie,Coo=ie coo=ie/
Adds the specified cookie to the response.
6 void add)ate(eader,String name< $ong date/
Adds a response header with the given name and date-value.
7 void add(eader,String name< String va$e/
Adds a response header with the given name and value.
8 void addInt(eader,String name< int va$e/
Adds a response header with the given name and integer value.
9 void f$shBffer,/
Forces any content in the buffer to be written to the client.
10 void reset,/
Clears any data that exists in the buffer as well as the status code and headers.
MAT SOFT
JAVA REFERENCE GUIDE
489
11 void resetBffer,/
Clears the content of the underlying buffer in the response without clearing headers or status
code.
12 void send7rror,int sc/
Sends an error response to the client using the specified status code and clearing the buffer.
13 void send7rror,int sc< String msg/
Sends an error response to the client using the specified status.
14 void send'edirect,String $ocation/
Sends a temporary redirect response to the client using the specified redirect location URL.
15 void setBfferSi2e,int si2e/
Sets the preferred buffer size for the body of the response.
16 void setCharacter7ncoding,String charset/
Sets the character encoding (MIME charset) of the response being sent to the client, for
example, to UTF-8.
17 void setContent0ength,int $en/
Sets the length of the content body in the response In HTTP servlets, this method sets the HTTP
Content-Length header.
18 void setContentType,String type/
Sets the content type of the response being sent to the client, if the response has not been
committed yet.
19 void set)ate(eader,String name< $ong date/
Sets a response header with the given name and date-value.
20 void set(eader,String name< String va$e/
Sets a response header with the given name and value.
21 void setInt(eader,String name< int va$e/
Sets a response header with the given name and integer value.
22 void set0oca$e,0oca$e $oc/
Sets the locale of the response, if the response has not been committed yet.
23 void setStats,int sc/
Sets the status code for this response.
HTTP Header Response Example:
Following example would use setInt(eader,/ method to set 'efresh header to simulate a digital
clock:
NW\ pag! import9)java.io.*2java.util.*) W.
Nhtml.
Nh!a#.
Ntitl!.0uto 7!fr!sh !a#!r 3:ampl!N/titl!.
N/h!a#.
Nbo#y.
Nc!nt!r.
Nh@.0uto 7!fr!sh !a#!r 3:ampl!N/h@.
NW
MAT SOFT
JAVA REFERENCE GUIDE
490
// %!t r!fr!sh2 autoloa# tim! as H s!con#s
r!spons!.s!t6nt!a#!r$)7!fr!sh)2 H(*
// 8!t curr!nt tim!
,al!n#ar cal!n#ar 9 n!w 8r!gorian,al!n#ar$(*
%tring amTpm*
int hour 9 cal!n#ar.g!t$,al!n#ar.?57(*
int minut! 9 cal!n#ar.g!t$,al!n#ar.M6=5T3(*
int s!con# 9 cal!n#ar.g!t$,al!n#ar.%3,?=4(*
if$cal!n#ar.g!t$,al!n#ar.0MTPM( 99 E(
amTpm 9 )0M)*
!ls!
amTpm 9 )PM)*
%tring ,T 9 hour>)-)> minut! >)-)> s!con# >) )> amTpm*
out.println$),rr!nt Tim!- ) > ,T > )On)(*
W.
N/c!nt!r.
N/bo#y.
N/html.
Now put the above code in main.jsp and try to access it. This would display current system time after
every 5 seconds as follows. Just run the JSP and wait to see the result:
JSP - Http Status Codes
The format of the HTTP request and HTTP response messages are similar and will have following
structure:
An initial status line + CRLF ( Carriage Return + Line Feed ie. New Line )
Zero or more header lines + CRLF
A blank line ie. a CRLF
An optioanl message body like file, query data or query output.
For example, a server response header looks as follows:
TTP/C.C @EE ?Y
,ont!nt;Typ!- t!:t/html
!a#!r@- ...
...
!a#!r=- ...
$Llan< 1in!(
NG#octyp! ....
Nhtml.
Nh!a#....N/h!a#.
Nbo#y.
...
MAT SOFT
JAVA REFERENCE GUIDE
491
N/bo#y.
N/html.
The status line consists of the HTTP version (HTTP/1.1 in the example), a status code (200 in the
example), and a very short message corresponding to the status code (OK in the example).
Following is a list of HTTP status codes and associated messages that might be returned from the Web
Server:
Code: Message: )escription:
100 Continue Only a part of the request has been received by the server,
but as long as it has not been rejected, the client should
continue with the request
101 Switching Protocols The server switches protocol.
200 OK The request is OK
201 Created The request is complete, and a new resource is created
202 Accepted The request is accepted for processing, but the processing is
not complete.
203 Non-authoritative
Information

204 No Content
205 Reset Content
206 Partial Content
300 Multiple Choices A link list. The user can select a link and go to that location.
Maximum five addresses
301 Moved Permanently The requested page has moved to a new url
302 Found The requested page has moved temporarily to a new url
303 See Other The requested page can be found under a different url
304 Not Modified
MAT SOFT
JAVA REFERENCE GUIDE
492
305 Use Proxy
306 8nused This code was used in a previous version. It is no longer
used, but the code is reserved.
307 Temporary Redirect The requested page has moved temporarily to a new url.
400 Bad Request The server did not understand the request
401 Unauthorized The requested page needs a username and a password
402 Payment Required <ou can not use this code yet
403 Forbidden Access is forbidden to the requested page
404 Not Found The server can not find the requested page.
405 Method Not Allowed The method specified in the request is not allowed.
406 Not Acceptable The server can only generate a response that is not accepted
by the client.
407 Proxy Authentication
Required
You must authenticate with a proxy server before this
request can be served.
408 Request Timeout The request took longer than the server was prepared to
wait.
409 Conflict The request could not be completed because of a conflict.
410 Gone The requested page is no longer available.
411 Length Required The "Content-Length" is not defined. The server will not
accept the request without it.
412 Precondition Failed The precondition given in the request evaluated to false by
the server.
413 Request Entity Too Large The server will not accept the request, because the request
entity is too large.
414 Request-url Too Long The server will not accept the request, because the url is too
long. Occurs when you convert a "post" request to a "get"
MAT SOFT
JAVA REFERENCE GUIDE
493
request with a long query information.
415 Unsupported Media Type The server will not accept the request, because the media
type is not supported.
417 Expectation Failed
500 Internal Server Error The request was not completed. The server met an
unexpected condition
501 Not Implemented The request was not completed. The server did not support
the functionality required.
502 Bad Gateway The request was not completed. The server received an
invalid response from the upstream server
503 Service Unavailable The request was not completed. The server is temporarily
overloading or down.
504 Gateway Timeout The gateway has timed out.
505 HTTP Version Not Supported The server does not support the "http protocol" version.
Methods to Set HTTP Status Code:
There are following methods which can be used to set HTTP Status Code in your servlet program.
These method are available with )ttp2er!let.esponse object.
S1N1 Method : )escription
1 p"$ic void setStats , int statsCode /
This method sets an arbitrary status code. The setStatus method takes an int (the status code)
as an argument. If your response includes a special status code and a document, be sure to call
setStatus before actually returning any of the content with the Print*riter.
2 p"$ic void send'edirect,String r$/
This method generates a 302 response along with a Location header giving the URL of the new
document.
3 p"$ic void send7rror,int code< String message/
This method sends a status code (usually 404) along with a short message that is automatically
formatted inside an HTML document and sent to the client.
MAT SOFT
JAVA REFERENCE GUIDE
494
HTTP Status Code Example:
Following is the example which would send 407 error code to the client browser and browser would
show you "Need authentication!!!" message.
Nhtml.
Nh!a#.
Ntitl!.%!tting TTP %tatus ,o#!N/titl!.
N/h!a#.
Nbo#y.
NW
// %!t !rror co#! an# r!ason.
r!spons!.s!n#3rror$FEI2 )=!!# auth!nticationGGG) (*
W.
N/bo#y.
N/html.
Now calling the above JSP would display following result:
@TTP S"%".$ 407 ; N113 %."210"#,%"#(0HHH
typ% Status report
m%ssa7% Need authentication!!!
1%s!riptio" The client must first authenticate itself with the proxy (Need authentication!!!).
Apa!h% (om!at9*-*-2&
To become more comfortable with HTTP status codes, try to set different status codes and their
description.
JSP - Form Processing
You must have come across many situations when you need to pass some information from your
browser to web server and ultimately to your backend program. The browser uses two methods to
pass this information to web server. These methods are GET Method and POST Method.
GET method:
The GET method sends the encoded user information appended to the page request. The page and the
encoded information are separated by the ? character as follows:
http-//www.t!st.com/h!lloS<!yC9valu!C[<!y@9valu!@
MAT SOFT
JAVA REFERENCE GUIDE
495
The GET method is the defualt method to pass information from browser to web server and it
produces a long string that appears in your browser's Location:box. Never use the GET method if you
have password or other sensitive information to pass to the server.
The GET method has size limtation: only 1024 characters can be in a request string.
This information is passed using QUERY_STRING header and will be accessible through
QUERY_STRING environment variable which can be handled using getQueryString() and
getParameter() methods of request object.
POST method:
A generally more reliable method of passing information to a backend program is the POST method.
This method packages the information in exactly the same way as GET methods, but instead of
sending it as a text string after a ? in the URL it sends it as a separate message. This message comes
to the backend program in the form of the standard input which you can parse and use for your
processing.
JSP handles this type of requests using getParameter() method to read simple parameters and
getInputStream() method to read binary data stream coming from the client.
Reading Form Data using JSP
JSP handles form data parsing automatically using the following methods depending on the situation:
getParameter,/: You call request.getParameter() method to get the value of a form
parameter.
getParameter*a$es,/: Call this method if the parameter appears more than once and
returns multiple values, for example checkbox.
getParameterNames,/: Call this method if you want a complete list of all parameters in the
current request.
getInptStream,/: Call this method to read binary data stream coming from the client.
GET Method Example Using URL:
Here is a simple URL which will pass two values to HelloForm program using GET method.
http:KK$oca$host:PIPIKmain1#spMfirstGnameQ@%'%:$astGnameQ%0I
Below is main1#sp JSP program to handle input given by web browser. We are going to
usegetParameter,/ method which makes it very easy to access passed information:
Nhtml.
Nh!a#.
Ntitl!.5sing 83T M!tho# to 7!a# Form 4ataN/titl!.
N/h!a#.
MAT SOFT
JAVA REFERENCE GUIDE
496
Nbo#y.
Nc!nt!r.
NhC.5sing 83T M!tho# to 7!a# Form 4ataN/hC.
Nul.
Nli.Np.Nb.First =am!-N/b.
NW9 r!Pu!st.g!tParam!t!r$)firstTnam!)(W.
N/p.N/li.
Nli.Np.Nb.1ast =am!-N/b.
NW9 r!Pu!st.g!tParam!t!r$)lastTnam!)(W.
N/p.N/li.
N/ul.
N/bo#y.
N/html.
Now type http%@@localhost%ABAB@main.jspC$irst1nameD>-.-Elast1nameD-L5 in your browser's
Location:box. This would generate following result:
Using GET Method to Read Form Data
+irst Name: ZARA
0ast Name: ALI
GET Method Example Using Form:
Here is a simple example which passes two values using HTML FORM and submit button. We are going
to use same JSP main.jsp to handle this imput.
Nhtml.
Nbo#y.
Nform action9)main.jsp) m!tho#9)83T).
First =am!- Ninput typ!9)t!:t) nam!9)firstTnam!).
Nbr /.
1ast =am!- Ninput typ!9)t!:t) nam!9)lastTnam!) /.
Ninput typ!9)submit) valu!9)%ubmit) /.
N/form.
N/bo#y.
N/html.
Keep this HTML in a file Hello.htm and put it in <Tomcat-installation-directory>/webapps/ROOT
directory. When you would access http%@@localhost%ABAB@)ello.htm, here is the actual output of the
above form.
First Name:
Last Name:
MAT SOFT
JAVA REFERENCE GUIDE
497
Try to enter First Name and Last Name and then click submit button to see the result on your local
machine where tomcat is running. Based on the input provided, it will generate similar result as
mentioned in the above example.
POST Method Example Using Form:
Let us do little modification in the above JSP to handle GET as well as POST methods. Below
ismain1#sp JSP program to handle input given by web browser using GET or POST methods.
Infact there is no change in above JSP because only way of passing parameters is changed and no
binary data is being passed to the JSP program. File handling related concepts would be explained in
separate chapter where we need to read binary data stream.
Nhtml.
Nh!a#.
Ntitl!.5sing 83T an# P?%T M!tho# to 7!a# Form 4ataN/titl!.
N/h!a#.
Nbo#y.
Nc!nt!r.
NhC.5sing 83T M!tho# to 7!a# Form 4ataN/hC.
Nul.
Nli.Np.Nb.First =am!-N/b.
NW9 r!Pu!st.g!tParam!t!r$)firstTnam!)(W.
N/p.N/li.
Nli.Np.Nb.1ast =am!-N/b.
NW9 r!Pu!st.g!tParam!t!r$)lastTnam!)(W.
N/p.N/li.
N/ul.
N/bo#y.
N/html.
Following is the content of Hello.htm file:
Nhtml.
Nbo#y.
Nform action9)main.jsp) m!tho#9)P?%T).
First =am!- Ninput typ!9)t!:t) nam!9)firstTnam!).
Nbr /.
1ast =am!- Ninput typ!9)t!:t) nam!9)lastTnam!) /.
Ninput typ!9)submit) valu!9)%ubmit) /.
N/form.
N/bo#y.
N/html.
Now let us keep main.jsp and hello.htm in <Tomcat-installation-directory>/webapps/ROOT directory.
When you would access http%@@localhost%ABAB@)ello.htm, below is the actual output of the above form.
MAT SOFT
JAVA REFERENCE GUIDE
498
First Name:
Last Name:
Try to enter First and Last Name and then click submit button to see the result on your local machine
where tomcat is running.
Based on the input provided, it would generate similar result as mentioned in the above examples.
Passing Checkbox Data to JSP Program
Checkboxes are used when more than one option is required to be selected.
Here is example HTML code, CheckBox.htm, for a form with two checkboxes
Nhtml.
Nbo#y.
Nform action9)main.jsp) m!tho#9)P?%T) targ!t9)Tblan<).
Ninput typ!9)ch!c<bo:) nam!9)maths) ch!c<!#9)ch!c<!#) /. Maths
Ninput typ!9)ch!c<bo:) nam!9)physics) /. Physics
Ninput typ!9)ch!c<bo:) nam!9)ch!mistry) ch!c<!#9)ch!c<!#) /.
,h!mistry
Ninput typ!9)submit) valu!9)%!l!ct %ubj!ct) /.
N/form.
N/bo#y.
N/html.
The result of this code is the following form
Maths Physics Chemistry
Below is main.jsp JSP program to handle input given by web browser for checkbox button.
Nhtml.
Nh!a#.
Ntitl!.7!a#ing ,h!c<bo: 4ataN/titl!.
N/h!a#.
Nbo#y.
Nc!nt!r.
NhC.7!a#ing ,h!c<bo: 4ataN/hC.
Nul.
Nli.Np.Nb.Maths Flag-N/b.
NW9 r!Pu!st.g!tParam!t!r$)maths)(W.
N/p.N/li.
Nli.Np.Nb.Physics Flag-N/b.
NW9 r!Pu!st.g!tParam!t!r$)physics)(W.
N/p.N/li.
MAT SOFT
JAVA REFERENCE GUIDE
499
Nli.Np.Nb.,h!mistry Flag-N/b.
NW9 r!Pu!st.g!tParam!t!r$)ch!mistry)(W.
N/p.N/li.
N/ul.
N/bo#y.
N/html.
For the above example, it would display following result:
Reading Checkbox Data
Maths +$ag : : on
Physics +$ag: : null
Chemistry +$ag: : on
Reading All Form Parameters:
Following is the generic example which uses getParameterNames,/ method of HttpServletRequest
to read all the available form parameters. This method returns an Enumeration that contains the
parameter names in an unspecified order.
Once we have an Enumeration, we can loop down the Enumeration in the standard manner,
using has#ore=lements() method to determine when to stop and using next=lement() method to get
each parameter name.
NW\ pag! import9)java.io.*2java.util.*) W.
Nhtml.
Nh!a#.
Ntitl!.TTP !a#!r 7!Pu!st 3:ampl!N/titl!.
N/h!a#.
Nbo#y.
Nc!nt!r.
Nh@.TTP !a#!r 7!Pu!st 3:ampl!N/h@.
Ntabl! wi#th9)CEEW) bor#!r9)C) align9)c!nt!r).
Ntr bgcolor9)^KFKFKF).
Nth.Param =am!N/th.Nth.Param Balu!$s(N/th.
N/tr.
NW
3num!ration param=am!s 9 r!Pu!st.g!tParam!t!r=am!s$(*
whil!$param=am!s.hasMor!3l!m!nts$(( {
%tring param=am! 9 $%tring(param=am!s.n!:t3l!m!nt$(*
out.print$)Ntr.Nt#.) > param=am! > )N/t#.On)(*
%tring paramBalu! 9 r!Pu!st.g!t!a#!r$param=am!(*
out.println$)Nt#. ) > paramBalu! > )N/t#.N/tr.On)(*
+
W.
N/tabl!.
MAT SOFT
JAVA REFERENCE GUIDE
500
N/c!nt!r.
N/bo#y.
N/html.
Following is the content of Hello.htm:
Nhtml.
Nbo#y.
Nform action9)main.jsp) m!tho#9)P?%T) targ!t9)Tblan<).
Ninput typ!9)ch!c<bo:) nam!9)maths) ch!c<!#9)ch!c<!#) /. Maths
Ninput typ!9)ch!c<bo:) nam!9)physics) /. Physics
Ninput typ!9)ch!c<bo:) nam!9)ch!mistry) ch!c<!#9)ch!c<!#) /. ,h!m
Ninput typ!9)submit) valu!9)%!l!ct %ubj!ct) /.
N/form.
N/bo#y.
N/html.
Now try calling JSP using above Hello.htm, this would generate a result something like as below based
on the provided input:
Reading All Form Parameters
Param Name Param *a$e,s/
maths on
chemistry on
Day 47: JSP - Cookies Handling
Cookies are text files stored on the client computer and they are kept for various information tracking
purpose. JSP transparently supports HTTP cookies using underlying servlet technology.
There are three steps involved in identifying returning users:
Server script sends a set of cookies to the browser. For example name, age, or identification
number etc.
Browser stores this information on local machine for future use.
When next time browser sends any request to web server then it sends those cookies
information to the server and server uses that information to identify the user or may be for
some other purpose as well.
This chapter will teach you how to set or reset cookies, how to access them and how to delete them
using JSP programs.
The Anatomy of a Cookie:
Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on a
browser). A JSP that sets a cookie might send headers that look something like this:
MAT SOFT
JAVA REFERENCE GUIDE
501
TTP/C.C @EE ?Y
4at!- Fri2 EF F!b @EEE @C-ED-DJ 8MT
%!rv!r- 0pach!/C.D.K $5=6R( PP/F.EbD
%!t;,oo<i!- nam!9:y/* !:pir!s9Fri#ay2 EF;F!b;EI @@-ED-DJ 8MT*
path9/* #omain9mat;soft.com
,onn!ction- clos!
,ont!nt;Typ!- t!:t/html
As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and a domain.
The name and value will be URL encoded. The expires field is an instruction to the browser to "forget"
the cookie after the given time and date.
If the browser is configured to store cookies, it will then keep this information until the expiry date. If
the user points the browser at any page that matches the path and domain of the cookie, it will resend
the cookie to the server. The browser's headers might look something like this:
83T / TTP/C.E
,onn!ction- Y!!p;0liv!
5s!r;0g!nt- Mo/illa/F.M $RCC* 6* 1inu: @.@.M;CHapmac ppc(
ost- /in<.#!mon.co.u<-CC@M
0cc!pt- imag!/gif2 */*
0cc!pt;3nco#ing- g/ip
0cc!pt;1anguag!- !n
0cc!pt;,hars!t- iso;JJHK;C2*2utf;J
,oo<i!- nam!9:y/
A JSP script will then have access to the cookies through the request
methodre4uest.getCoo(ies() which returns an array of Coo(ie objects.
Servlet Cookies Methods:
Following is the list of useful methods associated with Cookie object which you can use while
manipulating cookies in JSP:
S1N1 Method : )escription
1 p"$ic void set)omain,String pattern/
This method sets the domain to which cookie applies, for example mat-soft.com.
2 p"$ic String get)omain,/
This method gets the domain to which cookie applies, for example mat-soft.com.
3 p"$ic void setMax%ge,int expiry/
This method sets how much time (in seconds) should elapse before the cookie expires. If you
don't set this, the cookie will last only for the current session.
4 p"$ic int getMax%ge,/
This method returns the maximum age of the cookie, specified in seconds, By default, -1
MAT SOFT
JAVA REFERENCE GUIDE
502
indicating the cookie will persist until browser shutdown.
5 p"$ic String getName,/
This method returns the name of the cookie. The name cannot be changed after creation.
6 p"$ic void set*a$e,String ne3*a$e/
This method sets the value associated with the cookie.
7 p"$ic String get*a$e,/
This method gets the value associated with the cookie.
8 p"$ic void setPath,String ri/
This method sets the path to which this cookie applies. If you don't specify a path, the cookie is
returned for all URLs in the same directory as the current page as well as all subdirectories.
9 p"$ic String getPath,/
This method gets the path to which this cookie applies.
10 p"$ic void setSecre,"oo$ean f$ag/
This method sets the boolean value indicating whether the cookie should only be sent over
encrypted (i.e. SSL) connections.
11 p"$ic void setComment,String prpose/
This method specifies a comment that describes a cookie's purpose. The comment is useful if
the browser presents the cookie to the user.
12 p"$ic String getComment,/
This method returns the comment describing the purpose of this cookie, or null if the cookie has
no comment.
Setting Cookies with JSP:
Setting cookies with JSP involves three steps:
,4/ Creating a Coo=ie o"#ect: You call the Cookie constructor with a cookie name and a cookie
value, both of which are strings.
,oo<i! coo<i! 9 n!w ,oo<i!$)<!y)2)valu!)(*
Keep in mind, neither the name nor the value should contain white space or any of the following
characters:
& ' $ ( 9 2 ) / S \ - *
MAT SOFT
JAVA REFERENCE GUIDE
503
,5/ Setting the maximm age: You use setMaxAge to specify how long (in seconds) the cookie
should be valid. Following would set up a cookie for 24 hours.
coo<i!.s!tMa:0g!$ME*ME*@F(*
,E/ Sending the Coo=ie into the (TTP response headers: You use response1addCoo=ieto add
cookies in the HTTP response header as follows:
r!spons!.a##,oo<i!$coo<i!(*
Example:
Let us modify our example to set the cookies for first and last name.
NW
// ,r!at! coo<i!s for first an# last nam!s.
,oo<i! first=am! 9 n!w ,oo<i!$)firstTnam!)2
r!Pu!st.g!tParam!t!r$)firstTnam!)((*
,oo<i! last=am! 9 n!w ,oo<i!$)lastTnam!)2
r!Pu!st.g!tParam!t!r$)lastTnam!)((*
// %!t !:piry #at! aft!r @F rs for both th! coo<i!s.
first=am!.s!tMa:0g!$ME*ME*@F(*
last=am!.s!tMa:0g!$ME*ME*@F(*
// 0## both th! coo<i!s in th! r!spons! h!a#!r.
r!spons!.a##,oo<i!$ first=am! (*
r!spons!.a##,oo<i!$ last=am! (*
W.
Nhtml.
Nh!a#.
Ntitl!.%!tting ,oo<i!sN/titl!.
N/h!a#.
Nbo#y.
Nc!nt!r.
NhC.%!tting ,oo<i!sN/hC.
N/c!nt!r.
Nul.
Nli.Np.Nb.First =am!-N/b.
NW9 r!Pu!st.g!tParam!t!r$)firstTnam!)(W.
N/p.N/li.
Nli.Np.Nb.1ast =am!-N/b.
NW9 r!Pu!st.g!tParam!t!r$)lastTnam!)(W.
N/p.N/li.
N/ul.
N/bo#y.
N/html.
Let us put above code in main.jsp file and use it in the following HTML page:
MAT SOFT
JAVA REFERENCE GUIDE
504

Nhtml.
Nbo#y.
Nform action9)main.jsp) m!tho#9)83T).
First =am!- Ninput typ!9)t!:t) nam!9)firstTnam!).
Nbr /.
1ast =am!- Ninput typ!9)t!:t) nam!9)lastTnam!) /.
Ninput typ!9)submit) valu!9)%ubmit) /.
N/form.
N/bo#y.
N/html.
Keep above HTML content in a file hello.jsp and put hello.jsp and main.jsp in <Tomcat-installation-
directory>/webapps/ROOT directory. When you would accesshttp%@@localhost%ABAB@hello.jsp, here is
the actual output of the above form.
First Name:
Last Name:
Try to enter First Name and Last Name and then click submit button. This would display first name and
last name on your screen and same time it would set two cookies firstName and lastName which
would be passed back to the server when next time you would press Submit button.
Next section would explain you how you would access these cookies back in your web application.
Reading Cookies with JSP:
To read cookies, you need to create an array of ja!ax.ser!let.http.Coo(ie objects by calling
thegetCoo=ies, / method of )ttp2er!let.e4uest. Then cycle through the array, and use getName()
and getValue() methods to access each cookie and associated value.
Example:
Let us read cookies which we have set in previous example:
Nhtml.
Nh!a#.
Ntitl!.7!a#ing ,oo<i!sN/titl!.
N/h!a#.
Nbo#y.
Nc!nt!r.
NhC.7!a#ing ,oo<i!sN/hC.
N/c!nt!r.
NW
,oo<i! coo<i! 9 null*
,oo<i!&' coo<i!s 9 null*
// 8!t an array of ,oo<i!s associat!# with this #omain
coo<i!s 9 r!Pu!st.g!t,oo<i!s$(*
if$ coo<i!s G9 null ({
MAT SOFT
JAVA REFERENCE GUIDE
505
out.println$)Nh@. Foun# ,oo<i!s =am! an# Balu!N/h@.)(*
for $int i 9 E* i N coo<i!s.l!ngth* i>>({
coo<i! 9 coo<i!s&i'*
out.print$)=am! - ) > coo<i!.g!t=am!$ ( > )2 )(*
out.print$)Balu!- ) > coo<i!.g!tBalu!$ (>) Nbr/.)(*
+
+!ls!{
out.println$)Nh@.=o coo<i!s foun#sN/h@.)(*
+
W.
N/bo#y.
N/html.
Now let us put above code in main.jsp file and try to access it. If you would have set first_name cookie
as "John" and last_name cookie as "Player" then running http%@@localhost%ABAB@main.jspwould display
the following result:
Found Cookies Name and Value
Name : first_name, Value: John
Name : last_name, Value: Player
Delete Cookies with JSP:
To delete cookies is very simple. If you want to delete a cookie then you simply need to follow up
following three steps:
1. Read an already exsiting cookie and store it in Cookie object.
2. Set cookie age as zero using setMax%ge,/ method to delete an existing cookie.
3. Add this cookie back into response header.
Example:
Following example would delete and existing cookie named "first_name" and when you would run
main.jsp JSP next time it would return null value for first_name.
Nhtml.
Nh!a#.
Ntitl!.7!a#ing ,oo<i!sN/titl!.
N/h!a#.
Nbo#y.
Nc!nt!r.
NhC.7!a#ing ,oo<i!sN/hC.
MAT SOFT
JAVA REFERENCE GUIDE
506
N/c!nt!r.
NW
,oo<i! coo<i! 9 null*
,oo<i!&' coo<i!s 9 null*
// 8!t an array of ,oo<i!s associat!# with this #omain
coo<i!s 9 r!Pu!st.g!t,oo<i!s$(*
if$ coo<i!s G9 null ({
out.println$)Nh@. Foun# ,oo<i!s =am! an# Balu!N/h@.)(*
for $int i 9 E* i N coo<i!s.l!ngth* i>>({
coo<i! 9 coo<i!s&i'*
if$$coo<i!.g!t=am!$ ((.compar!To$)firstTnam!)( 99 E ({
coo<i!.s!tMa:0g!$E(*
r!spons!.a##,oo<i!$coo<i!(*
out.print$)4!l!t!# coo<i!- ) >
coo<i!.g!t=am!$ ( > )Nbr/.)(*
+
out.print$)=am! - ) > coo<i!.g!t=am!$ ( > )2 )(*
out.print$)Balu!- ) > coo<i!.g!tBalu!$ (>) Nbr/.)(*
+
+!ls!{
out.println$
)Nh@.=o coo<i!s foun#sN/h@.)(*
+
W.
N/bo#y.
N/html.
Now let us put above code in main.jsp file and try to access it. It would display the following result:
Cookies Name and Value
Deleted cookie : first_name
Name : first_name, Value: John
Name : last_name, Value: Player
Now try to run http%@@localhost%ABAB@main.jsp once again and it should display only one cookie as
follows:
Found Cookies Name and Value
Name : last_name, Value: Player
You can delete your cookies in Internet Explorer manually. Start at the Tools menu and select Internet
Options. To delete all cookies, press Delete Cookies.
MAT SOFT
JAVA REFERENCE GUIDE
507
JSP - Session Tracking
HTTP is a "stateless" protocol which means each time a client retrieves a Web page, the client opens a
separate connection to the Web server and the server automatically does not keep any record of
previous client request.
Still there are following three ways to maintain session between web client and web server:
(1) Cookies:
A webserver can assign a unique session ID as a cookie to each web client and for subsequent
requests from the client they can be recognized using the recieved cookie.
This may not be an effective way because many time browser does nots upport a cookie, so I would
not recommend to use this procedure to maintain the sessions.
(2) Hidden Form Fields:
A web server can send a hidden HTML form field along with a unique session ID as follows:
Ninput typ!9)hi##!n) nam!9)s!ssioni#) valu!9)C@DFH).
This entry means that, when the form is submitted, the specified name and value are automatically
included in the GET or POST data. Each time when web browser sends request back, then session_id
value can be used to keep the track of different web browsers.
This could be an effective way of keeping track of the session but clicking on a regular (<A HREF...>)
hypertext link does not result in a form submission, so hidden form fields also cannot support general
session tracking.
(3) URL Rewriting:
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.
For example, with http://mat-soft.com/file.htm;sessionid=12345, the session identifier is attached as
sessionid=12345 which can be accessed at the web server to identify the client.
URL rewriting is a better way to maintain sessions and works for the browsers when they don't
support cookies but here drawback is that you would have generate every URL dynamically to assign a
session ID though page is simple static HTML page.
The session Object:
MAT SOFT
JAVA REFERENCE GUIDE
508
Apart from the above mentioned three ways, JSP makes use of servlet provided HttpSession Interface
which provides a way to identify a user across more than one page request or visit to a Web site and
to store information about that user.
By default, JSPs have session tracking enabled and a new HttpSession object is instantiated for each
new client automatically. Disabling session tracking requires explicitly turning it off by setting the page
directive session attribute to false as follows:
NW\ pag! s!ssion9)fals!) W.
The JSP engine exposes the HttpSession object to the JSP author through the implicit sessionobject.
Since session object is already provided to the JSP programmer, the programmer can immediately
begin storing and retrieving data from the object without any initialization or getSession().
Here is a summary of important methods available through session object:
S1N1 Method : )escription
1 p"$ic !"#ect get%ttri"te,String name/
This method returns the object bound with the specified name in this session, or null if no object
is bound under the name.
2 p"$ic 7nmeration get%ttri"teNames,/
This method returns an Enumeration of String objects containing the names of all the objects
bound to this session.
3 p"$ic $ong getCreationTime,/
This method returns the time when this session was created, measured in milliseconds since
midnight January 1, 1970 GMT.
4 p"$ic String getId,/
This method returns a string containing the unique identifier assigned to this session.
5 p"$ic $ong get0ast%ccessedTime,/
This method returns the last time the client sent a request associated with this session, as the
number of milliseconds since midnight January 1, 1970 GMT.
6 p"$ic int getMaxInactiveInterva$,/
This method returns the maximum time interval, in seconds, that the servlet container will keep
this session open between client accesses.
7 p"$ic void inva$idate,/
This method invalidates this session and unbinds any objects bound to it.
8 p"$ic "oo$ean isNe3,
This method returns true if the client does not yet know about the session or if the client
MAT SOFT
JAVA REFERENCE GUIDE
509
chooses not to join the session.
9 p"$ic void remove%ttri"te,String name/
This method removes the object bound with the specified name from this session.
10 p"$ic void set%ttri"te,String name< !"#ect va$e/
This method binds an object to this session, using the name specified.
11 p"$ic void setMaxInactiveInterva$,int interva$/
This method specifies the time, in seconds, between client requests before the servlet container
will invalidate this session.
Session Tracking Example:
This example describes how to use the HttpSession object to find out the creation time and the last-
accessed time for a session. We would associate a new session with the request if one does not
already exist.
NW\ pag! import9)java.io.*2java.util.*) W.
NW
// 8!t s!ssion cr!ation tim!.
4at! cr!at!Tim! 9 n!w 4at!$s!ssion.g!t,r!ationTim!$((*
// 8!t last acc!ss tim! of this w!b pag!.
4at! last0cc!ssTim! 9 n!w 4at!$s!ssion.g!t1ast0cc!ss!#Tim!$((*
%tring titl! 9 )"!lcom! Lac< to my w!bsit!)*
6nt!g!r visit,ount 9 n!w 6nt!g!r$E(*
%tring visit,ountY!y 9 n!w %tring$)visit,ount)(*
%tring us!r64Y!y 9 n!w %tring$)us!r64)(*
%tring us!r64 9 n!w %tring$)0L,4)(*
// ,h!c< if this is n!w com!r on your w!b pag!.
if $s!ssion.is=!w$(({
titl! 9 )"!lcom! to my w!bsit!)*
s!ssion.s!t0ttribut!$us!r64Y!y2 us!r64(*
s!ssion.s!t0ttribut!$visit,ountY!y2 visit,ount(*
+
visit,ount 9 $6nt!g!r(s!ssion.g!t0ttribut!$visit,ountY!y*
visit,ount 9 visit,ount > C*
us!r64 9 $%tring(s!ssion.g!t0ttribut!$us!r64Y!y(*
s!ssion.s!t0ttribut!$visit,ountY!y2 visit,ount(*
W.
Nhtml.
Nh!a#.
Ntitl!.%!ssion Trac<ingN/titl!.
N/h!a#.
Nbo#y.
Nc!nt!r.
NhC.%!ssion Trac<ingN/hC.
N/c!nt!r.
MAT SOFT
JAVA REFERENCE GUIDE
510
Ntabl! bor#!r9)C) align9)c!nt!r).
Ntr bgcolor9)^KFKFKF).
Nth.%!ssion infoN/th.
Nth.Balu!N/th.
N/tr.
Ntr.
Nt#.i#N/t#.
Nt#.NW out.print$ s!ssion.g!t6#$((* W.N/t#.
N/tr.
Ntr.
Nt#.,r!ation Tim!N/t#.
Nt#.NW out.print$cr!at!Tim!(* W.N/t#.
N/tr.
Ntr.
Nt#.Tim! of 1ast 0cc!ssN/t#.
Nt#.NW out.print$last0cc!ssTim!(* W.N/t#.
N/tr.
Ntr.
Nt#.5s!r 64N/t#.
Nt#.NW out.print$us!r64(* W.N/t#.
N/tr.
Ntr.
Nt#.=umb!r of visitsN/t#.
Nt#.NW out.print$visit,ount(* W.N/t#.
N/tr.
N/tabl!.
N/bo#y.
N/html.
Now put above code in main.jsp and try to access http%@@localhost%ABAB@main.jsp. It would display the
following result when you would run for the first time:
Welcome to my website
Session Infomation
Session info va$e
id 0AE3EC93FF44E3C525B4351B77ABB2D5
Creation Time Tue Jun 08 17:26:40 GMT+04:00 2010
Time of Last Access Tue Jun 08 17:26:40 GMT+04:00 2010
User ID ABCD
Number of visits 0
Now try to run the same JSP for second time, it would display following result.
MAT SOFT
JAVA REFERENCE GUIDE
511
Welcome Back to my website
Session Infomation
info type va$e
id 0AE3EC93FF44E3C525B4351B77ABB2D5
Creation Time Tue Jun 08 17:26:40 GMT+04:00 2010
Time of Last Access Tue Jun 08 17:26:40 GMT+04:00 2010
User ID ABCD
Number of visits 1
Deleting Session Data:
When you are done with a user's session data, you have several options:
.. 'emove a partic$ar attri"te: You can call public !oid remo!e-ttribute(2tring
name)method to delete the value associated with a particular key.
/. )e$ete the 3ho$e session: You can call public !oid in!alidate() method to discard an entire
session.
0. Setting Session timeot: You can call public !oid set#ax5nacti!e5nter!al(int inter!al)method
to set the timeout for a session individually.
@. 0og the ser ot: The servers that support servlets 2.4, you can call $ogot to log the client
out of the Web server and invalidate all sessions belonging to all the users.
A. 3e"1xm$ Configration: If you are using Tomcat, apart from the above mentioned methods,
you can configure session time out in web.xml file as follows.
Ns!ssion;config.
Ns!ssion;tim!out.CHN/s!ssion;tim!out.
N/s!ssion;config.
The timeout is expressed as minutes, and overrides the default timeout which is 30 minutes in
Tomcat.
MAT SOFT
JAVA REFERENCE GUIDE
512
The getMaxInactiveInterval( ) method in a servlet returns the timeout period for that session in
seconds. So if your session is configured in web.xml for 15 minutes, getMaxInactiveInterval( ) returns
900.
Day 48: JSP - Page Redirecting
Page redirection is generally used when a document moves to a new location and we need to send the
client to this new location or may be because of load balancing, or for simple randomization.
The simplest way of redirecting a request to another page is using method send'edirect,/ of
response object. Following is the signature of this method:
public voi# r!spons!.s!n#7!#ir!ct$%tring location(
throws 6?3:c!ption
This method sends back the response to the browser along with the status code and new page
location. You can also use setStatus() and setHeader() methods together to achieve the same
redirection:
....
%tring sit! 9 )http-//www.n!wpag!.com) *
r!spons!.s!t%tatus$r!spons!.%,TM?B34TT3MP?70761A(*
MAT SOFT
JAVA REFERENCE GUIDE
513
r!spons!.s!t!a#!r$)1ocation)2 sit!(*
....
Example:
This example shows how a JSP performs page redirection to an another location:
NW\ pag! import9)java.io.*2java.util.*) W.
Nhtml.
Nh!a#.
Ntitl!.Pag! 7!#ir!ctionN/titl!.
N/h!a#.
Nbo#y.
Nc!nt!r.
NhC.Pag! 7!#ir!ctionN/hC.
N/c!nt!r.
NW
// =!w location to b! r!#ir!ct!#
%tring sit! 9 n!w %tring$)http-//www.photofuntoos.com)(*
r!spons!.s!t%tatus$r!spons!.%,TM?B34TT3MP?70761A(*
r!spons!.s!t!a#!r$)1ocation)2 sit!(*
W.
N/bo#y.
N/html.
Now let us put above code in PageRedirect.jsp and call this JSP using URL
http://localhost:8080/PageRedirect.jsp. This would take you given URL http://www.photofuntoos.com.
JSP - Database Access
To start with basic concept, let us create a simple table and create few records in that table as follows:
Create Table
To create the 7mp$oyees table in EMP database, use the following steps:
Step 1:
Open a Command Prompt and change to the installation directory as follows:
,-O.
,-O.c# Program Fil!sOMy%X1Obin
,-OProgram Fil!sOMy%X1Obin.
MAT SOFT
JAVA REFERENCE GUIDE
514
Step 2:
Login to database as follows
,-OProgram Fil!sOMy%X1Obin.mysPl ;u root ;p
3nt!r passwor#- ********
mysPl.
Step 3:
Create the table 7mp$oyee in T7ST database as follows:
mysPl. us! T3%T*
mysPl. cr!at! tabl! 3mploy!!s
$
i# int not null2
ag! int not null2
first varchar $@HH(2
last varchar $@HH(
(*
Xu!ry ?Y2 E rows aff!ct!# $E.EJ s!c(
mysPl.
Create Data Records
Finally you create few records in Employee table as follows:
mysPl. 6=%37T 6=T? 3mploy!!s B0153% $CEE2 CJ2 'Vara'2 '0li'(*
Xu!ry ?Y2 C row aff!ct!# $E.EH s!c(

mysPl. 6=%37T 6=T? 3mploy!!s B0153% $CEC2 @H2 'Mahna/'2 'Fatma'(*
Xu!ry ?Y2 C row aff!ct!# $E.EE s!c(

mysPl. 6=%37T 6=T? 3mploy!!s B0153% $CE@2 DE2 'Vai#'2 'Yhan'(*
Xu!ry ?Y2 C row aff!ct!# $E.EE s!c(

mysPl. 6=%37T 6=T? 3mploy!!s B0153% $CED2 @J2 '%umit'2 'Mittal'(*
Xu!ry ?Y2 C row aff!ct!# $E.EE s!c(

mysPl.
SELECT Operation:
Following example shows how we can execute SQL SELECT statement using JTSL in JSP programming:
NW\ pag! import9)java.io.*2java.util.*2java.sPl.*)W.
NW\ pag! import9)java:.s!rvl!t.http.*2java:.s!rvl!t.*) W.
MAT SOFT
JAVA REFERENCE GUIDE
515
NW\ taglib uri9)http-//java.sun.com/jsp/jstl/cor!) pr!fi:9)c)W.
NW\ taglib uri9)http-//java.sun.com/jsp/jstl/sPl) pr!fi:9)sPl)W.

Nhtml.
Nh!a#.
Ntitl!.%313,T ?p!rationN/titl!.
N/h!a#.
Nbo#y.

NsPl-s!t4ata%ourc! var9)snapshot) #riv!r9)com.mysPl.j#bc.4riv!r)
url9)j#bc-mysPl-//localhost/T3%T)
us!r9)root) passwor#9)passC@D)/.

NsPl-Pu!ry #ata%ourc!9)U{snapshot+) var9)r!sult).
%313,T * from 3mploy!!s*
N/sPl-Pu!ry.

Ntabl! bor#!r9)C) wi#th9)CEEW).
Ntr.
Nth.3mp 64N/th.
Nth.First =am!N/th.
Nth.1ast =am!N/th.
Nth.0g!N/th.
N/tr.
Nc-for3ach var9)row) it!ms9)U{r!sult.rows+).
Ntr.
Nt#.Nc-out valu!9)U{row.i#+)/.N/t#.
Nt#.Nc-out valu!9)U{row.first+)/.N/t#.
Nt#.Nc-out valu!9)U{row.last+)/.N/t#.
Nt#.Nc-out valu!9)U{row.ag!+)/.N/t#.
N/tr.
N/c-for3ach.
N/tabl!.

N/bo#y.
N/html.
Now try to access above JSP, which should display the following result:
7mp I) +irst Name 0ast Name %ge
100 Zara Ali 18
101 Mahnaz Fatma 25
102 Zaid Khan 30
103 Sumit Mittal 28
INSERT Operation:
MAT SOFT
JAVA REFERENCE GUIDE
516
Following example shows how we can execute SQL INSERT statement using JTSL in JSP programming:
NW\ pag! import9)java.io.*2java.util.*2java.sPl.*)W.
NW\ pag! import9)java:.s!rvl!t.http.*2java:.s!rvl!t.*) W.
NW\ taglib uri9)http-//java.sun.com/jsp/jstl/cor!) pr!fi:9)c)W.
NW\ taglib uri9)http-//java.sun.com/jsp/jstl/sPl) pr!fi:9)sPl)W.

Nhtml.
Nh!a#.
Ntitl!.J6=%37T ?p!rationN/titl!.
N/h!a#.
Nbo#y.

NsPl-s!t4ata%ourc! var9)snapshot) #riv!r9)com.mysPl.j#bc.4riv!r)
url9)j#bc-mysPl-//localhost/T3%T)
us!r9)root) passwor#9)passC@D)/.
NsPl-Pu!ry #ata%ourc!9)U{snapshot+) var9)r!sult).
6=%37T 6=T? 3mploy!!s B0153% $CEF2 @2 '=uha'2 '0li'(*
N/sPl-Pu!ry.

NsPl-Pu!ry #ata%ourc!9)U{snapshot+) var9)r!sult).
%313,T * from 3mploy!!s*
N/sPl-Pu!ry.

Ntabl! bor#!r9)C) wi#th9)CEEW).
Ntr.
Nth.3mp 64N/th.
Nth.First =am!N/th.
Nth.1ast =am!N/th.
Nth.0g!N/th.
N/tr.
Nc-for3ach var9)row) it!ms9)U{r!sult.rows+).
Ntr.
Nt#.Nc-out valu!9)U{row.i#+)/.N/t#.
Nt#.Nc-out valu!9)U{row.first+)/.N/t#.
Nt#.Nc-out valu!9)U{row.last+)/.N/t#.
Nt#.Nc-out valu!9)U{row.ag!+)/.N/t#.
N/tr.
N/c-for3ach.
N/tabl!.

N/bo#y.
N/html.
Now try to access above JSP, which should display the following result:
7mp I) +irst Name 0ast Name %ge
100 Zara Ali 18
101 Mahnaz Fatma 25
MAT SOFT
JAVA REFERENCE GUIDE
517
102 Zaid Khan 30
103 Sumit Mittal 28
104 Nuha Ali 2
DELETE Operation:
Following example shows how we can execute SQL DELETE statement using JTSL in JSP programming:
NW\ pag! import9)java.io.*2java.util.*2java.sPl.*)W.
NW\ pag! import9)java:.s!rvl!t.http.*2java:.s!rvl!t.*) W.
NW\ taglib uri9)http-//java.sun.com/jsp/jstl/cor!) pr!fi:9)c)W.
NW\ taglib uri9)http-//java.sun.com/jsp/jstl/sPl) pr!fi:9)sPl)W.

Nhtml.
Nh!a#.
Ntitl!.4313T3 ?p!rationN/titl!.
N/h!a#.
Nbo#y.

NsPl-s!t4ata%ourc! var9)snapshot) #riv!r9)com.mysPl.j#bc.4riv!r)
url9)j#bc-mysPl-//localhost/T3%T)
us!r9)root) passwor#9)passC@D)/.

Nc-s!t var9)!mp6#) valu!9)CED)/.

NsPl-up#at! #ata%ourc!9)U{snapshot+) var9)count).
4313T3 F7?M 3mploy!!s "373 6# 9 S
NsPl-param valu!9)U{!mp6#+) /.
N/sPl-up#at!.

NsPl-Pu!ry #ata%ourc!9)U{snapshot+) var9)r!sult).
%313,T * from 3mploy!!s*
N/sPl-Pu!ry.

Ntabl! bor#!r9)C) wi#th9)CEEW).
Ntr.
Nth.3mp 64N/th.
Nth.First =am!N/th.
Nth.1ast =am!N/th.
Nth.0g!N/th.
N/tr.
Nc-for3ach var9)row) it!ms9)U{r!sult.rows+).
Ntr.
Nt#.Nc-out valu!9)U{row.i#+)/.N/t#.
Nt#.Nc-out valu!9)U{row.first+)/.N/t#.
Nt#.Nc-out valu!9)U{row.last+)/.N/t#.
Nt#.Nc-out valu!9)U{row.ag!+)/.N/t#.
MAT SOFT
JAVA REFERENCE GUIDE
518
N/tr.
N/c-for3ach.
N/tabl!.

N/bo#y.
N/html.
Now try to access above JSP, which should display the following result:
7mp I) +irst Name 0ast Name %ge
100 Zara Ali 18
101 Mahnaz Fatma 25
102 Zaid Khan 30
UPDATE Operation:
Following example shows how we can execute SQL UPDATE statement using JTSL in JSP
programming:
NW\ pag! import9)java.io.*2java.util.*2java.sPl.*)W.
NW\ pag! import9)java:.s!rvl!t.http.*2java:.s!rvl!t.*) W.
NW\ taglib uri9)http-//java.sun.com/jsp/jstl/cor!) pr!fi:9)c)W.
NW\ taglib uri9)http-//java.sun.com/jsp/jstl/sPl) pr!fi:9)sPl)W.

Nhtml.
Nh!a#.
Ntitl!.4313T3 ?p!rationN/titl!.
N/h!a#.
Nbo#y.

NsPl-s!t4ata%ourc! var9)snapshot) #riv!r9)com.mysPl.j#bc.4riv!r)
url9)j#bc-mysPl-//localhost/T3%T)
us!r9)root) passwor#9)passC@D)/.

Nc-s!t var9)!mp6#) valu!9)CE@)/.

NsPl-up#at! #ata%ourc!9)U{snapshot+) var9)count).
5P40T3 3mploy!!s %3T last 9 '0li'
NsPl-param valu!9)U{!mp6#+) /.
N/sPl-up#at!.

NsPl-Pu!ry #ata%ourc!9)U{snapshot+) var9)r!sult).
%313,T * from 3mploy!!s*
N/sPl-Pu!ry.

Ntabl! bor#!r9)C) wi#th9)CEEW).
Ntr.
MAT SOFT
JAVA REFERENCE GUIDE
519
Nth.3mp 64N/th.
Nth.First =am!N/th.
Nth.1ast =am!N/th.
Nth.0g!N/th.
N/tr.
Nc-for3ach var9)row) it!ms9)U{r!sult.rows+).
Ntr.
Nt#.Nc-out valu!9)U{row.i#+)/.N/t#.
Nt#.Nc-out valu!9)U{row.first+)/.N/t#.
Nt#.Nc-out valu!9)U{row.last+)/.N/t#.
Nt#.Nc-out valu!9)U{row.ag!+)/.N/t#.
N/tr.
N/c-for3ach.
N/tabl!.

N/bo#y.
N/html.
Now try to access above JSP, which should display the following result:
7mp I) +irst Name 0ast Name %ge
100 Zara Ali 18
101 Mahnaz Fatma 25
102 Zaid Ali 30
Day 49: JSP - JavaBeans
A JavaBean is a specially constructed Java class written in the Java and coded according to the
JavaBeans API specifications.
Following are the unique characteristics that distinguish a JavaBean from other Java classes:
It provides a default, no-argument constructor.
It should be serializable and implement the Seria$i2a"$e interface.
It may have a number of properties which can be read or written.
It may have a number of "getter" and "setter" methods for the properties.
JavaBeans Properties:
A JavaBean property is a named attribute that can be accessed by the user of the object. The attribute
can be of any Java data type, including classes that you define.
A JavaBean property may be read, write, read only, or write only. JavaBean properties are accessed
through two methods in the JavaBean's implementation class:
MAT SOFT
JAVA REFERENCE GUIDE
520
Method )escription
getPropertyName() For example, if property name is $irst+ame, your method name would
be getFirstName() to read that property. This method is called
accessor.
setPropertyName() For example, if property name is $irst+ame, your method name would
be setFirstName() to write that property. This method is called mutator.
A read-only attribute will have only a getPropertyName() method, and a write-only attribute will
have only a setPropertyName() method.
JavaBeans Example:
Consider a student class with few properties:
pac<ag! mypac<*
public class %tu#!ntsL!an impl!m!nts java.io.%!riali/abl!
{
privat! %tring first=am! 9 null*
privat! %tring last=am! 9 null*
privat! int ag! 9 E*
public %tu#!ntsL!an$( {
+
public %tring g!tFirst=am!$({
r!turn first=am!*
+
public %tring g!t1ast=am!$({
r!turn last=am!*
+
public int g!t0g!$({
r!turn ag!*
+
public voi# s!tFirst=am!$%tring first=am!({
this.first=am! 9 first=am!*
+
public voi# s!t1ast=am!$%tring last=am!({
this.last=am! 9 last=am!*
+
public voi# s!t0g!$6nt!g!r ag!({
this.ag! 9 ag!*
+
+
Accessing JavaBeans:
The seBean action declares a JavaBean for use in a JSP. Once declared, the bean becomes a
scripting variable that can be accessed by both scripting elements and other custom tags used in the
JSP. The full syntax for the useBean tag is as follows:
MAT SOFT
JAVA REFERENCE GUIDE
521
Njsp-us!L!an i#9)b!an's nam!) scop!9)b!an's scop!) typ!%p!c/.
Here values for the scope attribute could be page, request, session or application based on your
requirement. The value of the id attribute may be any value as a long as it is a unique name among
other useBean declarations in the same JSP.
Following example shows its simple usage:
Nhtml.
Nh!a#.
Ntitl!.us!L!an 3:ampl!N/titl!.
N/h!a#.
Nbo#y.
Njsp-us!L!an i#9)#at!) class9)java.util.4at!) /.
Np.Th! #at!/tim! is NW9 #at! W.
N/bo#y.
N/html.
This would produce following result:
Th! #at!/tim! is Thu %!p DE CC-CJ-CC 8%T @ECE
Accessing JavaBeans Properties:
Along with <jsp:useBean...>, you can use <jsp:getProperty/> action to access get methods and
<jsp:setProperty/> action to access set methods. Here is the full syntax:
Njsp-us!L!an i#9)i#) class9)b!an's class) scop!9)b!an's scop!).
Njsp-s!tProp!rty nam!9)b!an's i#) prop!rty9)prop!rty nam!)
valu!9)valu!)/.
Njsp-g!tProp!rty nam!9)b!an's i#) prop!rty9)prop!rty nam!)/.
...........
N/jsp-us!L!an.
The name attribute references the id of a JavaBean previously introduced to the JSP by the useBean
action. The property attribute is the name of the get or set methods that should be invoked. Following
is a simple example to access the data using above syntax:
Nhtml.
Nh!a#.
Ntitl!.g!t an# s!t prop!rti!s 3:ampl!N/titl!.
N/h!a#.
Nbo#y.
MAT SOFT
JAVA REFERENCE GUIDE
522
Njsp-us!L!an i#9)stu#!nts)
class9)mypac<.%tu#!ntsL!an).
Njsp-s!tProp!rty nam!9)stu#!nts) prop!rty9)first=am!) valu!9)Vara)/.
Njsp-s!tProp!rty nam!9)stu#!nts) prop!rty9)last=am!) valu!9)0li)/.
Njsp-s!tProp!rty nam!9)stu#!nts) prop!rty9)ag!) valu!9)CE)/.
N/jsp-us!L!an.
Np.%tu#!nt First =am!-
Njsp-g!tProp!rty nam!9)stu#!nts) prop!rty9)first=am!)/.
N/p.
Np.%tu#!nt 1ast =am!-
Njsp-g!tProp!rty nam!9)stu#!nts) prop!rty9)last=am!)/.
N/p.
Np.%tu#!nt 0g!-
Njsp-g!tProp!rty nam!9)stu#!nts) prop!rty9)ag!)/.
N/p.
N/bo#y.
N/html.
Let us make StudentsBean.class available in CLASSPATH and try to access above JSP. This would
produce following result:
%tu#!nt First =am!- Vara
%tu#!nt 1ast =am!- 0li
%tu#!nt 0g!- CE
Day 50: JSP - Exception Handling
When you are writing JSP code, a programmer may leave a coding errors which can occur at any part
of the code. You can have following type of errors in your JSP code:
Chec=ed exceptions: Achecked exception is an exception that is typically a user error or a
problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but
the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at
the time of compilation.
'ntime exceptions: A runtime exception is an exception that occurs that probably could
have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions
are ignored at the time of compliation.
7rrors: These are not exceptions at all, but problems that arise beyond the control of the user
or the programmer. Errors are typically ignored in your code because you can rarely do
anything about an error. For example, if a stack overflow occurs, an error will arise. They are
also ignored at the time of compilation.
Using Exception Object:
MAT SOFT
JAVA REFERENCE GUIDE
523
The exception object is an instance of a subclass of Throwable (e.g., java.lang. NullPointerException)
and is only available in error pages. Following is the list of important medthods available in the
Throwable class.
SN Methods 3ith )escription
1 p"$ic String getMessage,/
Returns a detailed message about the exception that has occurred. This message is initialized in
the Throwable constructor.
2 p"$ic Thro3a"$e getCase,/
Returns the cause of the exception as represented by a Throwable object.
3 p"$ic String toString,/
Returns the name of the class concatenated with the result of getMessage()
4 p"$ic void printStac=Trace,/
Prints the result of toString() along with the stack trace to System.err, the error output stream.
5 p"$ic Stac=Trace7$ement -. getStac=Trace,/
Returns an array containing each element on the stack trace. The element at index 0 represents
the top of the call stack, and the last element in the array represents the method at the bottom
of the call stack.
6 p"$ic Thro3a"$e fi$$InStac=Trace,/
Fills the stack trace of this Throwable object with the current stack trace, adding to any previous
information in the stack trace.
JSP gives you an option to specify Error Page for each JSP. Whenever the page throws an exception,
the JSP container automatically invokes the error page.
Following is an example to specifiy an error page for a main.jsp. To set up an error page, use the <
%@ page errorPage="xxx" %> directive.
NW\ pag! !rrorPag!9)%how3rror.jsp) W.
Nhtml.
Nh!a#.
Ntitl!.3rror an#ling 3:ampl!N/titl!.
N/h!a#.
Nbo#y.
NW
// Throw an !:c!ption to invo<! th! !rror pag!
int : 9 C*
if $: 99 C(
{
throw n!w 7untim!3:c!ption$)3rror con#itionGGG)(*
+
W.
N/bo#y.
N/html.
Now you would have to write one Error Handling JSP ShowError.jsp, which is given below. Notice that
the error-handling page includes the directive <%@ page isErrorPage="true" %>. This directive
causes the JSP compiler to generate the exception instance variable.
MAT SOFT
JAVA REFERENCE GUIDE
524
NW\ pag! is3rrorPag!9)tru!) W.
Nhtml.
Nh!a#.
Ntitl!.%how 3rror Pag!N/titl!.
N/h!a#.
Nbo#y.
NhC.?pps...N/hC.
Np.%orry2 an !rror occurr!#.N/p.
Np.!r! is th! !:c!ption stac< trac!- N/p.
Npr!.
NW !:c!ption.print%tac<Trac!$r!spons!.g!t"rit!r$((* W.
N/pr!.
N/bo#y.
N/html.
Now try to access main.jsp, it should generate something as follows:
java.lang.7untim!3:c!ption- 3rror con#itionGGG
......
?pps...
%orry2 an !rror occurr!#.
!r! is th! !:c!ption stac< trac!-
Using JSTL tags for Error Page:
You can make use of JSTL tags to write an error page ShowError.jsp. This page has almost same logic
which we have used in above example, but it has better structure and it provides more information:
NW\ taglib pr!fi:9)c) uri9)http-//java.sun.com/jsp/jstl/cor!) W.
NW\pag! is3rrorPag!9)tru!) W.
Nhtml.
Nh!a#.
Ntitl!.%how 3rror Pag!N/titl!.
N/h!a#.
Nbo#y.
NhC.?pps...N/hC.
Ntabl! wi#th9)CEEW) bor#!r9)C).
Ntr valign9)top).
Nt# wi#th9)FEW).Nb.3rror-N/b.N/t#.
Nt#.U{pag!,ont!:t.!:c!ption+N/t#.
N/tr.
Ntr valign9)top).
Nt#.Nb.576-N/b.N/t#.
Nt#.U{pag!,ont!:t.!rror4ata.r!Pu!st576+N/t#.
N/tr.
Ntr valign9)top).
Nt#.Nb.%tatus co#!-N/b.N/t#.
Nt#.U{pag!,ont!:t.!rror4ata.status,o#!+N/t#.
N/tr.
MAT SOFT
JAVA REFERENCE GUIDE
525
Ntr valign9)top).
Nt#.Nb.%tac< trac!-N/b.N/t#.
Nt#.
Nc-for3ach var9)trac!)
it!ms9)U{pag!,ont!:t.!:c!ption.stac<Trac!+).
Np.U{trac!+N/p.
N/c-for3ach.
N/t#.
N/tr.
N/tabl!.
N/bo#y.
N/html.
Now try to access main.jsp, it should generate something as follows:
Opps...
7rror: java.lang.RuntimeException: Error condition!!!
B'I: /main.jsp
Stats code: 500
Stac= trace: org.apache.jsp.main_jsp._jspService(main_jsp.java:65)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:68)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:265)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
...................
Using Try...Catch Block:
If you want to handle errors with in the same page and want to take some action instead of firing an
error page, you can make use of try1111catch block.
Following is a simple example which shows how to use try...catch block. Let us put following code in
main.jsp:
Nhtml.
Nh!a#.
Ntitl!.Try...,atch 3:ampl!N/titl!.
N/h!a#.
Nbo#y.
NW
try{
int i 9 C*
i 9 i / E*
MAT SOFT
JAVA REFERENCE GUIDE
526
out.println$)Th! answ!r is ) > i(*
+
catch $3:c!ption !({
out.println$)0n !:c!ption occurr!#- ) > !.g!tM!ssag!$((*
+
W.
N/bo#y.
N/html.
Now try to access main.jsp, it should generate something as follows:
0n !:c!ption occurr!#- / by /!ro
Day 51: JSP - Custom Tags
A custom tag is a user-defined JSP language element. When a JSP page containing a custom tag is
translated into a servlet, the tag is converted to operations on an object called a tag handler. The Web
container then invokes those operations when the JSP page's servlet is executed.
JSP tag extensions let you create new tags that you can insert directly into a JavaServer Page just as
you would the built-in tags you learned about in earlier chapter. The JSP 2.0 specification introduced
Simple Tag Handlers for writing these custom tags.
To write a customer tab you can simply extend SimpleTagSupport class and override
thedoTag,/ method, where you can place your code to generate content for the tag.
Create "Hello" Tag:
Consider you want to define a custom tag named <ex:Hello> and you want to use it in the following
fashion without a body:
N!:-!llo /.
To create a custom JSP tag, you must first create a Java class that acts as a tag handler. So let us
create HelloTag class as follows:
MAT SOFT
JAVA REFERENCE GUIDE
527
pac<ag! mypac<*
import java:.s!rvl!t.jsp.tag!:t.**
import java:.s!rvl!t.jsp.**
import java.io.**
public class !lloTag !:t!n#s %impl!Tag%upport {
public voi# #oTag$( throws Jsp3:c!ption2 6?3:c!ption {
Jsp"rit!r out 9 g!tJsp,ont!:t$(.g!t?ut$(*
out.println$)!llo ,ustom TagG)(*
+
+
Above code has simple coding where doTag() method takes the current JspContext object using
getJspContext() method and uses it to send "Hello Custom Tag!" to the current JspWriter object.
Let us compile above class and copy it in a directory available in environment variable CLASSPATH.
Finally create following tag library file: <Tomcat-Installation-Directory>webapps\ROOT\WEB-
INF\custom.tld.
Ntaglib.
Ntlib;v!rsion.C.EN/tlib;v!rsion.
Njsp;v!rsion.@.EN/jsp;v!rsion.
Nshort;nam!.3:ampl! T14N/short;nam!.
Ntag.
Nnam!.!lloN/nam!.
Ntag;class.mypac<.!lloTagN/tag;class.
Nbo#y;cont!nt.!mptyN/bo#y;cont!nt.
N/tag.
N/taglib.
Now it's time to use above defined custom tag (e$$o in our JSP program as follows:
NW\ taglib pr!fi:9)!:) uri9)"3L;6=F/custom.tl#)W.
Nhtml.
Nh!a#.
Ntitl!.0 sampl! custom tagN/titl!.
N/h!a#.
Nbo#y.
N!:-!llo/.
N/bo#y.
N/html.
Try to call above JSP and this should produce following result:
!llo ,ustom TagG
Accessing the Tag Body:
MAT SOFT
JAVA REFERENCE GUIDE
528
You can include a message in the body of the tag as you have seen with standard tags. Consider you
want to define a custom tag named <ex:Hello> and you want to use it in the following fashion with a
body:
N!:-!llo.
This is m!ssag! bo#y
N/!:-!llo.
Let us make following changes in above our tag code to process the body of the tag:
pac<ag! mypac<*
import java:.s!rvl!t.jsp.tag!:t.**
import java:.s!rvl!t.jsp.**
import java.io.**
public class !lloTag !:t!n#s %impl!Tag%upport {
%tring"rit!r sw 9 n!w %tring"rit!r$(*
public voi# #oTag$(
throws Jsp3:c!ption2 6?3:c!ption
{
g!tJspLo#y$(.invo<!$sw(*
g!tJsp,ont!:t$(.g!t?ut$(.println$sw.to%tring$((*
+
+
In this case, the output resulting from the invocation is first captured into a StringWriter before being
written to the JspWriter associated with the tag. Now accordingly we need to change TLD file as
follows:
Ntaglib.
Ntlib;v!rsion.C.EN/tlib;v!rsion.
Njsp;v!rsion.@.EN/jsp;v!rsion.
Nshort;nam!.3:ampl! T14 with Lo#yN/short;nam!.
Ntag.
Nnam!.!lloN/nam!.
Ntag;class.mypac<.!lloTagN/tag;class.
Nbo#y;cont!nt.scriptl!ssN/bo#y;cont!nt.
N/tag.
N/taglib.
Now let us call above tag with proper body as follows:
NW\ taglib pr!fi:9)!:) uri9)"3L;6=F/custom.tl#)W.
Nhtml.
Nh!a#.
Ntitl!.0 sampl! custom tagN/titl!.
N/h!a#.
Nbo#y.
MAT SOFT
JAVA REFERENCE GUIDE
529
N!:-!llo.
This is m!ssag! bo#y
N/!:-!llo.
N/bo#y.
N/html.
This will produce following result:
This is m!ssag! bo#y
Custom Tag Attributes:
You can use various attributes along with your custom tags. To accept an attribute value, a custom tag
class needs to implement setter methods, identical to JavaBean setter methods as shown below:
pac<ag! mypac<*
import java:.s!rvl!t.jsp.tag!:t.**
import java:.s!rvl!t.jsp.**
import java.io.**
public class !lloTag !:t!n#s %impl!Tag%upport {
privat! %tring m!ssag!*
public voi# s!tM!ssag!$%tring msg( {
this.m!ssag! 9 msg*
+
%tring"rit!r sw 9 n!w %tring"rit!r$(*
public voi# #oTag$(
throws Jsp3:c!ption2 6?3:c!ption
{
if $m!ssag! G9 null( {
/* 5s! m!ssag! from attribut! */
Jsp"rit!r out 9 g!tJsp,ont!:t$(.g!t?ut$(*
out.println$ m!ssag! (*
+
!ls! {
/* us! m!ssag! from th! bo#y */
g!tJspLo#y$(.invo<!$sw(*
g!tJsp,ont!:t$(.g!t?ut$(.println$sw.to%tring$((*
+
+
+
The attribute's name is "message", so the setter method is setMessage(). Now let us add this attribute
in TLD file using <attribute> element as follows:
MAT SOFT
JAVA REFERENCE GUIDE
530
Ntaglib.
Ntlib;v!rsion.C.EN/tlib;v!rsion.
Njsp;v!rsion.@.EN/jsp;v!rsion.
Nshort;nam!.3:ampl! T14 with Lo#yN/short;nam!.
Ntag.
Nnam!.!lloN/nam!.
Ntag;class.mypac<.!lloTagN/tag;class.
Nbo#y;cont!nt.scriptl!ssN/bo#y;cont!nt.
Nattribut!.
Nnam!.m!ssag!N/nam!.
N/attribut!.
N/tag.
N/taglib.
Now let us try following JSP with message attribute as follows:
NW\ taglib pr!fi:9)!:) uri9)"3L;6=F/custom.tl#)W.
Nhtml.
Nh!a#.
Ntitl!.0 sampl! custom tagN/titl!.
N/h!a#.
Nbo#y.
N!:-!llo m!ssag!9)This is custom tag) /.
N/bo#y.
N/html.
This will produce following result:
This is custom tag
Hope above example makes sense for you. It would be worth to note that you can include following
properties for an attribute:
Property Prpose
name The name element defines the name of an attribute. Each attribute
name must be unique for a particular tag.
required This specifies if this attribute is required or optional. It would be false
for optional.
rtexprvalue Declares if a runtime expression value for a tag attribute is valid
type Defines the Java class-type of this attribute. By default it is assumed
as String
description Informational description can be provided.
fragment Declares if this attribute value should be treated as aJsp+ragment.
Following is the example to specify properties related to an attribute:
MAT SOFT
JAVA REFERENCE GUIDE
531
.....
Nattribut!.
Nnam!.attribut!Tnam!N/nam!.
Nr!Puir!#.fals!N/r!Puir!#.
Ntyp!.java.util.4at!N/typ!.
Nfragm!nt.fals!N/fragm!nt.
N/attribut!.
.....
If you are using two attributes then you can modify your TLD as follows:
.....
Nattribut!.
Nnam!.attribut!Tnam!CN/nam!.
Nr!Puir!#.fals!N/r!Puir!#.
Ntyp!.java.util.Lool!anN/typ!.
Nfragm!nt.fals!N/fragm!nt.
N/attribut!.
Nattribut!.
Nnam!.attribut!Tnam!@N/nam!.
Nr!Puir!#.tru!N/r!Puir!#.
Ntyp!.java.util.4at!N/typ!.
N/attribut!.
.....
JSP - Expression Language (EL)
JSP Expression Language (EL) makes it possible to easily access application data stored in JavaBeans
components. JSP EL allows you to create expressions both ,a/ arithmetic and ,"/logical. Within a JSP
EL expression, you can use integers, floating point numbers, strings, the built-in constants true and
false for boolean values, and null.
Simple Syntax:
Typically, when you specify an attribute value in a JSP tag, you simply use a string. For example:

Njsp-s!tProp!rty nam!9)bo:) prop!rty9)p!rim!t!r) valu!9)CEE)/.
JSP EL allows you to specify an expression for any of these attribute values. A simple syntax for JSP
EL is as follows:

U{!:pr+
MAT SOFT
JAVA REFERENCE GUIDE
532
Here expr specifies the expression itself. The most common operators in JSP EL are 1 and -.. These
two operators allow you to access various attributes of Java Beans and built-in JSP objects.
For example above syntax <jsp:setProperty> tag can be written with an expression like:

Njsp-s!tProp!rty nam!9)bo:) prop!rty9)p!rim!t!r)
valu!9)U{@*bo:.wi#th>@*bo:.h!ight+)/.
When the JSP compiler sees the ${} form in an attribute, it generates code to evaluate the expression
and substitues the value of expresson.
You can also use JSP EL expressions within template text for a tag. For example, the <jsp:text> tag
simply inserts its content within the body of a JSP. The following <jsp:text> declaration inserts
<h1>Hello JSP!</h1> into the JSP output:

Njsp-t!:t.
NhC.!llo J%PGN/hC.
N/jsp-t!:t.
You can include a JSP EL expression in the body of a <jsp:text> tag (or any other tag) with the same
${} syntax you use for attributes. For example:

Njsp-t!:t.
Lo: P!rim!t!r is- U{@*bo:.wi#th > @*bo:.h!ight+
N/jsp-t!:t.
EL expressions can use parentheses to group subexpressions. For example, ${(1 + 2) * 3} equals 9,
but ${1 + (2 * 3)} equals 7.
To deactivate the evaluation of EL expressions, we specify the isELIgnored attribute of the page
directive as below:
NW\ pag! is316gnor!# 9)tru!afals!) W.
The valid values of this attribute are true and false. If it is true, EL expressions are ignored when they
appear in static text or tag attributes. If it is false, EL expressions are evaluated by the container.
Basic Operators in EL:
JSP Expression Language (EL) supports most of the arithmatic and logical operators supported by
Java. Below is the list of most frequently used operators:
!perator )escription
. Access a bean property or Map entry
MAT SOFT
JAVA REFERENCE GUIDE
533
[] Access an array or List element
( ) Group a subexpression to change the evaluation order
+ Addition
- Subtraction or negation of a value
* Multiplication
/ or div Division
% or mod Modulo (remainder)
== or eq Test for equality
!= or ne Test for inequality
< or lt Test for less than
> or gt Test for greater than
<= or le Test for less than or equal
>= or gt Test for greater than or equal
&& or and Test for logical AND
|| or or Test for logical OR
! or not Unary Boolean complement
empty Test for empty variable values
Functions in JSP EL :
JSP EL allows you to use functions in expressions as well. These functions must be defined in custom
tag libraries. A function usage has the following syntax:

MAT SOFT
JAVA REFERENCE GUIDE
534
U{ns-func$paramC2 param@2 ...(+
Where ns is the namespace of the function, func is the name of the function and param1 is the first
parameter value. For example, the function fn:length, which is part of the JSTL library can be used as
follows to get the the length of a string.

U{fn-l!ngth$)8!t my l!ngth)(+
To use a function from any tag library (standard or custom), you must install that library on your
server and must include the library in your JSP using <taglib> directive as explained in JSTL chapter.
JSP EL Implicit Objects:
The JSP expression language supports the following implicit objects:
Imp$icit o"#ect )escription
pageScope Scoped variables from page scope
requestScope Scoped variables from request scope
sessionScope Scoped variables from session scope
applicationScope Scoped variables from application scope
param Request parameters as strings
paramValues Request parameters as collections of strings
header HTTP request headers as strings
headerValues HTTP request headers as collections of strings
initParam Context-initialization parameters
cookie Cookie values
pageContext The JSP PageContext object for the current page
MAT SOFT
JAVA REFERENCE GUIDE
535
You can use these objects in an expression as if they were variables. Here are few examples which
would clear the concept:
The pageContext Object:
The pageContext object gives you access to the pageContext JSP object. Through the pageContext
object, you can access the request object. For example, to access the incoming query string for a
request, you can use the expression:

U{pag!,ont!:t.r!Pu!st.Pu!ry%tring+
The Scope Objects:
The pageScope, requestScope, sessionScope, and applicationScope variables provide access to
variables stored at each scope level.
For example, If you need to explicitly access the box variable in the application scope, you can access
it through the applicationScope variable as applicationScope.box.
The param and paramValues Objects:
The param and paramValues objects give you access to the parameter values normally available
through the request.getParameter and request.getParameterValues methods.
For example, to access a parameter named order, use the expression ${param.order} or $
{param["order"]}.
Following is the example to access a request parameter named username:

NW\ pag! import9)java.io.*2java.util.*) W.
NW
%tring titl! 9 )0cc!ssing 7!Pu!st Param)*
W.
Nhtml.
Nh!a#.
Ntitl!.NW out.print$titl!(* W.N/titl!.
N/h!a#.
Nbo#y.
Nc!nt!r.
NhC.NW out.print$titl!(* W.N/hC.
N/c!nt!r.
N#iv align9)c!nt!r).
Np.U{param&)us!rnam!)'+N/p.
N/#iv.
N/bo#y.
N/html.
MAT SOFT
JAVA REFERENCE GUIDE
536
The param object returns single string values, whereas the paramValues object returns string arrays.
header and headerValues Objects:
The header and headerValues objects give you access to the header values normally available through
the request.getHeader and request.getHeaders methods.
For example, to access a header named user-agent, use the expression ${header.user-agent} or $
{header["user-agent"]}.
Following is the example to access a header parameter named user-agent:

NW\ pag! import9)java.io.*2java.util.*) W.
NW
%tring titl! 9 )5s!r 0g!nt 3:ampl!)*
W.
Nhtml.
Nh!a#.
Ntitl!.NW out.print$titl!(* W.N/titl!.
N/h!a#.
Nbo#y.
Nc!nt!r.
NhC.NW out.print$titl!(* W.N/hC.
N/c!nt!r.
N#iv align9)c!nt!r).
Np.U{h!a#!r&)us!r;ag!nt)'+N/p.
N/#iv.
N/bo#y.
N/html.
This would display something as follows:
User Agent Example
Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR
2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; HPNTDF; .NET4.0C;
InfoPath.2)
The header object returns single string values, whereas the headerValues object returns string arrays.
MAT SOFT
JAVA REFERENCE GUIDE
537
Day 52: JSP Standard Tag Library (JSTL)
The JavaServer Pages Standard Tag Library (JSTL) is a collection of useful JSP tags which encapsulates
core functionality common to many JSP applications.
JSTL has support for common, structural tasks such as iteration and conditionals, tags for
manipulating XML documents, internationalization tags, and SQL tags. It also provides a framework
for integrating existing custom tags with JSTL tags.
The JSTL tags can be classified, according to their functions, into following JSTL tag library groups that
can be used when creating a JSP page:
41 Core Tags
51 +ormatting tags
E1 SJ0 tags
F1 >M0 tags
V1 JST0 +nctions
Install JSTL Library:
If you are using Apache Tomcat container then follow the following two simple steps:
1. Download the binary distribution from Apache Standard Taglib and unpack the compressed
file.
2. To use the Standard Taglib from its Jakarta Taglibs distribution, simply copy the JAR files in the
distribution's 'lib' directory to your application's webapps\ROOT\WEB-INF\lib directory.
To use any of the libraries, you must include a <taglib> directive at the top of each JSP that uses the
library.
Core Tags:
MAT SOFT
JAVA REFERENCE GUIDE
538
The core group of tags are the most frequently used JSTL tags. Following is the syntax to include JSTL
Core library in your JSP:
NW\ taglib pr!fi:9)c)
uri9)http-//java.sun.com/jsp/jstl/cor!) W.
There are following Core JSTL Tags:
JSTL Core <c:out> Tag
The <c:out> tag displays the result of an expression, similar to the way <%= %> works with a
difference that <c:out> tag lets you use the simpler "." notation to access properties. For example, to
access customer.address.street just use tag is <c:out value="customer.address.street"/>.
The <c:out> tag can automatically escape XML tags so they aren't evaluated as actual tags.
Attribute:
The <c:out> tag has following attributes:
%ttri"te )escription 'e;ired )efa$t
value Information to output Yes None
default Fallback information to output No body
escapeXml True if the tag should escape special XML characters No true
Example:
NW\ taglib uri9)http-//java.sun.com/jsp/jstl/cor!) pr!fi:9)c) W.
Nhtml.
Nh!a#.
Ntitl!.Nc-out. Tag 3:ampl!N/titl!.
N/h!a#.
Nbo#y.
Nc-out valu!9)U{'Ntag. 2 ['+)/.
N/bo#y.
N/html.
This would produce following result:
Ntag. 2 [
MAT SOFT
JAVA REFERENCE GUIDE
539
JSTL Core <c:set> Tag
The <c:set> tag is JSTL-friendly version of the setProperty action. The tag is helpful because it
evaluates an expression and uses the results to set a value of a JavaBean or a java.util.Map object.
Attribute:
The <c:set> tag has following attributes:
%ttri"te )escription 'e;ired )efa$t
value Information to save No body
target Name of the variable whose property should be modified No None
property Property to modify No None
var Name of the variable to store information No None
scope Scope of variable to store information No Page
If target is specified, property must also be specified.
Example:
NW\ taglib uri9)http-//java.sun.com/jsp/jstl/cor!) pr!fi:9)c) W.
Nhtml.
Nh!a#.
Ntitl!.Nc-s!t. Tag 3:ampl!N/titl!.
N/h!a#.
Nbo#y.
Nc-s!t var9)salary) scop!9)s!ssion) valu!9)U{@EEE*@+)/.
Nc-out valu!9)U{salary+)/.
N/bo#y.
N/html.
This would produce following result:
FEEE
JSTL Core <c:remove> Tag
MAT SOFT
JAVA REFERENCE GUIDE
540
The <c:remove> tag removes a variable from either a specified scope or the first scope where the
variable is found (if no scope is specified). This action is not normally particularly helpful, but it can aid
in ensuring that a JSP cleans up any scoped resources it is responsible for.
Attribute:
The <c:remove> tag has following attributes:
%ttri"te )escription 'e;ired )efa$t
var Name of the variable to remove Yes None
scope Scope of the variable to remove No All scopes
Example:
NW\ taglib uri9)http-//java.sun.com/jsp/jstl/cor!) pr!fi:9)c) W.
Nhtml.
Nh!a#.
Ntitl!.Nc-r!mov!. Tag 3:ampl!N/titl!.
N/h!a#.
Nbo#y.
Nc-s!t var9)salary) scop!9)s!ssion) valu!9)U{@EEE*@+)/.
Np.L!for! 7!mov! Balu!- Nc-out valu!9)U{salary+)/.N/p.
Nc-r!mov! var9)salary)/.
Np.0ft!r 7!mov! Balu!- Nc-out valu!9)U{salary+)/.N/p.
N/bo#y.
N/html.
This would produce following result:
L!for! 7!mov! Balu!- FEEE
0ft!r 7!mov! Balu!-
JSTL Core <c:catch> Tag
The <c:catch> tag catches any Throwable that occurs in its body and optionally exposes it. Simply it is
used for error handling and to deal more gracefully with the problem.
Attribute:
The <c:catch> tag has following attributes:
%ttri"te )escription 'e;ired )efa$t
MAT SOFT
JAVA REFERENCE GUIDE
541
var The name of the variable to hold the java.lang.Throwable if
thrown by elements in the body.
No None
Example:
NW\ taglib uri9)http-//java.sun.com/jsp/jstl/cor!) pr!fi:9)c) W.
Nhtml.
Nh!a#.
Ntitl!.Nc-catch. Tag 3:ampl!N/titl!.
N/h!a#.
Nbo#y.
Nc-catch var 9)catch3:c!ption).
NW int : 9 H/E*W.
N/c-catch.
Nc-if t!st 9 )U{catch3:c!ption G9 null+).
Np.Th! !:c!ption is - U{catch3:c!ption+ Nbr /.
Th!r! is an !:c!ption- U{catch3:c!ption.m!ssag!+N/p.
N/c-if.
N/bo#y.
N/html.
This would produce following result:
Th! !:c!ption is - java.lang.0rithmatic3:c!ption- / by /!ro
Th!r! is an !:c!ption- / by /!ro
JSTL Core <c:if> Tag
The <c:if> tag evaluates an expression and displays its body content only if the expression evaluates
to true.
Attribute:
The <c:if> tag has following attributes:
%ttri"te )escription 'e;ired )efa$t
test Condition to evaluate Yes None
var Name of the variable to store the condition's result No None
scope Scope of the variable to store the condition's result No page
MAT SOFT
JAVA REFERENCE GUIDE
542
Example:
NW\ taglib uri9)http-//java.sun.com/jsp/jstl/cor!) pr!fi:9)c) W.
Nhtml.
Nh!a#.
Ntitl!.Nc-if. Tag 3:ampl!N/titl!.
N/h!a#.
Nbo#y.
Nc-s!t var9)salary) scop!9)s!ssion) valu!9)U{@EEE*@+)/.
Nc-if t!st9)U{salary . @EEE+).
Np.My salary is- Nc-out valu!9)U{salary+)/.Np.
N/c-if.
N/bo#y.
N/html.
This would produce following result:
My salary is- FEEE
JSTL Core <c:choose> Tag
JSTL Core <c:when> Tag
JSTL Core <c:otherwise> Tag
The <c:choose> works like a Java s3itch statement in that it lets you choose between a number of
alternatives. Where the s3itch statement has case statements, the <c:choose> tag has <c:when>
tags. A a switch statement has defa$t clause to specify a default action and similar way <c:choose>
has <c:otherwise> as default clause.
Attribute:
The <c:choose> tag does not have any attribute.
The <c:when> tag has one attributes which is listed below.
The <c:otherwise> tag does not have any attribute.
The <c:when> tag has following attributes:
%ttri"te )escription 'e;ired )efa$t
test Condition to evaluate Yes None
MAT SOFT
JAVA REFERENCE GUIDE
543
Example:
NW\ taglib uri9)http-//java.sun.com/jsp/jstl/cor!) pr!fi:9)c) W.
Nhtml.
Nh!a#.
Ntitl!.Nc-choos!. Tag 3:ampl!N/titl!.
N/h!a#.
Nbo#y.
Nc-s!t var9)salary) scop!9)s!ssion) valu!9)U{@EEE*@+)/.
Np.Aour salary is - Nc-out valu!9)U{salary+)/.N/p.
Nc-choos!.
Nc-wh!n t!st9)U{salary N9 E+).
%alary is v!ry low to surviv!.
N/c-wh!n.
Nc-wh!n t!st9)U{salary . CEEE+).
%alary is v!ry goo#.
N/c-wh!n.
Nc-oth!rwis!.
=o comm!nt sir...
N/c-oth!rwis!.
N/c-choos!.
N/bo#y.
N/html.
This would produce following result:
Aour salary is - FEEE
%alary is v!ry goo#.
JSTL Core <c:import> Tag
The <c:import> tag provides all of the functionality of the <include> action but also allows for
inclusion of absolute URLs.
For example, using the import tag allows for inclusion of content from a different Web site or an FTP
server.
Attribute:
The <c:import> tag has following attributes:
%ttri"te )escription 'e;ired )efa$t
url URL to retrieve and import into the page Yes None
context / followed by the name of a local web application No Current application
MAT SOFT
JAVA REFERENCE GUIDE
544
charEncoding Character set to use for imported data No ISO-8859-1
var Name of the variable to store imported text No Print to page
scope Scope of the variable used to store imported text No Page
varReader Name of an alternate variable to expose
java.io.Reader
No None
Example:
NW\ taglib uri9)http-//java.sun.com/jsp/jstl/cor!) pr!fi:9)c) W.
Nhtml.
Nh!a#.
Ntitl!.Nc-import. Tag 3:ampl!N/titl!.
N/h!a#.
Nbo#y.
Nc-import var9)#ata) url9)http-//www.mat;soft.com)/.
Nc-out valu!9)U{#ata+)/.
N/bo#y.
N/html.
Above example would fetch complete content from mat-soft.com/index.htm and would store in
variable data which will be printed eventually. Try it yourself.
JSTL Core <c:forEach> Tag
JSTL Core <c:forTokens> Tag
These tags exist as a good alternative to embedding a Java for< 3hi$e< or do&3hi$e loop via a
scriptlet. The <c:forEach> tag is the more commonly used tag because it iterates over a collection of
objects. The <c:forTokens> tag is used to break a string into tokens and iterate through each of the
tokens.
Attribute:
The <c:forEach> tag has following attributes:
MAT SOFT
JAVA REFERENCE GUIDE
545
%ttri"te )escription 'e;ired )efa$t
items Information to loop over No None
begin Element to start with (0 = first item, 1 = second item, ...) No 0
end Element to end with (0 = first item, 1 = second item, ...) No Last element
step Process every step items No 1
var Name of the variable to expose the current item No None
varStatus Name of the variable to expose the loop status No None
The <c:forTokens> tag has similar attributes as <c:forEach> except one additional
attributede$ims which specifies sharacters to use as delimiters.
%ttri"te )escription 'e;ired )efa$t
delims Characters to use as delimiters Yes None
Example for <c:forEach>:
NW\ taglib uri9)http-//java.sun.com/jsp/jstl/cor!) pr!fi:9)c) W.
Nhtml.
Nh!a#.
Ntitl!.Nc-for3ach. Tag 3:ampl!N/titl!.
N/h!a#.
Nbo#y.
Nc-for3ach var9)i) b!gin9)C) !n#9)H).
6t!m Nc-out valu!9)U{i+)/.Np.
N/c-for3ach.
N/bo#y.
N/html.
This would produce following result:
6t!m C
6t!m @
6t!m D
6t!m F
6t!m H
MAT SOFT
JAVA REFERENCE GUIDE
546
Example for <c:forTokens>:
NW\ taglib uri9)http-//java.sun.com/jsp/jstl/cor!) pr!fi:9)c) W.
Nhtml.
Nh!a#.
Ntitl!.Nc-forTo<!ns. Tag 3:ampl!N/titl!.
N/h!a#.
Nbo#y.
Nc-forTo<!ns it!ms9)Vara2nuha2roshy) #!lims9)2) var9)nam!).
Nc-out valu!9)U{nam!+)/.Np.
N/c-forTo<!ns.
N/bo#y.
N/html.
This would produce following result:
Vara
nuha
roshy
JSTL Core <c:param> Tag
The <c:param> tag allows proper URL request parameter to be specified with URL and it does any
necessary URL encoding required.
Within a <c:param> tag, the name attribute indicates the parameter name, and the value attribute
indicates the parameter value:
Attribute:
The <c:param> tag has following attributes:
%ttri"te )escription 'e;ired )efa$t
name Name of the request parameter to set in the URL Yes None
value Value of the request parameter to set in the URL No Body
Example:
If you need to pass parameters to a <c:import> tag, use the <c:url> tag to create the URL first as
shown below:
MAT SOFT
JAVA REFERENCE GUIDE
547
Nc-url valu!9)/in#!:.jsp) var9)my571).
Nc-param nam!9)trac<ing6#) valu!9)C@DF)/.
Nc-param nam!9)r!portTyp!) valu!9)summary)/.
N/c-url.
Nc-import url9)U{my571+)/.
Above request would pass URL as below - Try it yourself.
)/in#!:.jspStrac<ing6#9C@DF*r!portTyp!9summary)
JSTL Core <c:redirect> Tag
The <c:redirect> tag redirects the browser to an alternate URL by providing automatically URL
rewriting, it supports context-relative URLs, and it supports the <c:param> tag.
Attribute:
The <c:redirect> tag has following attributes:
%ttri"te )escription 'e;ired )efa$t
url URL to redirect the user's browser to Yes None
context / followed by the name of a local web application No Current application
Example:
If you need to pass parameters to a <c:import> tag, use the <c:url> tag to create the URL first as
shown below:
NW\ taglib uri9)http-//java.sun.com/jsp/jstl/cor!) pr!fi:9)c) W.
Nhtml.
Nh!a#.
Ntitl!.Nc-r!#ir!ct. Tag 3:ampl!N/titl!.
N/h!a#.
Nbo#y.
Nc-r!#ir!ct url9)http-//www.photofuntoos.com)/.
N/bo#y.
N/html.
Above example would redirect request to http://www.photofuntoos.com - Try it yourself.
MAT SOFT
JAVA REFERENCE GUIDE
548
JSTL Core <c:url> Tag
The <c:url> tag formats a URL into a string and stores it into a variable. This tag automatically
performs URL rewriting when necessary. The var attribute specifies the variable that will contain the
formatted URL. The JSTL url tag is just an alternative method of writing the call to the
response.encodeURL() method. The only real advantage the url tag provides is proper URL encoding,
including any parameters specified by children param tag.
Attribute:
The <c:url> tag has following attributes:
%ttri"te )escription 'e;ired )efa$t
value Base URL Yes None
context / followed by the name of a local web application No Current application
var Name of the variable to expose the processed URL No Print to page
scope Scope of the variable to expose the processed URL No Page
Example:
NW\ taglib uri9)http-//java.sun.com/jsp/jstl/cor!) pr!fi:9)c) W.
Nhtml.
Nh!a#.
Ntitl!.Nc-url. Tag 3:ampl!N/titl!.
N/h!a#.
Nbo#y.
Na hr!f9)Nc-url valu!9)/jsp/in#!:.htm)/.).T3%TN/a.
N/bo#y.
N/html.
This would produce following result:
T3%T

MAT SOFT
JAVA REFERENCE GUIDE
549
Day 53 !S"L S#L "$%S:
The JSTL SQL tag library provides tags for interacting with relational databases (RDBMSs) such as
Oracle, mySQL, or Microsoft SQL Server.
Following is the syntax to include JSTL SQL library in your JSP:
NW\ taglib pr!fi:9)sPl)
uri9)http-//java.sun.com/jsp/jstl/sPl) W.
Following is the list of SQL JSTL Tags:
JSTL SQL <sql:setDataSource> Tag
The <sql:setDataSource> tag sets the data source configuration variable or saves the data-source
information in a scoped variable that can be used as input to the other JSTL database actions.
Attribute:
The <sql:setDataSource> tag has following attributes:
%ttri"te )escription 'e;ired )efa$t
driver Name of the JDBC driver class to be registered No None
url JDBC URL for the database connection No None
user Database username No None
password Database password No None
password Database password No None
MAT SOFT
JAVA REFERENCE GUIDE
550
dataSource Database prepared in advance No None
var Name of the variable to represent the database No Set default
scope Scope of the variable to represent the database No Page
Example:
Consider the following information about your MySQL database setup:
We are using JDBC MySQL driver.
We are going to connect to TEST database on local machine.
We would use user_id and mypassword to access TEST database.
All the above parameters would vary based on your MySQL or any other database setup. Keeping
above parameters in mind, following is a simple example to use setDataSource tag:
NW\ taglib uri9)http-//java.sun.com/jsp/jstl/cor!) pr!fi:9)c) W.
NW\ taglib uri9)http-//java.sun.com/jsp/jstl/sPl) pr!fi:9)sPl)W.
Nhtml.
Nh!a#.
Ntitl!.J%T1 sPl-s!t4ata%ourc! TagN/titl!.
N/h!a#.
Nbo#y.

NsPl-s!t4ata%ourc! var9)snapshot) #riv!r9)com.mysPl.j#bc.4riv!r)
url9)j#bc-mysPl-//localhost/T3%T)
us!r9)us!rTi#) passwor#9)mypasswor#)/.
NsPl-Pu!ry #ata%ourc!9)U{snapshot+) sPl9)...) var9)r!sult) /.

N/bo#y.
N/html.
You will start using <sql:setDataSource> in subsequent SQL tags.
JSTL SQL <sql:query> Tag
The <sql:query> tag executes an SQL SELECT statement and saves the result in a scoped variable.
Attribute:
The <sql:query> tag has following attributes:
MAT SOFT
JAVA REFERENCE GUIDE
551
%ttri"te )escription 'e;ired )efa$t
sql SQL command to execute (should return a ResultSet) No Body
dataSource Database connection to use (overrides the default) No Default
database
maxRows Maximum number of results to store in the variable No Unlimited
startRow Number of the row in the result at which to start
recording
No 0
var Name of the variable to represent the database No Set default
scope Scope of variable to expose the result from the database No Page
Example:
To start with basic concept, let us create a simple table 7mp$oyees table in TEST database and create
few records in that table as follows:
Step 1:
Open a Command Prompt and change to the installation directory as follows:
,-O.
,-O.c# Program Fil!sOMy%X1Obin
,-OProgram Fil!sOMy%X1Obin.
Step 2:
Login to database as follows
,-OProgram Fil!sOMy%X1Obin.mysPl ;u root ;p
3nt!r passwor#- ********
mysPl.
Step 3:
Create the table 7mp$oyee in T7ST database as follows:
mysPl. us! T3%T*
mysPl. cr!at! tabl! 3mploy!!s
MAT SOFT
JAVA REFERENCE GUIDE
552
$
i# int not null2
ag! int not null2
first varchar $@HH(2
last varchar $@HH(
(*
Xu!ry ?Y2 E rows aff!ct!# $E.EJ s!c(
mysPl.
Create Data Records
Finally you create few records in Employee table as follows:
mysPl. 6=%37T 6=T? 3mploy!!s B0153% $CEE2 CJ2 'Vara'2 '0li'(*
Xu!ry ?Y2 C row aff!ct!# $E.EH s!c(

mysPl. 6=%37T 6=T? 3mploy!!s B0153% $CEC2 @H2 'Mahna/'2 'Fatma'(*
Xu!ry ?Y2 C row aff!ct!# $E.EE s!c(

mysPl. 6=%37T 6=T? 3mploy!!s B0153% $CE@2 DE2 'Vai#'2 'Yhan'(*
Xu!ry ?Y2 C row aff!ct!# $E.EE s!c(

mysPl. 6=%37T 6=T? 3mploy!!s B0153% $CED2 @J2 '%umit'2 'Mittal'(*
Xu!ry ?Y2 C row aff!ct!# $E.EE s!c(

mysPl.
Now let us write a JSP which will make use of <sql:query> to execute a SQL SELECT statement as
follows:
NW\ pag! import9)java.io.*2java.util.*2java.sPl.*)W.
NW\ pag! import9)java:.s!rvl!t.http.*2java:.s!rvl!t.*) W.
NW\ taglib uri9)http-//java.sun.com/jsp/jstl/cor!) pr!fi:9)c)W.
NW\ taglib uri9)http-//java.sun.com/jsp/jstl/sPl) pr!fi:9)sPl)W.
Nhtml.
Nh!a#.
Ntitl!.J%T1 sPl-Pu!ry TagN/titl!.
N/h!a#.
Nbo#y.

NsPl-s!t4ata%ourc! var9)snapshot) #riv!r9)com.mysPl.j#bc.4riv!r)
url9)j#bc-mysPl-//localhost/T3%T)
us!r9)root) passwor#9)passC@D)/.
NsPl-Pu!ry #ata%ourc!9)U{snapshot+) var9)r!sult).
%313,T * from 3mploy!!s*
N/sPl-Pu!ry.

Ntabl! bor#!r9)C) wi#th9)CEEW).
Ntr.
Nth.3mp 64N/th.
MAT SOFT
JAVA REFERENCE GUIDE
553
Nth.First =am!N/th.
Nth.1ast =am!N/th.
Nth.0g!N/th.
N/tr.
Nc-for3ach var9)row) it!ms9)U{r!sult.rows+).
Ntr.
Nt#.Nc-out valu!9)U{row.i#+)/.N/t#.
Nt#.Nc-out valu!9)U{row.first+)/.N/t#.
Nt#.Nc-out valu!9)U{row.last+)/.N/t#.
Nt#.Nc-out valu!9)U{row.ag!+)/.N/t#.
N/tr.
N/c-for3ach.
N/tabl!.
N/bo#y.
N/html.
Now try to access above JSP, which should display the following result:
7mp I) +irst Name 0ast Name %ge
100 Zara Ali 18
101 Mahnaz Fatma 25
102 Zaid Khan 30
103 Sumit Mittal 28
JSTL SQL <sql:update> Tag
The <sql:update> tag executes an SQL statement that does not return data, for example SQL INSERT,
UPDATE, or DELETE statements.
Attribute:
The <sql:update> tag has following attributes:
%ttri"te )escription 'e;ired )efa$t
sql SQL command to execute (should not return a
ResultSet)
No Body
dataSource Database connection to use (overrides the default) No Default database
MAT SOFT
JAVA REFERENCE GUIDE
554
var Name of the variable to store the count of affected rows No None
scope Scope of the variable to store the count of affected rows No Page
Example:
To start with basic concept, let us create a simple table 7mp$oyees table in TEST database and create
few records in that table as follows:
Step 1:
Open a Command Prompt and change to the installation directory as follows:
,-O.
,-O.c# Program Fil!sOMy%X1Obin
,-OProgram Fil!sOMy%X1Obin.
Step 2:
Login to database as follows
,-OProgram Fil!sOMy%X1Obin.mysPl ;u root ;p
3nt!r passwor#- ********
mysPl.
Step 3:
Create the table 7mp$oyee in T7ST database as follows:
mysPl. us! T3%T*
mysPl. cr!at! tabl! 3mploy!!s
$
i# int not null2
ag! int not null2
first varchar $@HH(2
last varchar $@HH(
(*
Xu!ry ?Y2 E rows aff!ct!# $E.EJ s!c(
mysPl.
Create Data Records
Finally you create few records in Employee table as follows:
MAT SOFT
JAVA REFERENCE GUIDE
555
mysPl. 6=%37T 6=T? 3mploy!!s B0153% $CEE2 CJ2 'Vara'2 '0li'(*
Xu!ry ?Y2 C row aff!ct!# $E.EH s!c(

mysPl. 6=%37T 6=T? 3mploy!!s B0153% $CEC2 @H2 'Mahna/'2 'Fatma'(*
Xu!ry ?Y2 C row aff!ct!# $E.EE s!c(

mysPl. 6=%37T 6=T? 3mploy!!s B0153% $CE@2 DE2 'Vai#'2 'Yhan'(*
Xu!ry ?Y2 C row aff!ct!# $E.EE s!c(

mysPl. 6=%37T 6=T? 3mploy!!s B0153% $CED2 @J2 '%umit'2 'Mittal'(*
Xu!ry ?Y2 C row aff!ct!# $E.EE s!c(

mysPl.
Now let us write a JSP which will make use of <sql:update> to execute a SQL INSERT statement to
create one record in the table as follows:
NW\ pag! import9)java.io.*2java.util.*2java.sPl.*)W.
NW\ pag! import9)java:.s!rvl!t.http.*2java:.s!rvl!t.*) W.
NW\ taglib uri9)http-//java.sun.com/jsp/jstl/cor!) pr!fi:9)c)W.
NW\ taglib uri9)http-//java.sun.com/jsp/jstl/sPl) pr!fi:9)sPl)W.
Nhtml.
Nh!a#.
Ntitl!.J%T1 sPl-up#at! TagN/titl!.
N/h!a#.
Nbo#y.

NsPl-s!t4ata%ourc! var9)snapshot) #riv!r9)com.mysPl.j#bc.4riv!r)
url9)j#bc-mysPl-//localhost/T3%T)
us!r9)root) passwor#9)passC@D)/.
NsPl-up#at! #ata%ourc!9)U{snapshot+) var9)count).
6=%37T 6=T? 3mploy!!s B0153% $CEF2 @2 '=uha'2 '0li'(*
N/sPl-up#at!.
NsPl-Pu!ry #ata%ourc!9)U{snapshot+) var9)r!sult).
%313,T * from 3mploy!!s*
N/sPl-Pu!ry.

Ntabl! bor#!r9)C) wi#th9)CEEW).
Ntr.
Nth.3mp 64N/th.
Nth.First =am!N/th.
Nth.1ast =am!N/th.
Nth.0g!N/th.
N/tr.
Nc-for3ach var9)row) it!ms9)U{r!sult.rows+).
Ntr.
Nt#.Nc-out valu!9)U{row.i#+)/.N/t#.
Nt#.Nc-out valu!9)U{row.first+)/.N/t#.
Nt#.Nc-out valu!9)U{row.last+)/.N/t#.
Nt#.Nc-out valu!9)U{row.ag!+)/.N/t#.
N/tr.
MAT SOFT
JAVA REFERENCE GUIDE
556
N/c-for3ach.
N/tabl!.
N/bo#y.
N/html.
Now try to access above JSP, which should display the following result:
7mp I) +irst Name 0ast Name %ge
100 Zara Ali 18
101 Mahnaz Fatma 25
102 Zaid Khan 30
103 Sumit Mittal 28
104 Nula Ali 2
Similar way, you can try SQL UPDATE and DELETE statements on the same table.
JSTL SQL <sql:param> Tag
The <sql:param> tag used as a nested action for <sql:query> and <sql:update> to supply a value for
a value placeholder. If a null value is provided, the value is set to SQL NULL for the placeholder.
Attribute:
The <sql:param> tag has following attributes:
%ttri"te )escription 'e;ired )efa$t
value Value of the parameter to set No Body
Example:
To start with basic concept, let us create a simple table 7mp$oyees table in TEST database and create
few records in that table as follows:
MAT SOFT
JAVA REFERENCE GUIDE
557
Step 1:
Open a Command Prompt and change to the installation directory as follows:
,-O.
,-O.c# Program Fil!sOMy%X1Obin
,-OProgram Fil!sOMy%X1Obin.
Step 2:
Login to database as follows
,-OProgram Fil!sOMy%X1Obin.mysPl ;u root ;p
3nt!r passwor#- ********
mysPl.
Step 3:
Create the table 7mp$oyee in T7ST database as follows:
mysPl. us! T3%T*
mysPl. cr!at! tabl! 3mploy!!s
$
i# int not null2
ag! int not null2
first varchar $@HH(2
last varchar $@HH(
(*
Xu!ry ?Y2 E rows aff!ct!# $E.EJ s!c(
mysPl.
Create Data Records
Finally you create few records in Employee table as follows:
mysPl. 6=%37T 6=T? 3mploy!!s B0153% $CEE2 CJ2 'Vara'2 '0li'(*
Xu!ry ?Y2 C row aff!ct!# $E.EH s!c(

mysPl. 6=%37T 6=T? 3mploy!!s B0153% $CEC2 @H2 'Mahna/'2 'Fatma'(*
Xu!ry ?Y2 C row aff!ct!# $E.EE s!c(

mysPl. 6=%37T 6=T? 3mploy!!s B0153% $CE@2 DE2 'Vai#'2 'Yhan'(*
Xu!ry ?Y2 C row aff!ct!# $E.EE s!c(

mysPl. 6=%37T 6=T? 3mploy!!s B0153% $CED2 @J2 '%umit'2 'Mittal'(*
Xu!ry ?Y2 C row aff!ct!# $E.EE s!c(

mysPl.
MAT SOFT
JAVA REFERENCE GUIDE
558
Now let us write a JSP which will make use of <sql:update> to execute a SQL DELETE statement to
delete one record with id = 103 from the table as follows:
NW\ pag! import9)java.io.*2java.util.*2java.sPl.*)W.
NW\ pag! import9)java:.s!rvl!t.http.*2java:.s!rvl!t.*) W.
NW\ taglib uri9)http-//java.sun.com/jsp/jstl/cor!) pr!fi:9)c)W.
NW\ taglib uri9)http-//java.sun.com/jsp/jstl/sPl) pr!fi:9)sPl)W.
Nhtml.
Nh!a#.
Ntitl!.J%T1 sPl-param TagN/titl!.
N/h!a#.
Nbo#y.

NsPl-s!t4ata%ourc! var9)snapshot) #riv!r9)com.mysPl.j#bc.4riv!r)
url9)j#bc-mysPl-//localhost/T3%T)
us!r9)root) passwor#9)passC@D)/.
Nc-s!t var9)!mp6#) valu!9)CED)/.
NsPl-up#at! #ata%ourc!9)U{snapshot+) var9)count).
4313T3 F7?M 3mploy!!s "373 6# 9 S
NsPl-param valu!9)U{!mp6#+) /.
N/sPl-up#at!.
NsPl-Pu!ry #ata%ourc!9)U{snapshot+) var9)r!sult).
%313,T * from 3mploy!!s*
N/sPl-Pu!ry.

Ntabl! bor#!r9)C) wi#th9)CEEW).
Ntr.
Nth.3mp 64N/th.
Nth.First =am!N/th.
Nth.1ast =am!N/th.
Nth.0g!N/th.
N/tr.
Nc-for3ach var9)row) it!ms9)U{r!sult.rows+).
Ntr.
Nt#.Nc-out valu!9)U{row.i#+)/.N/t#.
Nt#.Nc-out valu!9)U{row.first+)/.N/t#.
Nt#.Nc-out valu!9)U{row.last+)/.N/t#.
Nt#.Nc-out valu!9)U{row.ag!+)/.N/t#.
N/tr.
N/c-for3ach.
N/tabl!.
N/bo#y.
N/html.
Now try to access above JSP, which should display the following result:
7mp I) +irst Name 0ast Name %ge
MAT SOFT
JAVA REFERENCE GUIDE
559
100 Zara Ali 18
101 Mahnaz Fatma 25
102 Zaid Khan 30
You can try <sql:param> with SQL UPDATE and SELECT statements as well in the same way as I have
used it with DELETE statement.
JSTL SQL <sql:dateParam> Tag
The <sql:dateParam> tag is used as a nested action for <sql:query> and <sql:update> supply a date
and time value for a value placeholder. If a null value is provided, the value is set to SQL NULL for the
placeholder.
Attribute:
The <sql:dateParam> tag has following attributes:
%ttri"te )escription 'e;ired )efa$t
value Value of the date parameter to set (java.util.Date) No Body
type DATE (date only), TIME (time only), or TIMESTAMP (date and
time)
No TIMESTAMP
Example:
To start with basic concept, let us create a simple table Stdents table in TEST database and create
few records in that table as follows:
Step 1:
Open a Command Prompt and change to the installation directory as follows:
,-O.
,-O.c# Program Fil!sOMy%X1Obin
,-OProgram Fil!sOMy%X1Obin.
MAT SOFT
JAVA REFERENCE GUIDE
560
Step 2:
Login to database as follows
,-OProgram Fil!sOMy%X1Obin.mysPl ;u root ;p
3nt!r passwor#- ********
mysPl.
Step 3:
Create the table 7mp$oyee in T7ST database as follows:
mysPl. us! T3%T*
mysPl. cr!at! tabl! %tu#!nts
$
i# int not null2
first varchar $@HH(2
last varchar $@HH(2
#ob #at!
(*
Xu!ry ?Y2 E rows aff!ct!# $E.EJ s!c(
mysPl.
Create Data Records
Finally you create few records in Employee table as follows:
mysPl. 6=%37T 6=T? %tu#!nts
B0153% $CEE2 'Vara'2 '0li'2 '@EE@/EH/CM'(*
Xu!ry ?Y2 C row aff!ct!# $E.EH s!c(

mysPl. 6=%37T 6=T? %tu#!nts
B0153% $CEC2 'Mahna/'2 'Fatma'2 'CKIJ/CC/@J'(*
Xu!ry ?Y2 C row aff!ct!# $E.EE s!c(

mysPl. 6=%37T 6=T? %tu#!nts
B0153% $CE@2 'Vai#'2 'Yhan'2 'CKJE/CE/CE'(*
Xu!ry ?Y2 C row aff!ct!# $E.EE s!c(

mysPl. 6=%37T 6=T? %tu#!nts
B0153% $CED2 '%umit'2 'Mittal'2 'CKIC/EH/EJ'(*
Xu!ry ?Y2 C row aff!ct!# $E.EE s!c(

mysPl.
Now let us write a JSP which will make use of <sql:update> along with <sql:param> and
<sql:dataParam> to execute a SQL UPDATE statement to update date of birth for Zara:
NW\ pag! import9)java.io.*2java.util.*2java.sPl.*)W.
MAT SOFT
JAVA REFERENCE GUIDE
561
NW\ pag! import9)java:.s!rvl!t.http.*2java:.s!rvl!t.*) W.
NW\ pag! import9)java.util.4at!2java.t!:t.*) W.
NW\ taglib uri9)http-//java.sun.com/jsp/jstl/cor!) pr!fi:9)c)W.
NW\ taglib uri9)http-//java.sun.com/jsp/jstl/sPl) pr!fi:9)sPl)W.

Nhtml.
Nh!a#.
Ntitl!.J%T1 sPl-#ataParam TagN/titl!.
N/h!a#.
Nbo#y.

NsPl-s!t4ata%ourc! var9)snapshot) #riv!r9)com.mysPl.j#bc.4riv!r)
url9)j#bc-mysPl-//localhost/T3%T)
us!r9)root) passwor#9)passC@D)/.
NW
4at! 4oL 9 n!w 4at!$)@EEC/C@/CM)(*
int stu#!nt6# 9 CEE*
W.

NsPl-up#at! #ata%ourc!9)U{snapshot+) var9)count).
5P40T3 %tu#!nts %3T #ob 9 S "373 6# 9 S
NsPl-#at!Param valu!9)NW94oLW.) typ!9)40T3) /.
NsPl-param valu!9)NW9stu#!nt6#W.) /.
N/sPl-up#at!.

NsPl-Pu!ry #ata%ourc!9)U{snapshot+) var9)r!sult).
%313,T * from %tu#!nts*
N/sPl-Pu!ry.

Ntabl! bor#!r9)C) wi#th9)CEEW).
Ntr.
Nth.3mp 64N/th.
Nth.First =am!N/th.
Nth.1ast =am!N/th.
Nth.4oLN/th.
N/tr.
Nc-for3ach var9)row) it!ms9)U{r!sult.rows+).
Ntr.
Nt#.Nc-out valu!9)U{row.i#+)/.N/t#.
Nt#.Nc-out valu!9)U{row.first+)/.N/t#.
Nt#.Nc-out valu!9)U{row.last+)/.N/t#.
Nt#.Nc-out valu!9)U{row.#ob+)/.N/t#.
N/tr.
N/c-for3ach.
N/tabl!.

N/bo#y.
N/html.
Now try to access above JSP, which should display the following result after updating dob from
2002/05/16 to 2001/12/16 for the record with ID=100:
7mp I) +irst Name 0ast Name )oB
MAT SOFT
JAVA REFERENCE GUIDE
562
100 Zara Ali 2001-12-16
101 Mahnaz Fatma 1978-11-28
102 Zaid Khan 1980-10-10
103 Sumit Mittal 1971-05-08
JSTL SQL <sql:transaction> Tag
The <sql:transaction> tag is used to group <sql:query> and <sql:update> into transactions. You can
put as many <sql:query> and <sql:update> as statements inside <sql:transaction> to make them a
single transaction.
It ensures that the database modifications performed by the nested actions are either committed or
rolled back if an exception is thrown by any nested action.
Attribute:
The <sql:transaction> tag has following attributes:
%ttri"te )escription 'e;ired )efa$t
dataSource Database connection to use (overrides the default) No Default
database
isolation Transaction isolation (READ_COMMITTED,
READ_UNCOMMITTED, REPEATABLE_READ, or
SERIALIZABLE)
No Databases
default
Example:
To start with basic concept, let us create a simple table Stdents table in TEST database and create
few records in that table as follows:
Step 1:
Open a Command Prompt and change to the installation directory as follows:
,-O.
MAT SOFT
JAVA REFERENCE GUIDE
563
,-O.c# Program Fil!sOMy%X1Obin
,-OProgram Fil!sOMy%X1Obin.
Step 2:
Login to database as follows
,-OProgram Fil!sOMy%X1Obin.mysPl ;u root ;p
3nt!r passwor#- ********
mysPl.
Step 3:
Create the table 7mp$oyee in T7ST database as follows:
mysPl. us! T3%T*
mysPl. cr!at! tabl! %tu#!nts
$
i# int not null2
first varchar $@HH(2
last varchar $@HH(2
#ob #at!
(*
Xu!ry ?Y2 E rows aff!ct!# $E.EJ s!c(
mysPl.
Create Data Records
Finally you create few records in Employee table as follows:
mysPl. 6=%37T 6=T? %tu#!nts
B0153% $CEE2 'Vara'2 '0li'2 '@EE@/EH/CM'(*
Xu!ry ?Y2 C row aff!ct!# $E.EH s!c(

mysPl. 6=%37T 6=T? %tu#!nts
B0153% $CEC2 'Mahna/'2 'Fatma'2 'CKIJ/CC/@J'(*
Xu!ry ?Y2 C row aff!ct!# $E.EE s!c(

mysPl. 6=%37T 6=T? %tu#!nts
B0153% $CE@2 'Vai#'2 'Yhan'2 'CKJE/CE/CE'(*
Xu!ry ?Y2 C row aff!ct!# $E.EE s!c(

mysPl. 6=%37T 6=T? %tu#!nts
B0153% $CED2 '%umit'2 'Mittal'2 'CKIC/EH/EJ'(*
Xu!ry ?Y2 C row aff!ct!# $E.EE s!c(

mysPl.
MAT SOFT
JAVA REFERENCE GUIDE
564
Now let us write a JSP which will make use of <sql:update> along with <sql:transaction> to execute a
SQL UPDATE statement. Here code inside <sql:transaction> either would be exeucted completely or
not at all:
NW\ pag! import9)java.io.*2java.util.*2java.sPl.*)W.
NW\ pag! import9)java:.s!rvl!t.http.*2java:.s!rvl!t.*)W.
NW\ pag! import9)java.util.4at!2java.t!:t.*) W.
NW\ taglib uri9)http-//java.sun.com/jsp/jstl/cor!) pr!fi:9)c)W.
NW\ taglib uri9)http-//java.sun.com/jsp/jstl/sPl) pr!fi:9)sPl)W.

Nhtml.
Nh!a#.
Ntitl!.J%T1 sPl-transaction TagN/titl!.
N/h!a#.
Nbo#y.

NsPl-s!t4ata%ourc! var9)snapshot) #riv!r9)com.mysPl.j#bc.4riv!r)
url9)j#bc-mysPl-//localhost/T3%T)
us!r9)root) passwor#9)cohon#ob)/.
NW
4at! 4oL 9 n!w 4at!$)@EEC/C@/CM)(*
int stu#!nt6# 9 CEE*
W.
NsPl-transaction #ata%ourc!9)U{snapshot+).
NsPl-up#at! var9)count).
5P40T3 %tu#!nts %3T last 9 '0li' "373 6# 9 CE@
N/sPl-up#at!.
NsPl-up#at! var9)count).
5P40T3 %tu#!nts %3T last 9 '%hah' "373 6# 9 CED
N/sPl-up#at!.
NsPl-up#at! var9)count).
6=%37T 6=T? %tu#!nts
B0153% $CEF2'=uha'2 '0li'2 '@ECE/EH/@M'(*
N/sPl-up#at!.
N/sPl-transaction.
NsPl-Pu!ry #ata%ourc!9)U{snapshot+) var9)r!sult).
%313,T * from %tu#!nts*
N/sPl-Pu!ry.

Ntabl! bor#!r9)C) wi#th9)CEEW).
Ntr.
Nth.3mp 64N/th.
Nth.First =am!N/th.
Nth.1ast =am!N/th.
Nth.4oLN/th.
N/tr.
Nc-for3ach var9)row) it!ms9)U{r!sult.rows+).
Ntr.
Nt#.Nc-out valu!9)U{row.i#+)/.N/t#.
Nt#.Nc-out valu!9)U{row.first+)/.N/t#.
Nt#.Nc-out valu!9)U{row.last+)/.N/t#.
MAT SOFT
JAVA REFERENCE GUIDE
565
Nt#.Nc-out valu!9)U{row.#ob+)/.N/t#.
N/tr.
N/c-for3ach.
N/tabl!.

N/bo#y.
N/html.
Now try to access above JSP, which should display the following result:
7mp I) +irst Name 0ast Name )oB
100 Zara Ali 2001-12-16
101 Mahnaz Fatma 1978-11-28
102 Zaid Ali 1980-10-10
103 Sumit Shah 1971-05-08
104 Nuha Ali 2010-05-26
MAT SOFT
JAVA REFERENCE GUIDE
566
Day 54: JSTL Formatting tags:
The JSTL formatting tags are used to format and display text, the date, the time, and numbers for
internationalized Web sites. Following is the syntax to include Formatting library in your JSP:
NW\ taglib pr!fi:9)fmt)
uri9)http-//java.sun.com/jsp/jstl/fmt) W.
Following is the list of Formatting JSTL Tags:
JSTL Core <fmt:formatNumber> Tag
The <fmt:formatNumber> tag is used to format numbers, percentages, and currencies.
Attribute:
The <fmt:formatNumber> tag has following attributes:
%ttri"te )escription 'e;ired )efa$t
value Numeric value to display Yes None
type NUMBER, CURRENCY, or PERCENT No Number
pattern Specify a custom formatting pattern for the
output.
No None
currencyCode Currency code (for type="currency") No From the default
locale
currencySymbol Currency symbol (for type="currency") No From the default
MAT SOFT
JAVA REFERENCE GUIDE
567
locale
groupingUsed Whether to group numbers (TRUE or FALSE) No true
maxIntegerDigits Maximum number of integer digits to print No None
minIntegerDigits Minimum number of integer digits to print No None
maxFractionDigits Maximum number of fractional digits to print No None
minFractionDigits Minimum number of fractional digits to print No None
var Name of the variable to store the formatted
number
No Print to page
scope Scope of the variable to store the formatted
number
No page
If the type attribute is percent or number, then you can use several number-formatting
attributes. The maxIntegerDigits and minIntegerDigits attributes allow you to specify the size
of the nonfractional portion of the number. If the actual number exceeds maxIntegerDigits,
then the number is truncated.
Attributes are also provided to allow you to determine how many decimal places should be
used. The minFractionalDigits and maxFractionalDigits attributes allow you to specify the
number of decimal places. If the number exceeds the maximum number of fractional digits,
the number will be rounded.
Grouping can be used to insert commas between thousands groups. Grouping is specified by
setting the groupingIsUsed attribute to either true or false. When using grouping with
minIntegerDigits, you must be careful to get your intended result.
You may select to use the pattern attribute. This attribute lets you include special characters
that specify how you would like your number encoded. Following table shows these codes.
Sym"o$ )escription
0 Represents a digit.
E Represents in exponential form.
# Represents a digit; displays 0 as absent.
. Serves as a placeholder for a decimal separator.
MAT SOFT
JAVA REFERENCE GUIDE
568
, Serves as a placeholder for a grouping separator.
; Separates formats.
- Used as the default negative prefix.
% Multiplies by 100 and displays as a percentage.
? Multiplies by 1000 and displays as per mille.
Represents the currency sign; replaced by actional currency symbol.
X Indicates that any other characters can be used in the prefix or suffix.
' Used to quote special characters in a prefix or suffix.
Example:
NW\ taglib pr!fi:9)c) uri9)http-//java.sun.com/jsp/jstl/cor!) W.
NW\ taglib pr!fi:9)fmt) uri9)http-//java.sun.com/jsp/jstl/fmt) W.
Nhtml.
Nh!a#.
Ntitl!.J%T1 fmt-format=umb!r TagN/titl!.
N/h!a#.
Nbo#y.
NhD.=umb!r Format-N/hD.
Nc-s!t var9)balanc!) valu!9)C@EEEE.@DEK) /.
Np.Formatt!# =umb!r $C(- Nfmt-format=umb!r valu!9)U{balanc!+)
typ!9)curr!ncy)/.N/p.
Np.Formatt!# =umb!r $@(- Nfmt-format=umb!r typ!9)numb!r)
ma:6nt!g!r4igits9)D) valu!9)U{balanc!+) /.N/p.
Np.Formatt!# =umb!r $D(- Nfmt-format=umb!r typ!9)numb!r)
ma:Fraction4igits9)D) valu!9)U{balanc!+) /.N/p.
Np.Formatt!# =umb!r $F(- Nfmt-format=umb!r typ!9)numb!r)
grouping5s!#9)fals!) valu!9)U{balanc!+) /.N/p.
Np.Formatt!# =umb!r $H(- Nfmt-format=umb!r typ!9)p!rc!nt)
ma:6nt!g!r4igits9)D) valu!9)U{balanc!+) /.N/p.
Np.Formatt!# =umb!r $M(- Nfmt-format=umb!r typ!9)p!rc!nt)
minFraction4igits9)CE) valu!9)U{balanc!+) /.N/p.
Np.Formatt!# =umb!r $I(- Nfmt-format=umb!r typ!9)p!rc!nt)
ma:6nt!g!r4igits9)D) valu!9)U{balanc!+) /.N/p.
Np.Formatt!# =umb!r $J(- Nfmt-format=umb!r typ!9)numb!r)
patt!rn9)^^^.^^^3E) valu!9)U{balanc!+) /.N/p.
Np.,urr!ncy in 5%0 -
Nfmt-s!t1ocal! valu!9)!nT5%)/.
MAT SOFT
JAVA REFERENCE GUIDE
569
Nfmt-format=umb!r valu!9)U{balanc!+) typ!9)curr!ncy)/.N/p.
N/bo#y.
N/html.
This would produce following result:
Nm"er +ormat:
Formatted Number (1): 120,000.23
Formatted Number (2): 000.231
Formatted Number (3): 120,000.231
Formatted Number (4): 120000.231
Formatted Number (5): 023%
Formatted Number (6): 12,000,023.0900000000%
Formatted Number (7): 023%
Formatted Number (8): 120E3
Currency in USA : $120,000.23
JSTL Core <fmt:parseNumber> Tag
The <fmt:parseNumber> tag is used to parse numbers, percentages, and currencies.
Attribute:
The <fmt:parseNumber> tag has following attributes:
%ttri"te )escription 'e;ired )efa$t
value Numeric value to read (parse) No Body
type NUMBER, CURRENCY, or PERCENT No number
parseLocale Locale to use when parsing the number No Default locale
MAT SOFT
JAVA REFERENCE GUIDE
570
integerOnly Whether to parse to an integer (true) or floating-point
number (false)
No false
pattern Custom parsing pattern No None
timeZone Time zone of the displayed date No Default time
zone
var Name of the variable to store the parsed number No Print to page
scope Scope of the variable to store the formatted number No page
A pattern attribute is provided that works just like the pattern attribute for the <fmt:formatNumber>
tag. However, in the case of parsing, the pattern attribute tells the parser what format to expect.
Example:
NW\ taglib pr!fi:9)c) uri9)http-//java.sun.com/jsp/jstl/cor!) W.
NW\ taglib pr!fi:9)fmt) uri9)http-//java.sun.com/jsp/jstl/fmt) W.
Nhtml.
Nh!a#.
Ntitl!.J%T1 fmt-pars!=umb!r TagN/titl!.
N/h!a#.
Nbo#y.
NhD.=umb!r Parsing-N/hD.
Nc-s!t var9)balanc!) valu!9)C@HEEED.DHE) /.
Nfmt-pars!=umb!r var9)i) typ!9)numb!r) valu!9)U{balanc!+) /.
Np.Pars!# =umb!r $C( - Nc-out valu!9)U{i+) /.N/p.
Nfmt-pars!=umb!r var9)i) int!g!r?nly9)tru!)
typ!9)numb!r) valu!9)U{balanc!+) /.
Np.Pars!# =umb!r $@( - Nc-out valu!9)U{i+) /.N/p.
N/bo#y.
N/html.
This would produce following result:
Nm"er Parsing:
Parsed Number (1) : 1250003.35
Parsed Number (2) : 1250003
MAT SOFT
JAVA REFERENCE GUIDE
571
JSTL Core <fmt:formatDate> Tag
The <fmt:formatDate> tag is used to format dates in a variety of ways
Attribute:
The <fmt:formatDate> tag has following attributes:
%ttri"te )escription 'e;ired )efa$t
value Date value to display Yes None
type DATE, TIME, or BOTH No date
dateStyle FULL, LONG, MEDIUM, SHORT, or DEFAULT No default
timeStyle FULL, LONG, MEDIUM, SHORT, or DEFAULT No default
pattern Custom formatting pattern No None
timeZone Time zone of the displayed date No Default time zone
var Name of the variable to store the formatted date No Print to page
scope Scope of the variable to store the formatted date No page
The pattern attribute to specify even more precise handling of the date:
Code Prpose Samp$e
G The era designator AD
y The year 2002
M The month April & 04
d The day of the month 20
h The hour(12-hour time) 12
MAT SOFT
JAVA REFERENCE GUIDE
572
H The hour(24-hour time) 0
m The minute 45
s The second 52
S The millisecond 970
E The day of the week Tuesday
D The day of the year 180
F The day of the week in the month 2 (2nd Wed in month)
w The week in the year 27
W The week in the month 2
a The a.m./p.m. indicator PM
k The hour(12-hour time) 24
K The hour(24-hour time) 0
z The time zone Central Standard Time
'

The escape for text
''

The single quote
Example:
NW\ taglib pr!fi:9)c) uri9)http-//java.sun.com/jsp/jstl/cor!) W.
NW\ taglib pr!fi:9)fmt) uri9)http-//java.sun.com/jsp/jstl/fmt) W.
Nhtml.
Nh!a#.
Ntitl!.J%T1 fmt-#at!=umb!r TagN/titl!.
N/h!a#.
Nbo#y.
MAT SOFT
JAVA REFERENCE GUIDE
573
NhD.=umb!r Format-N/hD.
Nc-s!t var9)now) valu!9)NW9n!w java.util.4at!$(W.) /.
Np.Formatt!# 4at! $C(- Nfmt-format4at! typ!9)tim!)
valu!9)U{now+) /.N/p.
Np.Formatt!# 4at! $@(- Nfmt-format4at! typ!9)#at!)
valu!9)U{now+) /.N/p.
Np.Formatt!# 4at! $D(- Nfmt-format4at! typ!9)both)
valu!9)U{now+) /.N/p.
Np.Formatt!# 4at! $F(- Nfmt-format4at! typ!9)both)
#at!%tyl!9)short) tim!%tyl!9)short)
valu!9)U{now+) /.N/p.
Np.Formatt!# 4at! $H(- Nfmt-format4at! typ!9)both)
#at!%tyl!9)m!#ium) tim!%tyl!9)m!#ium)
valu!9)U{now+) /.N/p.
Np.Formatt!# 4at! $M(- Nfmt-format4at! typ!9)both)
#at!%tyl!9)long) tim!%tyl!9)long)
valu!9)U{now+) /.N/p.
Np.Formatt!# 4at! $I(- Nfmt-format4at! patt!rn9)yyyy;MM;##)
valu!9)U{now+) /.N/p.
N/bo#y.
N/html.
This would produce following result:
)ate +ormat:
Formatted Date (1): 14:27:18
Formatted Date (2): 23-Sep-2010
Formatted Date (3): 23-Sep-2010 14:27:18
Formatted Date (4): 23/09/10 14:27
Formatted Date (5): 23-Sep-2010 14:27:18
Formatted Date (6): 23 September 2010 14:27:18 GST
Formatted Date (7): 2010-09-23
JSTL Core <fmt:parseDate> Tag
The <fmt:parseDate> tag is used to parse dates.
MAT SOFT
JAVA REFERENCE GUIDE
574
Attribute:
The <fmt:parseDate> tag has following attributes:
%ttri"te )escription 'e;ired )efa$t
value Date value to read (parse) No Body
type DATE, TIME, or BOTH No date
dateStyle FULL, LONG, MEDIUM, SHORT, or DEFAULT No Default
timeStyle FULL, LONG, MEDIUM, SHORT, or DEFAULT No Default
parseLocale Locale to use when parsing the date No Default locale
pattern Custom parsing pattern No None
timeZone Time zone of the parsed date No Default time zone
var Name of the variable to store the parsed date No Print to page
scope Scope of the variable to store the formatted date No page
A pattern attribute is provided that works just like the pattern attribute for the <fmt:formatDate> tag.
However, in the case of parsing, the pattern attribute tells the parser what format to expect.
Example:
NW\ taglib pr!fi:9)c) uri9)http-//java.sun.com/jsp/jstl/cor!) W.
NW\ taglib pr!fi:9)fmt) uri9)http-//java.sun.com/jsp/jstl/fmt) W.
Nhtml.
Nh!a#.
Ntitl!.J%T1 fmt-pars!4at! TagN/titl!.
N/h!a#.
Nbo#y.
NhD.4at! Parsing-N/hD.
Nc-s!t var9)now) valu!9)@E;CE;@ECE) /.
Nfmt-pars!4at! valu!9)U{now+) var9)pars!#3mp4at!)
patt!rn9)##;MM;yyyy) /.
Np.Pars!# 4at!- Nc-out valu!9)U{pars!#3mp4at!+) /.N/p.
N/bo#y.
N/html.
MAT SOFT
JAVA REFERENCE GUIDE
575
This would produce following result:
)ate Parsing:
Parsed Date: Wed Oct 20 00:00:00 GST 2010
JSTL Core <fmt:timeZone> Tag
The <fmt:timeZone> tag is used to specify the time zone that all tags within its body will use.
Attribute:
The <fmt:timeZone> tag has following attributes:
%ttri"te )escription 'e;ired )efa$t
value Time zone to apply to the body Yes None
Example:
NW\ taglib uri9)http-//java.sun.com/jsp/jstl/cor!) pr!fi:9)c) W.
NW\ taglib uri9)http-//java.sun.com/jsp/jstl/fmt) pr!fi:9)fmt) W.
Nhtml.
Nh!a#.
Ntitl!.J%T1 fmt-tim!Von! TagN/titl!.
N/h!a#.
Nbo#y.
Nc-s!t var9)now) valu!9)NW9n!w java.util.4at!$(W.) /.
Ntabl! bor#!r9)C) wi#th9)CEEW).
Ntr.
Nt# wi#th9)CEEW) colspan9)@) bgcolor9)^EEEEFF).
Np align9)c!nt!r).
Nb.
Nfont color9)^FFFFFF) si/!9)F).Formatting-
Nfmt-format4at! valu!9)U{now+) typ!9)both)
tim!%tyl!9)long) #at!%tyl!9)long) /.
N/font.
N/b.
N/p.
N/t#.
N/tr.
Nc-for3ach var9)/on!)
it!ms9)NW9java.util.Tim!Von!.g!t0vailabl!64s$(W.).
Ntr.
Nt# wi#th9)HCW).
MAT SOFT
JAVA REFERENCE GUIDE
576
Nc-out valu!9)U{/on!+) /.
N/t#.
Nt# wi#th9)FKW).
Nfmt-tim!Von! valu!9)U{/on!+).
Nfmt-format4at! valu!9)U{now+) tim!Von!9)U{/n+)
typ!9)both) /.
N/fmt-tim!Von!.
N/t#.
N/tr.
N/c-for3ach.
N/tabl!.
N/bo#y.
N/html.
This would produce following result:
+ormatting: 5E Septem"er 5I4I 4V:IH:IH ?ST
Etc/GMT+12 22-Sep-2010 23:09:09
Etc/GMT+11 23-Sep-2010 00:09:09
...........................
JSTL Core <fmt:setTimeZone> Tag
The <fmt:setTimeZone> tag is used to copy a time zone object into the specified scoped variable.
Attribute:
The <fmt:setTimeZone> tag has following attributes:
%ttri"te )escription 'e;ired )efa$t
value Time zone to expose as a scoped or configuration variable Yes None
var Name of the variable to store the new time zone No Replace default
scope Scope of the variable to store the new time zone No Page
Example:
NW\ taglib uri9)http-//java.sun.com/jsp/jstl/cor!) pr!fi:9)c) W.
NW\ taglib uri9)http-//java.sun.com/jsp/jstl/fmt) pr!fi:9)fmt) W.
Nhtml.
MAT SOFT
JAVA REFERENCE GUIDE
577
Nh!a#.
Ntitl!.J%T1 fmt-s!tTim!Von! TagN/titl!.
N/h!a#.
Nbo#y.
Nc-s!t var9)now) valu!9)NW9n!w java.util.4at!$(W.) /.
Np.4at! in ,urr!nt Von!- Nfmt-format4at! valu!9)U{now+)
typ!9)both) tim!%tyl!9)long) #at!%tyl!9)long) /.N/p.
Np.,hang! Tim! Von! to 8MT;JN/p.
Nfmt-s!tTim!Von! valu!9)8MT;J) /.
Np.4at! in ,hang!# Von!- Nfmt-format4at! valu!9)U{now+)
typ!9)both) tim!%tyl!9)long) #at!%tyl!9)long) /.N/p.
N/bo#y.
N/html.
This would produce following result:
Date in Current Zone: 23 September 2010 15:21:37 GST
Change Time Zone to GMT-8
Date in Changed Zone: 23 September 2010 03:21:37 GMT-08:00
JSTL Core <fmt:setLocale> Tag
The <fmt:setLocale> tag is used to store the given locale in the locale configuration variable.
Attribute:
The <fmt:setLocale> tag has following attributes:
%ttri"te )escription 'e;ired )efa$t
value Specifies a two-part code that represents the ISO-639 language
code and an ISO-3166 country code.
Yes en_US
variant Browser-specific variant No None
scope Scope of the locale configuration variable No Page
Example:
Resource bundles contain locale-specific objects. Resource bundles contain key/value pairs. When your
program needs a locale-specific resource, you keep all the keys common to all the locale but you can
have translated values specific to locale. Resource bundles helps in providing content specific to locale.
MAT SOFT
JAVA REFERENCE GUIDE
578
A Java resource bundle file contains a series of key-to-string mappings. The method that we focus on
involves creating compiled Java classes that extend the java.util.ListResourceBundle class. You must
compile these class files and make them available to the classpath of your Web application.
Let us define a default resource bundle as follows:
pac<ag! mypac<*
import java.util.1ist7!sourc!Lun#l!*
public class 3:ampl!T3n !:t!n#s 1ist7!sourc!Lun#l! {
public ?bj!ct&'&' g!t,ont!nts$( {
r!turn cont!nts*
+
static final ?bj!ct&'&' cont!nts 9 {
{)count.on!)2 )?n!)+2
{)count.two)2 )Two)+2
{)count.thr!!)2 )Thr!!)+2
+*
+
Now let us define one more resource bundle which we will use for Spanish Locale:
pac<ag! mypac<*
import java.util.1ist7!sourc!Lun#l!*
public class 3:ampl!T!sT3% !:t!n#s 1ist7!sourc!Lun#l! {
public ?bj!ct&'&' g!t,ont!nts$( {
r!turn cont!nts*
+
static final ?bj!ct&'&' cont!nts 9 {
{)count.on!)2 )5no)+2
{)count.two)2 )4os)+2
{)count.thr!!)2 )Tr!s)+2
+*
+
Let us compile above classes Example.class and Example_es_ES.class and make them available in the
CLASSPATH of your Web application. Now you can use the following JSTL tags to display the three
numbers as follows:
NW\ taglib uri9)http-//java.sun.com/jsp/jstl/cor!) pr!fi:9)c) W.
NW\ taglib uri9)http-//java.sun.com/jsp/jstl/fmt) pr!fi:9)fmt) W.
Nhtml.
Nh!a#.
Ntitl!.J%T1 fmt-s!t1ocal! TagN/titl!.
N/h!a#.
Nbo#y.
Nfmt-bun#l! bas!nam!9)mypac<.3:ampl!).
Nfmt-m!ssag! <!y9)count.on!)/.Nbr/.
MAT SOFT
JAVA REFERENCE GUIDE
579
Nfmt-m!ssag! <!y9)count.two)/.Nbr/.
Nfmt-m!ssag! <!y9)count.thr!!)/.Nbr/.
N/fmt-bun#l!.
NG;; ,hang! th! 1ocal! ;;.
Nfmt-s!t1ocal! valu!9)!sT3%)/.
Nfmt-bun#l! bas!nam!9)mypac<.3:ampl!).
Nfmt-m!ssag! <!y9)count.on!)/.Nbr/.
Nfmt-m!ssag! <!y9)count.two)/.Nbr/.
Nfmt-m!ssag! <!y9)count.thr!!)/.Nbr/.
N/fmt-bun#l!.
N/bo#y.
N/html.
This would produce following result:
?n!
Two
Thr!!
5no
4os
Tr!s
JSTL Functions:
JSTL includes a number of standard functions, most of which are common string manipulation
functions. Following is the syntax to include JSTL Functions library in your JSP:
NW\ taglib pr!fi:9)fn)
uri9)http-//java.sun.com/jsp/jstl/functions) W.
Following is the list of JSTL Functions:
+nction )escription
fn:contains() Tests if an input string contains the specified substring.
fn:containsIgnoreCase() Tests if an input string contains the specified substring in a case
insensitive way.
fn:endsWith() Tests if an input string ends with the specified suffix.
fn:escapeXml() Escapes characters that could be interpreted as XML markup.
fn:indexOf() Returns the index withing a string of the first occurrence of a
specified substring.
fn:join() Joins all elements of an array into a string.
fn:length() Returns the number of items in a collection, or the number of
characters in a string.
MAT SOFT
JAVA REFERENCE GUIDE
580
fn:replace() Returns a string resulting from replacing in an input string all
occurrences with a given string.
fn:split() Splits a string into an array of substrings.
fn:startsWith() Tests if an input string starts with the specified prefix.
fn:substring() Returns a subset of a string.
fn:substringAfter() Returns a subset of a string following a specific substring.
fn:substringBefore() Returns a subset of a string before a specific substring.
fn:toLowerCase() Converts all of the characters of a string to lower case.
fn:toUpperCase() Converts all of the characters of a string to upper case.
fn:trim() Removes white spaces from both ends of a string.
Example1: fn:contains() Function
The fn:contains() function determines whether an input string contains a specified substring.
Syntax:
The fn:contains() function has following syntax:
bool!an contains$java.lang.%tring2 java.lang.%tring(
Example:
Following is the example to explain the functionality of this function:
NW\ taglib uri9)http-//java.sun.com/jsp/jstl/cor!) pr!fi:9)c) W.
NW\ taglib uri9)http-//java.sun.com/jsp/jstl/functions)
pr!fi:9)fn) W.
Nhtml.
Nh!a#.
Ntitl!.5sing J%T1 FunctionsN/titl!.
N/h!a#.
Nbo#y.
Nc-s!t var9)th!%tring) valu!9)6 am a t!st %tring)/.
Nc-if t!st9)U{fn-contains$th!%tring2 't!st'(+).
Np.Foun# t!st stringNp.
N/c-if.
Nc-if t!st9)U{fn-contains$th!%tring2 'T3%T'(+).
Np.Foun# T3%T stringNp.
N/c-if.
MAT SOFT
JAVA REFERENCE GUIDE
581
N/bo#y.
N/html.
This would produce following result:
Foun# t!st string
Example2: fn:split() Function
The fn:split() function splits a string into an array of substrings based on a delimiter string.
Syntax:
The fn:split() function has following syntax:
java.lang.%tring&' split$java.lang.%tring2 java.lang.%tring(
Example:
Following is the example to explain the functionality of this function:
NW\ taglib uri9)http-//java.sun.com/jsp/jstl/cor!) pr!fi:9)c) W.
NW\ taglib uri9)http-//java.sun.com/jsp/jstl/functions)
pr!fi:9)fn) W.
Nhtml.
Nh!a#.
Ntitl!.5sing J%T1 FunctionsN/titl!.
N/h!a#.
Nbo#y.
Nc-s!t var9)stringC) valu!9)This is first %tring.)/.
Nc-s!t var9)string@) valu!9)U{fn-split$stringC2 ' '(+) /.
Nc-s!t var9)stringD) valu!9)U{fn-join$string@2 ';'(+) /.
Np.%tring $D( - U{stringD+N/p.
Nc-s!t var9)stringF) valu!9)U{fn-split$stringD2 ';'(+) /.
Nc-s!t var9)stringH) valu!9)U{fn-join$stringF2 ' '(+) /.
Np.%tring $H( - U{stringH+N/p.
N/bo#y.
N/html.
This would produce following result:
%tring $D( - This;is;first;%tring.
MAT SOFT
JAVA REFERENCE GUIDE
582
%tring $H( - This is first %tring.
Day 55: Getting Started with AJAX using Java
AJAX is an acronym for Asynchronous JavaScript And XML. AJAX provides an ability
to communicate with the server asynchronously. Here asynchronous is the keyword.
To explain that in simple terms, you can send a request to server and continue user
interaction with the user. You need not wait for response from the server. Once the
response arrives, a designated area in UI will update itself and reflect the response
information. Whole page need not be reloaded.
This is achieved by AJAX using XMLHttpRequest object. Your browser provides the
capability for XMLHttpRequest object. Most modern browsers provides support for
XMLHttpRequest. This object helps for http request and process XML response. It is
not mandatory that you should use only XML. Simple text can also be used in Ajax
but which is uncommon.
Before continuing with the article, I assume that you have basic knowledge about
http headers, request response mechanism, different method types and response
codes. If you lack knowledge in these areas, it is better to update them before
proceeding. If you cant read GET, POST, HTTP status 200 OK and response
Content-Type: text/html, xml then you must know these topics before learning
AJAX. I am not writing in detail about them here, because each one of them calls
for a detailed separate article.
MAT SOFT
JAVA REFERENCE GUIDE
583
Let me write a HelloWorld ajax web application to demonstrate basics. We shall
have a button with name `Say Hello! On click of that button, without reloading the
whole page we will display "Hello World! by replacing the `Say Hello! button.
Following source code listing contains complete code of sample web application.
index.jsp
Nhtml :mlns9)http-//www.wD.org/CKKK/:html).
Nh!a#.
Ntitl!.8!tting %tart!# with 0J0R using J0B0N/titl!.
Nm!ta http;!Puiv9),ont!nt;Typ!) cont!nt9)t!:t/html* chars!t9utf;J) /.
Nscript typ!9)t!:t/javascript) languag!9)javascript) src9)aja:.js)/.
N/h!a#.
Nbo#y.
N#iv.8!tting %tart!# with 0J0R using J0B0- !llo "orl#GN/#iv.
N#iv i#9)h!llo).
Nbutton typ!9)button) onclic<9)ma<!7!Pu!st$().%ay !lloGN/button.
N/#iv.
N/bo#y.
N/html.
index.jsp contains a div `hello. That is the div which XMLHttpRequest object is going
to overwrite with response from Servlet. On click of the button we call a java script
function makeRequest(). Until now, there is nothing special. Its usual jsp and
javascript call. Ajax is not in the picture.
Now go through makeRequest() given below. Inside that we call
getXMLHttpRequest() which returns a XMLHttpRequest object. That can be used as
a utility method in all your AJAX programs. Thats an attempt to standardization.
Different versions of browsers provide different ways of creating XMLHttpRequest.
We are covering all possible combinations inside that method.
Once we get XMLHttpRequest object, we need to register a function which will be
called on state change. Now its time to explain in detail about XMLHttpRequest
object.
XMLHttpReuest pr!perties and events
XMLHttpRequest consists of properties readyState, status, statusText, responseText
and responseXML.
MAT SOFT
JAVA REFERENCE GUIDE
584
readyState denotes states as 0 - UNINITIALIZED, 1 -
LOADING, 2 - LOADED, 3 - INTERACTIVE, 4 - COMPLETE.
status is HTTP status code for the response
statusText is HTTP status message for the status code
responseText is response text from server
responseXML is DOM document object of reponse XML
document from server
XMLHttpRequest contains an event `onreadystatechange. It is invoked whenever
`readyState property given above changes.
We need to register a function for the above event `onreadystatechange. In our
makeRequest(), after getting xmlHttpRequest object we register
getReadyStateHandler(xmlHttpRequest). Therefore whenever there is a state
change, this function will be called by the XMLHttpRequest / browser.
After registering the callback funtion we set the request url as the HelloWorld
servlet. In web.xml we have done theservlet mapping for that servlet.
In getReadyStateHandler function, if readyState is 4 and http status code is 200
then we set the reponse text from XMLHttpRequest object to the div hello in
index.jsp.
ajax.js
/*
* cr!at!s a n!w RM1ttp7!Pu!st obj!ct which is th! bac<bon! of 0J0R2
* or r!turns fals! if th! brows!r #o!sn't support it
*/
function g!tRM1ttp7!Pu!st$( {
var :mlttp7!P 9 fals!*
// to cr!at! RM1ttp7!Pu!st obj!ct in non;Microsoft brows!rs
if $win#ow.RM1ttp7!Pu!st( {
:mlttp7!P 9 n!w RM1ttp7!Pu!st$(*
+ !ls! if $win#ow.0ctiv!R?bj!ct( {
try {
// to cr!at! RM1ttp7!Pu!st obj!ct in lat!r v!rsions
// of 6nt!rn!t 3:plor!r
:mlttp7!P 9 n!w 0ctiv!R?bj!ct$)Ms:ml@.RM1TTP)(*
+ catch $!:pC( {
try {
MAT SOFT
JAVA REFERENCE GUIDE
585
// to cr!at! RM1ttp7!Pu!st obj!ct in ol#!r v!rsions
// of 6nt!rn!t 3:plor!r
:mlttp7!P 9 n!w 0ctiv!R?bj!ct$)Microsoft.RM1TTP)(*
+ catch $!:p@( {
:mlttp7!P 9 fals!*
+
+
+
r!turn :mlttp7!P*
+
/*
* 0J0R call starts with this function
*/
function ma<!7!Pu!st$( {
var :mlttp7!Pu!st 9 g!tRM1ttp7!Pu!st$(*
:mlttp7!Pu!st.onr!a#ystat!chang! 9 g!t7!a#y%tat!an#l!r$:mlttp7!Pu!st(*
:mlttp7!Pu!st.op!n$)P?%T)2 )h!llo"orl#.#o)2 tru!(*
:mlttp7!Pu!st.s!t7!Pu!st!a#!r$),ont!nt;Typ!)2
)application/:;www;form;url!nco#!#)(*
:mlttp7!Pu!st.s!n#$null(*
+

/*
* 7!turns a function that waits for th! stat! chang! in RM1ttp7!Pu!st
*/
function g!t7!a#y%tat!an#l!r$:mlttp7!Pu!st( {

// an anonymous function r!turn!#
// it list!ns to th! RM1ttp7!Pu!st instanc!
r!turn function$( {
if $:mlttp7!Pu!st.r!a#y%tat! 99 F( {
if $:mlttp7!Pu!st.status 99 @EE( {
#ocum!nt.g!t3l!m!ntLy6#$)h!llo)(.inn!rTM1 9 :mlttp7!Pu!st.r!spons!T!:t*
+ !ls! {
al!rt$)TTP !rror ) > :mlttp7!Pu!st.status > )- ) > :mlttp7!Pu!st.statusT!:t(*
+
+
+*
+
A simple Hello World servet sending response as Hello World! as text.
He""!#!r"d.java
pac<ag! mypac<*

import java:.s!rvl!t.http.ttp%!rvl!t*
import java:.s!rvl!t.http.ttp%!rvl!t7!Pu!st*
import java:.s!rvl!t.http.ttp%!rvl!t7!spons!*

public class !llo"orl# !:t!n#s ttp%!rvl!t {

/**
MAT SOFT
JAVA REFERENCE GUIDE
586
* 0 simpl! !llo"orl# %!rvl!t
*/
public voi# #oPost$ttp%!rvl!t7!Pu!st r!P2 ttp%!rvl!t7!spons! r!s(
throws java.io.6?3:c!ption {
r!s.s!t,ont!ntTyp!$)t!:t/html)(*
r!s.g!t"rit!r$(.writ!$)!llo "orl#G)(*
+

public voi# #o8!t$ttp%!rvl!t7!Pu!st r!P2 ttp%!rvl!t7!spons! r!s(
throws java.io.6?3:c!ption {
#oPost$r!P2 r!s(*
+
+
we$.x%"
NS:ml v!rsion9)C.E) !nco#ing9)5TF;J)S.
Nw!b;app :mlns-:si9)http-//www.wD.org/@EEC/RM1%ch!ma;instanc!)
:mlns9)http-//java.sun.com/:ml/ns/java!!)
:mlns-w!b9)http-//java.sun.com/:ml/ns/java!!/w!b;appT@TH.:s#)
:si-sch!ma1ocation9)http-//java.sun.com/:ml/ns/java!!
http-//java.sun.com/:ml/ns/java!!/w!b;appT@TH.:s#) i#9)"!b0ppT64) v!rsion9)@.H).
N#isplay;nam!.8!tting %tart!# with 0J0R using J0B0N/#isplay;nam!.
Nw!lcom!;fil!;list.
Nw!lcom!;fil!.in#!:.jspN/w!lcom!;fil!.
N/w!lcom!;fil!;list.
Ns!rvl!t.
Ns!rvl!t;nam!.h!llo"orl#N/s!rvl!t;nam!.
Ns!rvl!t;class.mypac<.!llo"orl#N/s!rvl!t;class.
Nloa#;on;startup.CN/loa#;on;startup.
N/s!rvl!t.
Ns!rvl!t;mapping.
Ns!rvl!t;nam!.h!llo"orl#N/s!rvl!t;nam!.
Nurl;patt!rn./h!llo"orl#.#oN/url;patt!rn.
N/s!rvl!t;mapping.
N/w!b;app.
&utput !' He""! #!r"d AJAX
Before AJAX call:
MAT SOFT
JAVA REFERENCE GUIDE
587
After AJAX call:
Day 5(: #e$ Servi)e *ntr!du)ti!n +ut!ria"
Web service is a system that enables applications to communicate with an API. Web
service helps to expose business logic through an API interface where different
systems communicate over network. At higher level there are two parties involved,
party providing the service is web service provider and the one utilizing it is web
service consumer. In a previous hello world tutorial for web servicewe discussed
about creating a service based on soap using Netbeans. This micro tutorial will help
understand some important jargon related to web services. In near future we will
see tutorials based on Eclipse to create web services.
Generally,
Application to application communication.
MAT SOFT
JAVA REFERENCE GUIDE
588
Interoperability between disparate systems.
Communication over network.
Exposed interface is platform independent and internal
implementation is abstracted.
Enables loosely coupled design.
Open protocol is used for establishing communication.
Web services are self contained.
,!%p!nents !' a #e$ Servi)e
This is to highlight some of the important jargons related to web services.
wsd"
Web Services Description Language (WSDL) is used to describe a web service in an
XML file. It covers all the aspects of a web service like what is the message format,
communication protocol, endpoint, security etc. This is a standard provided by W3C
consortium and widely accepted for web services description.
A wsdl xml file for a web service is generally expected to be published publicly so
that parties seeking to utilize its services can understand the nature of service and
consume it accordingly.
+ypes
Types is an important element in WSDL. It is used to describe the message
attributes and respective types. XSD is the preferred format to describe the types.
Type definition can be given in a separate XSD file and imported in WSDL.
N#!finitions .... .
Ntyp!s.
N:s#-sch!ma .... /.*
N/typ!s.
N/#!finitions.
-DD*
MAT SOFT
JAVA REFERENCE GUIDE
589
Universal Description, Discovery and Integration (UDDI) is a directory service. Web
services can register with a UDDI and make themselves available through it for
discovery. It is like a marriage broker :-) People ready to get married will describe
themselves in a standard format (WSDL) and register with this directory. People
seeking pair will approach this directory and discover based on the information
provided and approach.
Stu$ and S.e"et!n
Stub and skeleton are counterparts in a web service setup. Skeleton belongs to
service provider side and stub belongs to receiver side. At lower level stub and
skeleton communicate with each other. From client side the business objects
communicates with stub objects and stub takes the responsibility form the message
and invoke the web service. Once the invoking is done, at service provider side,
skeleton is the parallel object for stub and it receives the request message and
understands it and passes on the information to service side business objects.
/ndp!int
An endpoint is a particular network location with associated protocol which includes
message format mapping using which we can access that instance of web service.
This is described in WSDL file. Consider this as a handle using which we will access
the web service.
0inding
Associating an interface with a protocol and message format is binding. It is used in
endpoint definition. Binding is described in WSDL.
&perati!n
A single logical grouping of a meaningful action which comprises a request and
response is an operation. Group of operations forms a web service.
S&A1
MAT SOFT
JAVA REFERENCE GUIDE
590
Simple Object Access Protocol is a XML based specification for web services
message format and communication over network. That is it helps to describe the
transport method and message format in a web service.
Message
Data that is used to communicate to and fro with a web service is a message. It is a
standalone entity which comprises of complete information for a request or a
response.
#e$ Servi)e Design
As given in diagram a web service has logic and an interface. Logic is the actual
service provided and interface is used to communicate with the web service.
Interface definition is given in WSDL. There are two approaches in implementing a
web service and they are bottom-up and top-down.
0!tt!% -p Appr!a)h
Bottom up approach is where we first define the logic of a web service and then
using that we will build the interface. Service code is written first and then the
WSDL is created using the service code. There are tools available to generate the
wsdl file automatically based on it.
+!p D!wn Appr!a)h
Top down is the reverse of bottom up approach. First the service definition is
written up. WSDL is created first. The complete service definition, message format,
transport protocol, security and everything is described in WSDL. Then service is
written after the WSDL. Using that wsdl the skeleton code is generated
automatically and after that the service code is filled up.
This article is to help us understand what is a soap web service. Through this
tutorial, we will learn to create a simple hello world web service and a web service
client to consume it, of course all in java.
MAT SOFT
JAVA REFERENCE GUIDE
591
For this article to create a hello world soap webservice, I have chosen Netbeans as
the IDE. Netbeans provides better out of the box support for web service
development.
Soap webservice is cumbersome to work with in comparison to RESTful web
services. If the soap web service development is going to happen using notepad
then that is the first dumbest big mistake in the development plan.
#hat is a we$ servi)e2
*GC de$intion $or a 0eb ser!ice is3 Ha so$t0are system designed to support
interoperable machine-to-machine interaction o!er a net0or(I.
Web service is an interface for your software. We may have web user interface or a
thick client (desktop) user interface for our software. Imagine web service as
another similar interface. This interface is not for humans but for softwares.
Web/thick client directly serves end user as an interface to interact with the
software. Web service serves as an interface to software developers. Using web
service as an API, developers can build external systems that will interact with the
software.
There are two major categories of web services
1. SOAP Web Service
2. RESTful Web Service
S!ap #e$ Servi)e
Simple Object Access Protocol (SOAP) is a standard protocol specification for
message exchange based on XML. Communication between the web service and
client happens using XML messages. SOAP defines the rules for communication like
what are all the tags that should be used in XML and their meaning.
R/S+'u" #e$ Servi)e
MAT SOFT
JAVA REFERENCE GUIDE
592
RESTful web service uses architectures that use HTTP or similar protocols by
restricting the interface to use standard operations like GET, POST, PUT, DELETE for
HTTP. Based on my experience RESTful is easier to develop. I know this statement
will invite wrath of SOAP lovers.
#SDL
One major component of a web service is Web Services Description Language
(WSDL). It is an xml file that describes the web service technically in a machine
readable format. That is, using this WSDL file we can understand things like,
Port / Endpoint - URL of the web service (using which we should access it)
Input message format
Output message format
Security protocol that needs to be followed (like https)
Which protocol the web service uses
I just want this article to be a beginning point for your web service exploration. Do
not stop with this, explore more and more and you will love this service oriented
architecture. Theory is too dull isnt it? Lets move to fun part the coding.
He""! #!r"d S&A1 #e$ Servi)e
Download the latest Netbeans IDE. Go! I will wait. I am using NetBeans IDE 7.1 for
this tutorial.
A 0asi) #e$ App"i)ati!n
File - New Project (Ctrl + Shift + n)
In `Categories: choose "Java Web, in `Projects: choose "Web Application and click
Next.
MAT SOFT
JAVA REFERENCE GUIDE
593
In `Project Name: type "SOAPHelloWorld and click Next.
By default `Server: is "GlassFish Server 3.1.1" and `Java EE Version: is "Java EE 6
Web and click Finish.
Now you have created a basic web application. By default NetBeans creates
web.xml and a welcome page (Hello World) jsp page.
MAT SOFT
JAVA REFERENCE GUIDE
594
Just to ensure our basic setup is good, right click on the project name and click
`Run.
(If you have firewall running, it may popup to allow access - just allow access)
We should get "Hello World! message in the browser. This is just a basic web
application printing hello world. Now we want to do the same thing using a web
service.
+!wards #e$ Servi)e
Right click on project name, select `New and then select `Web Service
Type `Web Service Name: as "HelloWorld, then type `Package: as "mypack and
click Finish.
MAT SOFT
JAVA REFERENCE GUIDE
595
Thats it! Web service development is done! Oh my God this is too much. Is that so
easy?? Till now, we have heard a lot about web services but we never thought of it
to be so easy! Wait wait, before we relax..
NetBeans has created this SOAP based hello world web service. Lets understand
what it has done in the background and verify if it is working.
Servi)e ,!de
Following is the java code that serves as the web service and it is generated by
Netbeans.
/*
* To chang! this t!mplat!2 choos! Tools a T!mplat!s
* an# op!n th! t!mplat! in th! !#itor.
*/
pac<ag! mypac<*

import java:.jws."!b%!rvic!*
import java:.jws."!bM!tho#*
import java:.jws."!bParam*

/**
*
* \author 5%37
*/
\"!b%!rvic!$s!rvic!=am! 9 )!llo"orl#)(
public class !llo"orl# {

MAT SOFT
JAVA REFERENCE GUIDE
596
/**
* This is a sampl! w!b s!rvic! op!ration
*/
\"!bM!tho#$op!ration=am! 9 )h!llo)(
public %tring h!llo$\"!bParam$nam! 9 )nam!)( %tring t:t( {
r!turn )!llo ) > t:t > ) G)*
+
+
hello is the operation that returns "Hello + the parameter sent as argument.
#SDL !' #e$ Servi)e
Now right click the project and click run. Then type the following url in the browser
http://localhost:8080/SOAPHelloWorld/HelloWorld?wsdl
it will return the wsdl of the soap web service that we have created now. This wsdl
contains,
xml definition
XSD schema import
Two message tags hello and helloResponse (request and response)
Porttype definition including operation hello
Binding describes, we use soap, then operation, input and output.
Service definition, name, port and address for invocation.
#e$ Servi)e ,"ient
Now lets invoke this webservice and see how it works.
Open the index.jsp that was generated by NetBeans
MAT SOFT
JAVA REFERENCE GUIDE
597
Remove the "Hello World! string. We are going to access the now created soap web
service in the place and print whatever the web service returns.
Right click on the project and choose `New then `Web Service Client.
In the New Web Service Client dialog select `WSDL URL: and type the wsdl url in
the text box `http://localhost:8080/SOAPHelloWorld/HelloWorld?wsdl. Then in
package, type mypackclient and click Finish.
MAT SOFT
JAVA REFERENCE GUIDE
598
*nv!.e the #e$ Servi)e
Now the web service client is ready. We need to invoke the hello world soap web
service using the web service client we have created now.
In that place right click choose "Web Service Client Resources then select "Call
Web Service Operation.
From that dialog select "hello and clik ok. This is the operation we are invoking of
that web service.
MAT SOFT
JAVA REFERENCE GUIDE
599
Following is the code snippet inserted by Netbeans IDE to access the web service.
NW try { mypac<cli!nt.!llo"orl#T%!rvic! s!rvic! 9
n!w mypac<cli!nt.!llo"orl#T%!rvic!$(*
mypac<cli!nt.!llo"orl# port 9 s!rvic!.g!t!llo"orl#Port$(*
// T?4? initiali/! "% op!ration argum!nts h!r!
java.lang.%tring nam! 9 ))*
// T?4? proc!ss r!sult h!r!
java.lang.%tring r!sult 9 port.h!llo$nam!(*
out.println$)7!sult 9 )>r!sult(*
+
catch $3:c!ption !:( {
// T?4? han#l! custom !:c!ptions h!r! + W.
In the above code snippet, for vaiable `name assign a string value you prefer like,
java.lang.%tring nam! 9 )w!bs!rvic! !:ampl!)*
Right click the project and select `run and you get "Result = Hello webservice
example !
MAT SOFT
JAVA REFERENCE GUIDE
600
Day *7: 'I:ERNA(E
ORM O<1-<#1&
What is JDBC?
JDBC stands for Java )ata"ase Connectivity and provides a set of Java API for accessing the
relational databases from Java program. These Java APIs enables Java programs to execute SQL
statements and interact with any SQL compliant database.
JDBC provides a flexible architecture to write a database independent application that can run on
different platforms and interact with different DBMS without any modification.
Pros and Cons of JDBC
Pros of J)BC Cons of J)BC
Clean and simple SQL processing
Good performance with large data
Very good for small applications
Simple syntax so easy to learn
Complex if it is used in large projects
Large programming overhead
No encapsulation
Hard to implement MVC concept
Query is DBMS specific
Why Object Relational Mapping (ORM)?
When we work with an object-oriented systems, there's a mismatch between the object model and the
relational database. RDBMSs represent data in a tabular format whereas object-oriented languages,
such as Java or C# represent it as an interconnected graph of objects. Consider the following Java
Class with proper constructors and associated public function:
public class 3mploy!! {
privat! int i#*
privat! %tring firstTnam!*
privat! %tring lastTnam!*
privat! int salary*
public 3mploy!!$( {+
public 3mploy!!$%tring fnam!2 %tring lnam!2 int salary( {
this.firstTnam! 9 fnam!*
this.lastTnam! 9 lnam!*
this.salary 9 salary*
+
public int g!t6#$( {
MAT SOFT
JAVA REFERENCE GUIDE
601
r!turn i#*
+
public %tring g!tFirst=am!$( {
r!turn firstTnam!*
+
public %tring g!t1ast=am!$( {
r!turn lastTnam!*
+
public int g!t%alary$( {
r!turn salary*
+
+
Consider above objects need to be stored and retrieved into the following RDBMS table:
cr!at! tabl! 3MP1?A33 $
i# 6=T =?T =511 autoTincr!m!nt2
firstTnam! B07,07$@E( #!fault =5112
lastTnam! B07,07$@E( #!fault =5112
salary 6=T #!fault =5112
P76M07A Y3A $i#(
(*
First problem, what if we need to modify the design of our database after having developed few pages
or our application? Second, Loading and storing objects in a relational database exposes us to the
following five mismatch problems.
Mismatch )escription
Granularity Sometimes you will have an object model which has more classes than the
number of corresponding tables in the database.
Inheritance RDBMSs do not define anything similar to Inheritance which is a natural paradigm
in object-oriented programming languages.
Identity A RDBMS defines exactly one notion of 'sameness': the primary key. Java,
however, defines both object identity (a==b) and object equality (a.equals(b)).
Associations Object-oriented languages represent associations using object references where
as am RDBMS represents an association as a foreign key column.
Navigation The ways you access objects in Java and in a RDBMS are fundamentally different.
The !bject-'elational Mapping (ORM) is the solution to handle all the above impedance mismatches.
MAT SOFT
JAVA REFERENCE GUIDE
602
What is ORM?
ORM stands for !bject-'elational Mapping (ORM) is a programming technique for converting data
between relational databases and object oriented programming languages such as Java, C# etc. An
ORM system has following advantages over plain JDBC
S1N1 %dvantages
1 Lets business code access objects rather than DB tables.
2 Hides details of SQL queries from OO logic.
3 Based on JDBC 'under the hood'
4 No need to deal with the database implementation.
5 Entities based on business concepts rather than database structure.
6 Transaction management and automatic key generation.
7 Fast development of application.
An ORM solution consists of the following four entities:
S1N1 So$tions
1 An API to perform basic CRUD operations on objects of persistent classes.
2 A language or API to specify queries that refer to classes and properties of classes.
3 A configurable facility for specifying mapping metadata.
4 A technique to interact with transactional objects to perform dirty checking, lazy association
fetching, and other optimization functions.
Java ORM Frameworks:
There are several persistent frameworks and ORM options in Java. A persistent framework is an ORM
service that stores and retrieves objects into a relational database.
Enterprise JavaBeans Entity Beans
Java Data Objects
MAT SOFT
JAVA REFERENCE GUIDE
603
Castor
TopLink
Spring DAO
Hibernate
And many more
@IBERNATE OVERVIEW
Hibernate is an Object-Relational Mapping(ORM) solution for JAVA and it raised as an open source
persistent framework created by Gavin King in 2001. It is a powerful, high performance Object-
Relational Persistence and Query service for any Java Application.
Hibernate maps Java classes to database tables and from Java data types to SQL data types and
relieve the developer from 95% of common data persistence related programming tasks.
Hibernate sits between traditional Java objects and database server to handle all the work in persisting
those objects based on the appropriate O/R mechanisms and patterns.
Hibernate Advantages:
Hibernate takes care of mapping Java classes to database tables using XML files and without
writing any line of code.
Provides simple APIs for storing and retrieving Java objects directly to and from the database.
If there is change in Database or in any table then the only need to change XML file
properties.
Abstract away the unfamiliar SQL types and provide us to work around familiar Java Objects.
Hibernate does not require an application server to operate.
Manipulates Complex associations of objects of your database.
Minimize database access with smart fetching strategies.
MAT SOFT
JAVA REFERENCE GUIDE
604
Provides Simple querying of data.
Supported Databases:
Hibernate supports almost all the major RDBMS. Following is list of few of the database engines
supported by Hibernate.
HSQL Database Engine
DB2/NT
MySQL
PostgreSQL
FrontBase
Oracle
Microsoft SQL Server Database
Sybase SQL Server
Informix Dynamic Server
Supported Technologies:
Hibernate supports a variety of other technologies, including the following:
XDoclet Spring
J2EE
Eclipse plug-ins
Maven
ARC@ETICT?RE
The Hibernate architecture is layered to keep you isolated from having to know the underlying APIs.
Hibernate makes use of the database and configuration data to provide persistence services (and
persistent objects) to the application.
Following is a very high level view of the Hibernate Application Architecture.
MAT SOFT
JAVA REFERENCE GUIDE
605
Following is a detailed view of the Hibernate Application Architecture with few important core classes.
MAT SOFT
JAVA REFERENCE GUIDE
606
Hibernate uses various existing Java APIs, like JDBC, Java Transaction API(JTA), and Java Naming and
Directory Interface (JNDI). JDBC provides a rudimentary level of abstraction of functionality common
to relational databases, allowing almost any database with a JDBC driver to be supported by
Hibernate. JNDI and JTA allow Hibernate to be integrated with J2EE application servers.
Following section gives brief description of each of the class objects involved in Hibernate Application
Architecture.
Confguration Object:
The Configuration object is the first Hibernate object you create in any Hibernate application and
usually created only once during application initialization. It represents a configuration or properties
file required by the Hibernate. The Configuration object provides two keys components:
.. )ata"ase Connection: This is handled through one or more configuration files supported by
Hibernate. These files are hi"ernate1properties and hi"ernate1cfg1xm$.
/. C$ass Mapping Setp
This component creates the connection between the Java classes and database tables..
MAT SOFT
JAVA REFERENCE GUIDE
607
SessionFactory Object:
Configuration object is used to create a SessionFactory object which inturn configures Hibernate for
the application using the supplied configuration file and allows for a Session object to be instantiated.
The SessionFactory is a thread safe object and used by all the threads of an application.
The SessionFactory is is heavyweight object so usually it is created during application start up and
kept for later use. You would need one SessionFactory object per database using a separate
configuration file. So if you are using multiple databases then you would have to create multiple
SessionFactory objects.
Session Object:
A Session is used to get a physical connection with a database. The Session object is lightweight and
designed to be instantiated each time an interaction is needed with the database. Persistent objects
are saved and retrieved through a Session object.
The session objects should not be kept open for a long time because they are not usually thread safe
and they should be created and destroyed them as needed.
Transaction Object:
A Transaction represents a unit of work with the database and most of the RDBMS supports
transaction functionality. Transactions in Hibernate are handled by an underlying transaction manager
and transaction (from JDBC or JTA).
This is an optional object and Hibernate applications may choose not to use this interface, instead
managing transactions in their own application code.
Query Object:
Query objects use SQL or Hibernate Query Language (HQL) string to retrieve data from the database
and create objects. A Query instance is used to bind query parameters, limit the number of results
returned by the query, and finally to execute the query.
Criteria Object:
Criteria object are used to create and execute object oriented criteria queries to retrieve objects.
ENVIRONMENT
This chapter will explain how to install Hibernate and other associated packages to prepare a develop
environment for the Hibernate applications. We will work with MySQL database to experiment with
Hibernate examples, so make sure you already have setup for MySQL database. For a more detail on
MySQL you can check our MySQL Tutorial.
MAT SOFT
JAVA REFERENCE GUIDE
608
Downloading Hibernate:
It is assumed that you already have latest version of Java is installed on your machine. Following are
the simple steps to download and install Hibernate on your machine.
Make a choice whether you want to install Hibernate on Windows, or Unix and then proceed to
the next step to download .zip file for windows and .tz file for Unix.
Download the latest version of Hibernate from http://www.hibernate.org/downloads.
At the time of writing this tutorial I downloaded hi"ernate&distri"tion&E181F1+ina$ and
when you unzip the downloaded file it will give you directory structure as follows.
Installing Hibernate:
Once you downloaded and unzipped the latest version of the Hibernate Installation file, you need to
perform following two simple steps. Make sure you are setting your CLASSPATH variable properly
otherwise you will face problem while compiling your application.
Now copy all the library files from K$i" into your CLASSPATH, and change your classpath
variable to include all the JARs:
Finally copy hi"ernateE1#ar file into your CLASSPATH. This file lies in the root directory of the
installation and is the primary JAR that Hibernate needs to do its work.
Hibernate Prerequisites:
Following is the list of the packages/libraries required by Hibernate and you should install them before
starting with Hibernate. To install these packages you would have to copy library files from K$i" into
your CLASSPATH, and change your CLASSPATH variable accordingly.
S1N1 Pac=agesK0i"raries
1 domF# - XML parsing www.dom4j.org/
2 >a$an - XSLT Processor http://xml.apache.org/xalan-j/
MAT SOFT
JAVA REFERENCE GUIDE
609
3 >erces - The Xerces Java Parser http://xml.apache.org/xerces-j/
4 cg$i" - Appropriate changes to Java classes at runtime http://cglib.sourceforge.net/
5 $ogF# - Logging Faremwork http://logging.apache.org/log4j
6 Commons - Logging, Email etc. http://jakarta.apache.org/commons
7 S0+FJ - Logging Facade for Java http://www.slf4j.org
CONFI?RATION
Hibernate requires to know in advance where to find the mapping information that defines how your
Java classes relate to the database tables. Hibernate also requires a set of configuration settings
related to database and other related parameters. All such information is usually supplied as a
standard Java properties file called hi"ernate1properties, or as an XML file
named hi"ernate1cfg1xm$.
I will consider XML formatted file hi"ernate1cfg1xm$ to specify required Hibernate properties in my
examples. Most of the properties take their default values and it is not required to specify them in the
property file unless it is really required. This file is kept in the root directory of your application's
classpath.
Hibernate Properties:
Following is the list of important properties you would require to configure for a databases in a
standalone situation:
S1N1 Properties and )escription
1 hi"ernate1dia$ect
This property makes Hibernate generate the appropriate SQL for the chosen database.
2 hi"ernate1connection1driverGc$ass
The JDBC driver class.
3 hi"ernate1connection1r$
The JDBC URL to the database instance.
4 hi"ernate1connection1sername
The database username.
5 hi"ernate1connection1pass3ord
The database password.
MAT SOFT
JAVA REFERENCE GUIDE
610
6 hi"ernate1connection1poo$Gsi2e
Limits the number of connections waiting in the Hibernate database connection pool.
7 hi"ernate1connection1atocommit
Allows autocommit mode to be used for the JDBC connection.
If you are using a database along with an application server and JNDI then you would have to
configure the following properties:
S1N1 Properties and )escription
1 hi"ernate1connection1datasorce
The JNDI name defined in the application server context you are using for the application.
2 hi"ernate1#ndi1c$ass
The InitialContext class for JNDI.
3 hi"ernate1#ndi1WJN)IpropertynameX
Passes any JNDI property you like to the JNDI 5nitialContext.
4 hi"ernate1#ndi1r$
Provides the URL for JNDI.
5 hi"ernate1connection1sername
The database username.
6 hi"ernate1connection1pass3ord
The database password.
Hibernate with MySQL Database:
MySQL is one of the most popular open-source database systems available today. Let us
createhi"ernate1cfg1xm$ configuration file and place it in the root of your application's classpath. You
would have to make sure that you have testd" database available in your MySQL database and you
have a user test available to access the database.
The XML configuration file must conform to the Hibernate 3 Configuration DTD, which is available from
http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd.
NS:ml v!rsion9)C.E) !nco#ing9)utf;J)S.
NG4?,TAP3 hib!rnat!;configuration %A%T3M
)http-//www.hib!rnat!.org/#t#/hib!rnat!;configuration;D.E.#t#).
Nhib!rnat!;configuration.
Ns!ssion;factory.
MAT SOFT
JAVA REFERENCE GUIDE
611
Nprop!rty nam!9)hib!rnat!.#ial!ct).
org.hib!rnat!.#ial!ct.My%X14ial!ct
N/prop!rty.
Nprop!rty nam!9)hib!rnat!.conn!ction.#riv!rTclass).
com.mysPl.j#bc.4riv!r
N/prop!rty.
NG;; 0ssum! t!st is th! #atabas! nam! ;;.
Nprop!rty nam!9)hib!rnat!.conn!ction.url).
j#bc-mysPl-//localhost/t!st
N/prop!rty.
Nprop!rty nam!9)hib!rnat!.conn!ction.us!rnam!).
root
N/prop!rty.
Nprop!rty nam!9)hib!rnat!.conn!ction.passwor#).
rootC@D
N/prop!rty.
NG;; 1ist of RM1 mapping fil!s ;;.
Nmapping r!sourc!9)3mploy!!.hbm.:ml)/.
N/s!ssion;factory.
N/hib!rnat!;configuration.
The above configuration file includes WmappingX tags which are related to hibernate-mapping file
and we will see in next chapter what exactly is a hibernate mapping file and how and why do we use
it. Following is the list of various important databases dialect property type:
)ata"ase )ia$ect Property
DB2 org.hibernate.dialect.DB2Dialect
HSQLDB org.hibernate.dialect.HSQLDialect
HypersonicSQL org.hibernate.dialect.HSQLDialect
Informix org.hibernate.dialect.InformixDialect
Ingres org.hibernate.dialect.IngresDialect
Interbase org.hibernate.dialect.InterbaseDialect
Microsoft SQL Server 2000 org.hibernate.dialect.SQLServerDialect
Microsoft SQL Server 2005 org.hibernate.dialect.SQLServer2005Dialect
Microsoft SQL Server 2008 org.hibernate.dialect.SQLServer2008Dialect
MAT SOFT
JAVA REFERENCE GUIDE
612
MySQL org.hibernate.dialect.MySQLDialect
Oracle (any version) org.hibernate.dialect.OracleDialect
Oracle 11g org.hibernate.dialect.Oracle10gDialect
Oracle 10g org.hibernate.dialect.Oracle10gDialect
Oracle 9i org.hibernate.dialect.Oracle9iDialect
PostgreSQL org.hibernate.dialect.PostgreSQLDialect
Progress org.hibernate.dialect.ProgressDialect
SAP DB org.hibernate.dialect.SAPDBDialect
Sybase org.hibernate.dialect.SybaseDialect
Sybase Anywhere org.hibernate.dialect.SybaseAnywhereDialect
SESSIONS
A Session is used to get a physical connection with a database. The Session object is lightweight and
designed to be instantiated each time an interaction is needed with the database. Persistent objects
are saved and retrieved through a Session object.
The session objects should not be kept open for a long time because they are not usually thread safe
and they should be created and destroyed them as needed. The main function of the Session is to
offer create, read and delete operations for instances of mapped entity classes. Instances may exist in
one of the following three states at a given point in time:
1. transient: A new instance of a a persistent class which is not associated with a Session and
has no representation in the database and no identifier value is considered transient by
Hibernate.
2. persistent: You can make a transient instance persistent by associating it with a Session. A
persistent instance has a representation in the database, an identifier value and is associated
with a Session.
3. detached: Once we close the Hibernate Session, the persistent instance will become a
detached instance.
A Session instance is serializable if its persistent classes are serializable. A typical transaction should
use the following idiom:
MAT SOFT
JAVA REFERENCE GUIDE
613
%!ssion s!ssion 9 factory.op!n%!ssion$(*
Transaction t: 9 null*
try {
t: 9 s!ssion.b!ginTransaction$(*
// #o som! wor<
...
t:.commit$(*
+
catch $3:c!ption !( {
if $t:G9null( t:.rollbac<$(*
!.print%tac<Trac!$(*
+finally {
s!ssion.clos!$(*
+
If the Session throws an exception, the transaction must be rolled back and the session must be
discarded.
Session Interface Methods:
There are number of methods provided by the Session interface but I'm going to list down few
important methods only, which we will use in this tutorial. You can check Hibernate documentation for
a complete list of methods associated with Session and Session+actory.
S1N1 Session Methods and )escription
1 Transaction "eginTransaction,/
Begin a unit of work and return the associated Transaction object.
2 void cance$Jery,/
Cancel the execution of the current query.
3 void c$ear,/
Completely clear the session.
4 Connection c$ose,/
End the session by releasing the JDBC connection and cleaning up.
5 Criteria createCriteria,C$ass persistentC$ass/
Create a new Criteria instance, for the given entity class, or a superclass of an entity class.
6 Criteria createCriteria,String entityName/
Create a new Criteria instance, for the given entity name.
7 Seria$i2a"$e getIdentifier,!"#ect o"#ect/
Return the identifier value of the given entity as associated with this session.
MAT SOFT
JAVA REFERENCE GUIDE
614
8 Jery create+i$ter,!"#ect co$$ection< String ;eryString/
Create a new instance of Query for the given collection and filter string.
9 Jery createJery,String ;eryString/
Create a new instance of Query for the given HQL query string.
10 SJ0Jery createSJ0Jery,String ;eryString/
Create a new instance of SQLQuery for the given SQL query string.
11 void de$ete,!"#ect o"#ect/
Remove a persistent instance from the datastore.
12 void de$ete,String entityName< !"#ect o"#ect/
Remove a persistent instance from the datastore.
13 Session get,String entityName< Seria$i2a"$e id/
Return the persistent instance of the given named entity with the given identifier, or null if there
is no such persistent instance.
14 Session+actory getSession+actory,/
Get the session factory which created this session.
15 void refresh,!"#ect o"#ect/
Re-read the state of the given instance from the underlying database.
16 Transaction getTransaction,/
Get the Transaction instance associated with this session.
17 "oo$ean isConnected,/
Check if the session is currently connected.
18 "oo$ean is)irty,/
Does this session contain any changes which must be synchronized with the database?
19 "oo$ean is!pen,/
Check if the session is still open.
20 Seria$i2a"$e save,!"#ect o"#ect/
Persist the given transient instance, first assigning a generated identifier.
21 void save!rBpdate,!"#ect o"#ect/
Either save(Object) or update(Object) the given instance.
22 void pdate,!"#ect o"#ect/
MAT SOFT
JAVA REFERENCE GUIDE
615
Update the persistent instance with the identifier of the given detached instance.
23 void pdate,String entityName< !"#ect o"#ect/
Update the persistent instance with the identifier of the given detached instance.
PERSISTANCE CLASS
The entire concept of Hibernate is to take the values from Java class attributes and persist them to a
database table. A mapping document helps Hibernate in determining how to pull the values from the
classes and map them with table and associated fields.
Java classes whose objects or instances will be stored in database tables are called persistent classes
in Hibernate. Hibernate works best if these classes follow some simple rules, also known as the Plain
Old Java Object (POJO) programming model. There are following main rules of persistent classes,
however, none of these rules are hard requirements.
All Java classes that will be persisted need a default constructor.
All classes should contain an ID in order to allow easy identification of your objects within
Hibernate and the database. This property maps to the primary key column of a database
table.
All attributes that will be persisted should be declared private and
have get>>> andset>>> methods defined in the JavaBean style.
A central feature of Hibernate, proxies, depends upon the persistent class being either non-
final, or the implementation of an interface that declares all public methods.
All classes that do not extend or implement some specialized classes and interfaces required
by the EJB framework.
The POJO name is used to emphasize that a given object is an ordinary Java Object, not a special
object, and in particular not an Enterprise JavaBean.
A simple POJO example:
Based on the few rules mentioned above we can define a POJO class as follows:
public class 3mploy!! {
privat! int i#*
privat! %tring first=am!*
privat! %tring last=am!*
privat! int salary*
public 3mploy!!$( {+
public 3mploy!!$%tring fnam!2 %tring lnam!2 int salary( {
MAT SOFT
JAVA REFERENCE GUIDE
616
this.first=am! 9 fnam!*
this.last=am! 9 lnam!*
this.salary 9 salary*
+
public int g!t6#$( {
r!turn i#*
+
public voi# s!t6#$ int i# ( {
this.i# 9 i#*
+
public %tring g!tFirst=am!$( {
r!turn first=am!*
+
public voi# s!tFirst=am!$ %tring firstTnam! ( {
this.first=am! 9 firstTnam!*
+
public %tring g!t1ast=am!$( {
r!turn last=am!*
+
public voi# s!t1ast=am!$ %tring lastTnam! ( {
this.last=am! 9 lastTnam!*
+
public int g!t%alary$( {
r!turn salary*
+
public voi# s!t%alary$ int salary ( {
this.salary 9 salary*
+
+
MAPPIN FILES
An Object/relational mappings are usually defined in an XML document. This mapping file instructs
Hibernate how to map the defined class or classes to the database tables.
Though many Hibernate users choose to write the XML by hand, a number of tools exist to generate
the mapping document. These include >)oc$et< Midd$egen and %ndroM)% for advanced Hibernate
users.
Let us consider our previously defined POJO class whose objects will persist in the table defined in
next section.
public class 3mploy!! {
privat! int i#*
privat! %tring first=am!*
privat! %tring last=am!*
privat! int salary*
public 3mploy!!$( {+
public 3mploy!!$%tring fnam!2 %tring lnam!2 int salary( {
this.first=am! 9 fnam!*
this.last=am! 9 lnam!*
MAT SOFT
JAVA REFERENCE GUIDE
617
this.salary 9 salary*
+
public int g!t6#$( {
r!turn i#*
+
public voi# s!t6#$ int i# ( {
this.i# 9 i#*
+
public %tring g!tFirst=am!$( {
r!turn first=am!*
+
public voi# s!tFirst=am!$ %tring firstTnam! ( {
this.first=am! 9 firstTnam!*
+
public %tring g!t1ast=am!$( {
r!turn last=am!*
+
public voi# s!t1ast=am!$ %tring lastTnam! ( {
this.last=am! 9 lastTnam!*
+
public int g!t%alary$( {
r!turn salary*
+
public voi# s!t%alary$ int salary ( {
this.salary 9 salary*
+
+
There would be one table corresponding to each object you are willing to provide persistence. Consider
above objects need to be stored and retrieved into the following RDBMS table:
cr!at! tabl! 3MP1?A33 $
i# 6=T =?T =511 autoTincr!m!nt2
firstTnam! B07,07$@E( #!fault =5112
lastTnam! B07,07$@E( #!fault =5112
salary 6=T #!fault =5112
P76M07A Y3A $i#(
(*
Based on the two above entities we can define following mapping file which instructs Hibernate how to
map the defined class or classes to the database tables.
NS:ml v!rsion9)C.E) !nco#ing9)utf;J)S.
NG4?,TAP3 hib!rnat!;mapping P5L16,
);//ib!rnat!/ib!rnat! Mapping 4T4//3=)
)http-//www.hib!rnat!.org/#t#/hib!rnat!;mapping;D.E.#t#).
Nhib!rnat!;mapping.
Nclass nam!9)3mploy!!) tabl!9)3MP1?A33).
Nm!ta attribut!9)class;#!scription).
This class contains th! !mploy!! #!tail.
N/m!ta.
Ni# nam!9)i#) typ!9)int) column9)i#).
MAT SOFT
JAVA REFERENCE GUIDE
618
Ng!n!rator class9)nativ!)/.
N/i#.
Nprop!rty nam!9)first=am!) column9)firstTnam!) typ!9)string)/.
Nprop!rty nam!9)last=am!) column9)lastTnam!) typ!9)string)/.
Nprop!rty nam!9)salary) column9)salary) typ!9)int)/.
N/class.
N/hib!rnat!;mapping.
You should save the mapping document in a file with the format <classname>.hbm.xml. We saved our
mapping document in the file Employee.hbm.xml. Let us see little detail about the mapping elements
used in the mapping file:
The mapping document is an XML document having Whi"ernate&mappingX as the root
element which contains all the <class> elements.
The Wc$assX elements are used to define specific mappings from a Java classes to the
database tables. The Java class name is specified using the name attribute of the class
element and the database table name is specified using the ta"$e attribute.
The WmetaX element is optional element and can be used to create the class description.
The WidX element maps the unique ID attribute in class to the primary key of the database
table. The name attribute of the id element refers to the prPESoperty in the class and
the co$mn attribute refers to the column in the database table. The type attribute holds the
hibernate mapping type, this mapping types will convert from Java to SQL data type.
The WgeneratorX element within the id element is used to automatically generate the
primary key values. Set the c$ass attribute of the generator element is set to native to let
hibernate pick up either identity< se;ence or hi$o algorithm to create primary key
depending upon the capabilities of the underlying database.
The WpropertyX element is used to map a Java class property to a column in the database
table. The name attribute of the element refers to the property in the class and
the co$mn attribute refers to the column in the database table. The type attribute holds the
hibernate mapping type, this mapping types will convert from Java to SQL data type.
There are other attributes and elements available which will be used in a mapping document and I
would try to cover as many as possible while discussing other Hibernate related topics.
MAPPIN T!PES
When you prepare a Hibernate mapping document, we have seen that you map Java data types into
RDBMS data types. The types declared and used in the mapping files are not Java data types; they
are not SQL database types either. These types are called Hibernate mapping types, which can
translate from Java to SQL data types and vice versa.
This chapter lists down all the basic, date and time, large object, and various other builtin mapping
types.
Primitive types:
Mapping type Java type %NSI SJ0 Type
MAT SOFT
JAVA REFERENCE GUIDE
619
integer int or java.lang.Integer INTEGER
long long or java.lang.Long BIGINT
short short or java.lang.Short SMALLINT
float float or java.lang.Float FLOAT
double double or java.lang.Double DOUBLE
big_decimal java.math.BigDecimal NUMERIC
character java.lang.String CHAR(1)
string java.lang.String VARCHAR
byte byte or java.lang.Byte TINYINT
boolean boolean or java.lang.Boolean BIT
yes/no boolean or java.lang.Boolean CHAR(1) ('Y' or 'N')
true/false boolean or java.lang.Boolean CHAR(1) ('T' or 'F')
Date and time types:
Mapping type Java type %NSI SJ0 Type
date java.util.Date or java.sql.Date DATE
time java.util.Date or java.sql.Time TIME
timestamp java.util.Date or java.sql.Timestamp TIMESTAMP
calendar java.util.Calendar TIMESTAMP
calendar_date java.util.Calendar DATE
Binary and large object types:
Mapping type Java type %NSI SJ0 Type
MAT SOFT
JAVA REFERENCE GUIDE
620
binary byte[] VARBINARY (or BLOB)
text java.lang.String CLOB
serializable any Java class that implements java.io.Serializable VARBINARY (or BLOB)
clob java.sql.Clob CLOB
blob java.sql.Blob BLOB
JDK-related types:
Mapping type Java type %NSI SJ0 Type
class java.lang.Class VARCHAR
locale java.util.Locale VARCHAR
timezone java.util.TimeZone VARCHAR
currency java.util.Currency VARCHAR
EIAMPLE
Let us try an example of using Hibernate to provide Java persistence in a standalone application. We
will go through different steps involved in creating Java Application using Hibernate technology.
Create POJO Classes:
The first step in creating an application is to build the Java POJO class or classes, depending on the
application that will be persisted to the database. Let us consider our 7mp$oyee class
withget>>> and set>>> methods to make it JavaBeans compliant class.
A POJO (Plain Old Java Object) is a Java object that doesn't extend or implement some specialized
classes and interfaces respectively required by the EJB framework. All normal Java objects are POJO.
When you design a classs to be persisted by Hibernate, it's important to provide JavaBeans compliant
code as well as one attribute which would work as index like id attribute in the Employee class.
public class 3mploy!! {
privat! int i#*
privat! %tring first=am!*
privat! %tring last=am!*
privat! int salary*
MAT SOFT
JAVA REFERENCE GUIDE
621
public 3mploy!!$( {+
public 3mploy!!$%tring fnam!2 %tring lnam!2 int salary( {
this.first=am! 9 fnam!*
this.last=am! 9 lnam!*
this.salary 9 salary*
+
public int g!t6#$( {
r!turn i#*
+
public voi# s!t6#$ int i# ( {
this.i# 9 i#*
+
public %tring g!tFirst=am!$( {
r!turn first=am!*
+
public voi# s!tFirst=am!$ %tring firstTnam! ( {
this.first=am! 9 firstTnam!*
+
public %tring g!t1ast=am!$( {
r!turn last=am!*
+
public voi# s!t1ast=am!$ %tring lastTnam! ( {
this.last=am! 9 lastTnam!*
+
public int g!t%alary$( {
r!turn salary*
+
public voi# s!t%alary$ int salary ( {
this.salary 9 salary*
+
+
Create Database Tables:
Second step would be creating tables in your database. There would be one table corresponding to
each object you are willing to provide persistence. Consider above objects need to be stored and
retrieved into the following RDBMS table:
cr!at! tabl! 3MP1?A33 $
i# 6=T =?T =511 autoTincr!m!nt2
firstTnam! B07,07$@E( #!fault =5112
lastTnam! B07,07$@E( #!fault =5112
salary 6=T #!fault =5112
P76M07A Y3A $i#(
(*
Create Mapping Confguration File:
This step is to create a mapping file that instructs Hibernate how to map the defined class or classes
to the database tables.
MAT SOFT
JAVA REFERENCE GUIDE
622
NS:ml v!rsion9)C.E) !nco#ing9)utf;J)S.
NG4?,TAP3 hib!rnat!;mapping P5L16,
);//ib!rnat!/ib!rnat! Mapping 4T4//3=)
)http-//www.hib!rnat!.org/#t#/hib!rnat!;mapping;D.E.#t#).
Nhib!rnat!;mapping.
Nclass nam!9)3mploy!!) tabl!9)3MP1?A33).
Nm!ta attribut!9)class;#!scription).
This class contains th! !mploy!! #!tail.
N/m!ta.
Ni# nam!9)i#) typ!9)int) column9)i#).
Ng!n!rator class9)nativ!)/.
N/i#.
Nprop!rty nam!9)first=am!) column9)firstTnam!) typ!9)string)/.
Nprop!rty nam!9)last=am!) column9)lastTnam!) typ!9)string)/.
Nprop!rty nam!9)salary) column9)salary) typ!9)int)/.
N/class.
N/hib!rnat!;mapping.
You should save the mapping document in a file with the format <classname>.hbm.xml. We saved our
mapping document in the file Employee.hbm.xml. Let us see little detail about the mapping document:
The mapping document is an XML document having <hibernate-mapping> as the root element
which contains all the <class> elements.
The Wc$assX elements are used to define specific mappings from a Java classes to the
database tables. The Java class name is specified using the name attribute of the class
element and the database table name is specified using the ta"$e attribute.
The WmetaX element is optional element and can be used to create the class description.
The WidX element maps the unique ID attribute in class to the primary key of the database
table. The name attribute of the id element refers to the property in the class and
the co$mn attribute refers to the column in the database table. The type attribute holds the
hibernate mapping type, this mapping types will convert from Java to SQL data type.
The WgeneratorX element within the id element is used to automatically generate the
primary key values. Set the c$ass attribute of the generator element is set to native to let
hibernate pick up either identity< se;ence or hi$o algorithm to create primary key
depending upon the capabilities of the underlying database.
The WpropertyX element is used to map a Java class property to a column in the database
table. The name attribute of the element refers to the property in the class and
the co$mn attribute refers to the column in the database table. The type attribute holds the
hibernate mapping type, this mapping types will convert from Java to SQL data type.
There are other attributes and elements available which will be used in a mapping document and I
would try to cover as many as possible while discussing other Hibernate related topics.
MAT SOFT
JAVA REFERENCE GUIDE
623
Create Application Class:
Finally, we will create our application class with the main() method to run the application. We will use
this application to save few Employee's records and then we will apply CRUD operations on those
records.
import java.util.1ist*
import java.util.4at!*
import java.util.6t!rator*

import org.hib!rnat!.ib!rnat!3:c!ption*
import org.hib!rnat!.%!ssion*
import org.hib!rnat!.Transaction*
import org.hib!rnat!.%!ssionFactory*
import org.hib!rnat!.cfg.,onfiguration*
public class Manag!3mploy!! {
privat! static %!ssionFactory factory*
public static voi# main$%tring&' args( {
try{
factory 9 n!w ,onfiguration$(.configur!$(.buil#%!ssionFactory$(*
+catch $Throwabl! !:( {
%yst!m.!rr.println$)Fail!# to cr!at! s!ssionFactory obj!ct.) >
!:(*
throw n!w 3:c!ption6n6nitiali/!r3rror$!:(*
+
Manag!3mploy!! M3 9 n!w Manag!3mploy!!$(*
/* 0## f!w !mploy!! r!cor#s in #atabas! */
6nt!g!r !mp64C 9 M3.a##3mploy!!$)Vara)2 )0li)2 CEEE(*
6nt!g!r !mp64@ 9 M3.a##3mploy!!$)4aisy)2 )4as)2 HEEE(*
6nt!g!r !mp64D 9 M3.a##3mploy!!$)John)2 )Paul)2 CEEEE(*
/* 1ist #own all th! !mploy!!s */
M3.list3mploy!!s$(*
/* 5p#at! !mploy!!'s r!cor#s */
M3.up#at!3mploy!!$!mp64C2 HEEE(*
/* 4!l!t! an !mploy!! from th! #atabas! */
M3.#!l!t!3mploy!!$!mp64@(*
/* 1ist #own n!w list of th! !mploy!!s */
M3.list3mploy!!s$(*
+
/* M!tho# to ,730T3 an !mploy!! in th! #atabas! */
public 6nt!g!r a##3mploy!!$%tring fnam!2 %tring lnam!2 int salary({
%!ssion s!ssion 9 factory.op!n%!ssion$(*
Transaction t: 9 null*
6nt!g!r !mploy!!64 9 null*
try{
t: 9 s!ssion.b!ginTransaction$(*
3mploy!! !mploy!! 9 n!w 3mploy!!$fnam!2 lnam!2 salary(*
!mploy!!64 9 $6nt!g!r( s!ssion.sav!$!mploy!!(*
MAT SOFT
JAVA REFERENCE GUIDE
624
t:.commit$(*
+catch $ib!rnat!3:c!ption !( {
if $t:G9null( t:.rollbac<$(*
!.print%tac<Trac!$(*
+finally {
s!ssion.clos!$(*
+
r!turn !mploy!!64*
+
/* M!tho# to 7304 all th! !mploy!!s */
public voi# list3mploy!!s$ ({
%!ssion s!ssion 9 factory.op!n%!ssion$(*
Transaction t: 9 null*
try{
t: 9 s!ssion.b!ginTransaction$(*
1ist !mploy!!s 9 s!ssion.cr!at!Xu!ry$)F7?M 3mploy!!)(.list$(*
for $6t!rator it!rator 9
!mploy!!s.it!rator$(* it!rator.has=!:t$(*({
3mploy!! !mploy!! 9 $3mploy!!( it!rator.n!:t$(*
%yst!m.out.print$)First =am!- ) > !mploy!!.g!tFirst=am!$((*
%yst!m.out.print$) 1ast =am!- ) > !mploy!!.g!t1ast=am!$((*
%yst!m.out.println$) %alary- ) > !mploy!!.g!t%alary$((*
+
t:.commit$(*
+catch $ib!rnat!3:c!ption !( {
if $t:G9null( t:.rollbac<$(*
!.print%tac<Trac!$(*
+finally {
s!ssion.clos!$(*
+
+
/* M!tho# to 5P40T3 salary for an !mploy!! */
public voi# up#at!3mploy!!$6nt!g!r 3mploy!!642 int salary ({
%!ssion s!ssion 9 factory.op!n%!ssion$(*
Transaction t: 9 null*
try{
t: 9 s!ssion.b!ginTransaction$(*
3mploy!! !mploy!! 9
$3mploy!!(s!ssion.g!t$3mploy!!.class2 3mploy!!64(*
!mploy!!.s!t%alary$ salary (*
s!ssion.up#at!$!mploy!!(*
t:.commit$(*
+catch $ib!rnat!3:c!ption !( {
if $t:G9null( t:.rollbac<$(*
!.print%tac<Trac!$(*
+finally {
s!ssion.clos!$(*
+
+
/* M!tho# to 4313T3 an !mploy!! from th! r!cor#s */
public voi# #!l!t!3mploy!!$6nt!g!r 3mploy!!64({
%!ssion s!ssion 9 factory.op!n%!ssion$(*
Transaction t: 9 null*
try{
t: 9 s!ssion.b!ginTransaction$(*
MAT SOFT
JAVA REFERENCE GUIDE
625
3mploy!! !mploy!! 9
$3mploy!!(s!ssion.g!t$3mploy!!.class2 3mploy!!64(*
s!ssion.#!l!t!$!mploy!!(*
t:.commit$(*
+catch $ib!rnat!3:c!ption !( {
if $t:G9null( t:.rollbac<$(*
!.print%tac<Trac!$(*
+finally {
s!ssion.clos!$(*
+
+
+
Compilation and Execution:
Here are the steps to compile and run the above mentioned application. Make sure you have set PATH
and CLASSPATH appropriately before proceeding for the compilation and execution.
1. Create hibernate.cfg.xml configuration file as explained in configuration chapter.
2. Create Employee.hbm.xml mapping file as shown above.
3. Create Employee.java source file as shown above and compile it.
4. Create ManageEmployee.java source file as shown above and compile it.
5. Execute ManageEmployee binary to run the program.
You would get following result, and records would be created in EMPLOYEE table.
Ujava Manag!3mploy!!
.......B076?5% 1?8 M3%%083% "611 46%P10A 373........
First =am!- Vara 1ast =am!- 0li %alary- CEEE
First =am!- 4aisy 1ast =am!- 4as %alary- HEEE
First =am!- John 1ast =am!- Paul %alary- CEEEE
First =am!- Vara 1ast =am!- 0li %alary- HEEE
First =am!- John 1ast =am!- Paul %alary- CEEEE
If you check your EMPLOYEE table, it should have following records:
mysPl. s!l!ct * from 3MP1?A33*
>;;;;>;;;;;;;;;;;;>;;;;;;;;;;;>;;;;;;;;>
a i# a firstTnam! a lastTnam! a salary a
>;;;;>;;;;;;;;;;;;>;;;;;;;;;;;>;;;;;;;;>
a @K a Vara a 0li a HEEE a
a DC a John a Paul a CEEEE a
>;;;;>;;;;;;;;;;;;>;;;;;;;;;;;>;;;;;;;;>
@ rows in s!t $E.EE s!c
mysPl.
MAT SOFT
JAVA REFERENCE GUIDE
626
OR;MAPPIN
So far we have seen very basic O/R mapping using hibernate but there are three most important
mapping topics which we have to learn in detail. These are the mapping of collections, the mapping of
associations between entity classes and Component Mappings.
Collections Mappings:
If an entity or class has collection of values for a particular variable, then we can map those values
using any one of the collection interfaces available in java. Hibernate can persist instances
of #ava1ti$1Map< #ava1ti$1Set< #ava1ti$1SortedMap< #ava1ti$1SortedSet< #ava1ti$10ist, and
any array of persistent entities or values.
Co$$ection type Mapping and )escription
java.util.Set This is mapped with a <set> element and initialized with java.util.HashSet
java.util.SortedSet This is mapped with a <set> element and initialized with java.util.TreeSet.
The sort attribute can be set to either a comparator or natural ordering.
java.util.List This is mapped with a <list> element and initialized with java.util.ArrayList
java.util.Collection This is mapped with a <bag> or <ibag> element and initialized with
java.util.ArrayList
java.util.Map This is mapped with a <map> element and initialized with java.util.HashMap
java.util.SortedMap This is mapped with a <map> element and initialized with java.util.TreeMap.
The sort attribute can be set to either a comparator or natural ordering.
Arrays are supported by Hibernate with <primitive-array> for Java primitive value types and <array>
for everything else. However, they are rarely used so I'm not going to discuss them in this tutorial.
If you want to map a user defined collection interfaces which is not directly supported by Hibernate,
you need to tell Hibernate about the semantics of your custom collections which is not very easy and
not recommend to be used.
Association Mappings:
The mapping of associations between entity classes and the relationships between tables is the soul of
ORM. Following are the four ways in which the cardinality of the relationship between the objects can
be expressed. An association mapping can be unidirectional as well as bidirectional.
Mapping type )escription
MAT SOFT
JAVA REFERENCE GUIDE
627
Many-to-One Mapping many-to-one relationship using Hibernate
One-to-One Mapping one-to-one relationship using Hibernate
One-to-Many Mapping one-to-many relationship using Hibernate
Many-to-Many Mapping many-to-many relationship using Hibernate
Component Mappings:
It is very much possible that an Entity class can have a reference to another class as a member
variable. If the referred class does not have it's own life cycle and completely depends on the life cycle
of the owning entity class, then the referred class hence therefore is called as the Component class.
The mapping of Collection of Components is also possible in a similar way just as the mapping of
regular Collections with minor configuration differences. We will see these two mappings in detail with
examples.
Mapping type )escription
Component Mappings Mapping for a class having a reference to another class as a member
variable.
ANNOTATIONS
So far you have seen how Hibernate uses XML mapping file for the transformation of data from POJO
to database tables and vice versa. Hibernate annotations is the newest way to define mappings
without a use of XML file. You can use annotations in addition to or as a replacement of XML mapping
metadata.
Hibernate Annotations is the powerful way to provide the metadata for the Object and Relational Table
mapping. All the metadata is clubbed into the POJO java file along with the code this helps the user to
understand the table structure and POJO simultaneously during the development.
If you going to make your application portable to other EJB 3 compliant ORM applications, you must
use annotations to represent the mapping information but still if you want greater flexibility then you
should go with XML-based mappings.
Environment Setup for Hibernate Annotation
First of all you would have to make sure that you are using JDK 5.0 otherwise you need to upgrade
your JDK to JDK 5.0 to take advantage of the native support for annotations.
Second, you will need to install the Hibernate 3.x annotations distribution package, available from the
sourceforge: (Download Hibernate Annotation) and copy hi"ernate&annotations1#ar<
MAT SOFT
JAVA REFERENCE GUIDE
628
$i"Khi"ernate&comons&annotations1#ar and $i"Ke#"E&persistence1#ar from the Hibernate
Annotations distribution to your CLASSPATH
Annotated Class Example:
As I mentioned above while working with Hibernate Annotation all the metadata is clubbed into the
POJO java file along with the code this helps the user to understand the table structure and POJO
simultaneously during the development.
Consider we are going to use following EMPLOYEE table to store our objects:
cr!at! tabl! 3MP1?A33 $
i# 6=T =?T =511 autoTincr!m!nt2
firstTnam! B07,07$@E( #!fault =5112
lastTnam! B07,07$@E( #!fault =5112
salary 6=T #!fault =5112
P76M07A Y3A $i#(
(*
Following is the mapping of Employee class with annotations to map objects with the defined
EMPLOYEE table:
import java:.p!rsist!nc!.**
\3ntity
\Tabl!$nam! 9 )3MP1?A33)(
public class 3mploy!! {
\6# \8!n!rat!#Balu!
\,olumn$nam! 9 )i#)(
privat! int i#*
\,olumn$nam! 9 )firstTnam!)(
privat! %tring first=am!*
\,olumn$nam! 9 )lastTnam!)(
privat! %tring last=am!*
\,olumn$nam! 9 )salary)(
privat! int salary*
public 3mploy!!$( {+
public int g!t6#$( {
r!turn i#*
+
public voi# s!t6#$ int i# ( {
this.i# 9 i#*
+
public %tring g!tFirst=am!$( {
r!turn first=am!*
+
public voi# s!tFirst=am!$ %tring firstTnam! ( {
this.first=am! 9 firstTnam!*
MAT SOFT
JAVA REFERENCE GUIDE
629
+
public %tring g!t1ast=am!$( {
r!turn last=am!*
+
public voi# s!t1ast=am!$ %tring lastTnam! ( {
this.last=am! 9 lastTnam!*
+
public int g!t%alary$( {
r!turn salary*
+
public voi# s!t%alary$ int salary ( {
this.salary 9 salary*
+
+
Hibernate detects that the @Id annotation is on a field and assumes that it should access properties
on an object directly through fields at runtime. If you placed the @Id annotation on the getId()
method, you would enable access to properties through getter and setter methods by default. Hence,
all other annotations are also placed on either fields or getter methods, following the selected
strategy. Following section will explain the annotations used in the above class.
L7ntity %nnotation:
The EJB 3 standard annotations are contained in the #avax1persistence package, so we import this
package as the first step. Second we used the L7ntity annotation to the Employee class which marks
this class as an entity bean, so it must have a no-argument constructor that is visible with at least
protected scope.
LTa"$e %nnotation:
The @Table annotation allows you to specify the details of the table that will be used to persist the
entity in the database.
The @Table annotation provides four attributes, allowing you to override the name of the table, its
catalogue, and its schema, and enforce unique constraints on columns in the table. For now we are
using just table name which is EMPLOYEE.
LId and L?enerated*a$e %nnotations:
Each entity bean will have a primary key, which you annotate on the class with the LIdannotation.
The primary key can be a single field or a combination of multiple fields depending on your table
structure.
By default, the @Id annotation will automatically determine the most appropriate primary key
generation strategy to be used but you can override this by applying
the L?enerated*a$eannotation which takes two parameters strategy and generator which I'm
not going to discuss here, so let us use only default the default key generation strategy. Letting
Hibernate determine which generator type to use makes your code portable between different
databases.
MAT SOFT
JAVA REFERENCE GUIDE
630
LCo$mn %nnotation:
The @Column annotation is used to specify the details of the column to which a field or property will
be mapped. You can use column annotation with the following most commonly used attributes:
name attribute permits the name of the column to be explicitly specified.
$ength attribute permits the size of the column used to map a value particularly for a String
value.
n$$a"$e attribute permits the column to be marked NOT NULL when the schema is generated.
ni;e attribute permits the column to be marked as containing only unique values.
Create Application Class:
Finally, we will create our application class with the main() method to run the application. We will use
this application to save few Employee's records and then we will apply CRUD operations on those
records.
import java.util.1ist*
import java.util.4at!*
import java.util.6t!rator*

import org.hib!rnat!.ib!rnat!3:c!ption*
import org.hib!rnat!.%!ssion*
import org.hib!rnat!.Transaction*
import org.hib!rnat!.cfg.0nnotation,onfiguration*
import org.hib!rnat!.%!ssionFactory*
import org.hib!rnat!.cfg.,onfiguration*
public class Manag!3mploy!! {
privat! static %!ssionFactory factory*
public static voi# main$%tring&' args( {
try{
factory 9 n!w 0nnotation,onfiguration$(.
configur!$(.
//a##Pac<ag!$)com.:y/)( //a## pac<ag! if us!#.
a##0nnotat!#,lass$3mploy!!.class(.
buil#%!ssionFactory$(*
+catch $Throwabl! !:( {
%yst!m.!rr.println$)Fail!# to cr!at! s!ssionFactory obj!ct.) >
!:(*
throw n!w 3:c!ption6n6nitiali/!r3rror$!:(*
+
Manag!3mploy!! M3 9 n!w Manag!3mploy!!$(*
/* 0## f!w !mploy!! r!cor#s in #atabas! */
6nt!g!r !mp64C 9 M3.a##3mploy!!$)Vara)2 )0li)2 CEEE(*
6nt!g!r !mp64@ 9 M3.a##3mploy!!$)4aisy)2 )4as)2 HEEE(*
6nt!g!r !mp64D 9 M3.a##3mploy!!$)John)2 )Paul)2 CEEEE(*
/* 1ist #own all th! !mploy!!s */
MAT SOFT
JAVA REFERENCE GUIDE
631
M3.list3mploy!!s$(*
/* 5p#at! !mploy!!'s r!cor#s */
M3.up#at!3mploy!!$!mp64C2 HEEE(*
/* 4!l!t! an !mploy!! from th! #atabas! */
M3.#!l!t!3mploy!!$!mp64@(*
/* 1ist #own n!w list of th! !mploy!!s */
M3.list3mploy!!s$(*
+
/* M!tho# to ,730T3 an !mploy!! in th! #atabas! */
public 6nt!g!r a##3mploy!!$%tring fnam!2 %tring lnam!2 int salary({
%!ssion s!ssion 9 factory.op!n%!ssion$(*
Transaction t: 9 null*
6nt!g!r !mploy!!64 9 null*
try{
t: 9 s!ssion.b!ginTransaction$(*
3mploy!! !mploy!! 9 n!w 3mploy!!$(*
!mploy!!.s!tFirst=am!$fnam!(*
!mploy!!.s!t1ast=am!$lnam!(*
!mploy!!.s!t%alary$salary(*
!mploy!!64 9 $6nt!g!r( s!ssion.sav!$!mploy!!(*
t:.commit$(*
+catch $ib!rnat!3:c!ption !( {
if $t:G9null( t:.rollbac<$(*
!.print%tac<Trac!$(*
+finally {
s!ssion.clos!$(*
+
r!turn !mploy!!64*
+
/* M!tho# to 7304 all th! !mploy!!s */
public voi# list3mploy!!s$ ({
%!ssion s!ssion 9 factory.op!n%!ssion$(*
Transaction t: 9 null*
try{
t: 9 s!ssion.b!ginTransaction$(*
1ist !mploy!!s 9 s!ssion.cr!at!Xu!ry$)F7?M 3mploy!!)(.list$(*
for $6t!rator it!rator 9
!mploy!!s.it!rator$(* it!rator.has=!:t$(*({
3mploy!! !mploy!! 9 $3mploy!!( it!rator.n!:t$(*
%yst!m.out.print$)First =am!- ) > !mploy!!.g!tFirst=am!$((*
%yst!m.out.print$) 1ast =am!- ) > !mploy!!.g!t1ast=am!$((*
%yst!m.out.println$) %alary- ) > !mploy!!.g!t%alary$((*
+
t:.commit$(*
+catch $ib!rnat!3:c!ption !( {
if $t:G9null( t:.rollbac<$(*
!.print%tac<Trac!$(*
+finally {
s!ssion.clos!$(*
+
+
/* M!tho# to 5P40T3 salary for an !mploy!! */
MAT SOFT
JAVA REFERENCE GUIDE
632
public voi# up#at!3mploy!!$6nt!g!r 3mploy!!642 int salary ({
%!ssion s!ssion 9 factory.op!n%!ssion$(*
Transaction t: 9 null*
try{
t: 9 s!ssion.b!ginTransaction$(*
3mploy!! !mploy!! 9
$3mploy!!(s!ssion.g!t$3mploy!!.class2 3mploy!!64(*
!mploy!!.s!t%alary$ salary (*
s!ssion.up#at!$!mploy!!(*
t:.commit$(*
+catch $ib!rnat!3:c!ption !( {
if $t:G9null( t:.rollbac<$(*
!.print%tac<Trac!$(*
+finally {
s!ssion.clos!$(*
+
+
/* M!tho# to 4313T3 an !mploy!! from th! r!cor#s */
public voi# #!l!t!3mploy!!$6nt!g!r 3mploy!!64({
%!ssion s!ssion 9 factory.op!n%!ssion$(*
Transaction t: 9 null*
try{
t: 9 s!ssion.b!ginTransaction$(*
3mploy!! !mploy!! 9
$3mploy!!(s!ssion.g!t$3mploy!!.class2 3mploy!!64(*
s!ssion.#!l!t!$!mploy!!(*
t:.commit$(*
+catch $ib!rnat!3:c!ption !( {
if $t:G9null( t:.rollbac<$(*
!.print%tac<Trac!$(*
+finally {
s!ssion.clos!$(*
+
+
+
Database Confguration:
Now let us create hi"ernate1cfg1xm$ configuration file to define database related parameters. This
time we are not going to mentioned any *.hbm.xml mapping file in this configuration file.
NS:ml v!rsion9)C.E) !nco#ing9)utf;J)S.
NG4?,TAP3 hib!rnat!;configuration %A%T3M
)http-//www.hib!rnat!.org/#t#/hib!rnat!;configuration;D.E.#t#).
Nhib!rnat!;configuration.
Ns!ssion;factory.
Nprop!rty nam!9)hib!rnat!.#ial!ct).
org.hib!rnat!.#ial!ct.My%X14ial!ct
N/prop!rty.
Nprop!rty nam!9)hib!rnat!.conn!ction.#riv!rTclass).
com.mysPl.j#bc.4riv!r
N/prop!rty.
MAT SOFT
JAVA REFERENCE GUIDE
633
NG;; 0ssum! stu#!nts is th! #atabas! nam! ;;.
Nprop!rty nam!9)hib!rnat!.conn!ction.url).
j#bc-mysPl-//localhost/t!st
N/prop!rty.
Nprop!rty nam!9)hib!rnat!.conn!ction.us!rnam!).
root
N/prop!rty.
Nprop!rty nam!9)hib!rnat!.conn!ction.passwor#).
cohon#ob
N/prop!rty.
N/s!ssion;factory.
N/hib!rnat!;configuration.
Compilation and Execution:
Here are the steps to compile and run the above mentioned application. Make sure you have set PATH
and CLASSPATH appropriately before proceeding for the compilation and execution.
1. Delete Employee.hbm.xml mapping file from the path.
2. Create Employee.java source file as shown above and compile it.
3. Create ManageEmployee.java source file as shown above and compile it.
4. Execute ManageEmployee binary to run the program.
You would get following result, and records would be created in EMPLOYEE table.
Ujava Manag!3mploy!!
.......B076?5% 1?8 M3%%083% "611 46%P10A 373........
First =am!- Vara 1ast =am!- 0li %alary- CEEE
First =am!- 4aisy 1ast =am!- 4as %alary- HEEE
First =am!- John 1ast =am!- Paul %alary- CEEEE
First =am!- Vara 1ast =am!- 0li %alary- HEEE
First =am!- John 1ast =am!- Paul %alary- CEEEE
If you check your EMPLOYEE table, it should have following records:
mysPl. s!l!ct * from 3MP1?A33*
>;;;;>;;;;;;;;;;;;>;;;;;;;;;;;>;;;;;;;;>
a i# a firstTnam! a lastTnam! a salary a
>;;;;>;;;;;;;;;;;;>;;;;;;;;;;;>;;;;;;;;>
a @K a Vara a 0li a HEEE a
a DC a John a Paul a CEEEE a
>;;;;>;;;;;;;;;;;;>;;;;;;;;;;;>;;;;;;;;>
@ rows in s!t $E.EE s!c
mysPl.
MAT SOFT
JAVA REFERENCE GUIDE
634
J?ER! LAN?AE
Hibernate Query Language (HQL) is an object-oriented query language, similar to SQL, but instead of
operating on tables and columns, HQL works with persistent objects and their properties. HQL queries
are translated by Hibernate into conventional SQL queries which in turns perform action on database.
Although you can use SQL statements directly with Hibernate using Native SQL but I would
recommend to use HQL whenever possible to avoid database portability hassles, and to take
advantage of Hibernate's SQL generation and caching strategies.
Keywords like SELECT , FROM and WHERE etc. are not case sensitive but properties like table and
column names are case sensitive in HQL.
FROM Clause
You will use +'!M clause if you want to load a complete persistent objects into memory. Following is
the simple syntax of using FROM clause:
%tring hPl 9 )F7?M 3mploy!!)*
Xu!ry Pu!ry 9 s!ssion.cr!at!Xu!ry$hPl(*
1ist r!sults 9 Pu!ry.list$(*
If you need to fully qualify a class name in HQL, just specify the package and class name as follows:
%tring hPl 9 )F7?M com.hib!rnat!boo<.crit!ria.3mploy!!)*
Xu!ry Pu!ry 9 s!ssion.cr!at!Xu!ry$hPl(*
1ist r!sults 9 Pu!ry.list$(*
AS Clause
The %S clause can be used to assign aliases to the classes in your HQL queries, specially when you
have long queries. For instance, our previous simple example would be the following:
%tring hPl 9 )F7?M 3mploy!! 0% 3)*
Xu!ry Pu!ry 9 s!ssion.cr!at!Xu!ry$hPl(*
1ist r!sults 9 Pu!ry.list$(*
The %S keyword is optional and you can also specify the alias directly after the class name, as follows:
%tring hPl 9 )F7?M 3mploy!! 3)*
Xu!ry Pu!ry 9 s!ssion.cr!at!Xu!ry$hPl(*
1ist r!sults 9 Pu!ry.list$(*
MAT SOFT
JAVA REFERENCE GUIDE
635
SELECT Clause
The S707CT clause provides more control over the result set than the from clause. If you want to
obtain few properties of objects instead of the complete object, use the SELECT clause. Following is
the simple syntax of using SELECT clause to get just first_name field of the Employee object:
%tring hPl 9 )%313,T 3.first=am! F7?M 3mploy!! 3)*
Xu!ry Pu!ry 9 s!ssion.cr!at!Xu!ry$hPl(*
1ist r!sults 9 Pu!ry.list$(*
It is notable here that 7mp$oyee1firstName is a property of Employee object rather than a field of
the EMPLOYEE table.
WHERE Clause
If you want to narrow the specific objects that are returned from storage, you use the WHERE clause.
Following is the simple syntax of using WHERE clause:
%tring hPl 9 )F7?M 3mploy!! 3 "373 3.i# 9 CE)*
Xu!ry Pu!ry 9 s!ssion.cr!at!Xu!ry$hPl(*
1ist r!sults 9 Pu!ry.list$(*
ORDER BY Clause
To sort your HQL query's results, you will need to use the !')7' BA clause. You can order the results
by any property on the objects in the result set either ascending (ASC) or descending (DESC).
Following is the simple syntax of using ORDER BY clause:
%tring hPl 9 )F7?M 3mploy!! 3 "373 3.i# . CE ?7437 LA 3.salary 43%,)*
Xu!ry Pu!ry 9 s!ssion.cr!at!Xu!ry$hPl(*
1ist r!sults 9 Pu!ry.list$(*
If you wanted to sort by more than one property, you would just add the additional properties to the
end of the order by clause, separated by commas as follows:
%tring hPl 9 )F7?M 3mploy!! 3 "373 3.i# . CE ) >
)?7437 LA 3.first=am! 43%,2 3.salary 43%, )*
Xu!ry Pu!ry 9 s!ssion.cr!at!Xu!ry$hPl(*
1ist r!sults 9 Pu!ry.list$(*
GROUP BY Clause
This clause lets Hibernate pull information from the database and group it based on a value of an
attribute and, typically, use the result to include an aggregate value. Following is the simple syntax of
using GROUP BY clause:
MAT SOFT
JAVA REFERENCE GUIDE
636
%tring hPl 9 )%313,T %5M$3.salary(2 3.firt=am! F7?M 3mploy!! 3 ) >
)87?5P LA 3.first=am!)*
Xu!ry Pu!ry 9 s!ssion.cr!at!Xu!ry$hPl(*
1ist r!sults 9 Pu!ry.list$(*
Using Named Paramters
Hibernate supports named parameters in its HQL queries. This makes writing HQL queries that accept
input from the user easy and you do not have to defend against SQL injection attacks. Following is the
simple syntax of using named parameters:
%tring hPl 9 )F7?M 3mploy!! 3 "373 3.i# 9 -!mploy!!Ti#)*
Xu!ry Pu!ry 9 s!ssion.cr!at!Xu!ry$hPl(*
Pu!ry.s!tParam!t!r$)!mploy!!Ti#)2CE(*
1ist r!sults 9 Pu!ry.list$(*
UPDATE Clause
Bulk updates are new to HQL with Hibernate 3, and deletes work differently in Hibernate 3 than they
did in Hibernate 2. The Query interface now contains a method called executeUpdate() for executing
HQL UPDATE or DELETE statements.
The BP)%T7 clause can be used to update one or more properties of an one or more objects.
Following is the simple syntax of using UPDATE clause:
%tring hPl 9 )5P40T3 3mploy!! s!t salary 9 -salary ) >
)"373 i# 9 -!mploy!!Ti#)*
Xu!ry Pu!ry 9 s!ssion.cr!at!Xu!ry$hPl(*
Pu!ry.s!tParam!t!r$)salary)2 CEEE(*
Pu!ry.s!tParam!t!r$)!mploy!!Ti#)2 CE(*
int r!sult 9 Pu!ry.!:!cut!5p#at!$(*
%yst!m.out.println$)7ows aff!ct!#- ) > r!sult(*
DELETE Clause
The )707T7 clause can be used to delete one or more objects. Following is the simple syntax of using
DELETE clause:
%tring hPl 9 )4313T3 F7?M 3mploy!! ) >
)"373 i# 9 -!mploy!!Ti#)*
Xu!ry Pu!ry 9 s!ssion.cr!at!Xu!ry$hPl(*
Pu!ry.s!tParam!t!r$)!mploy!!Ti#)2 CE(*
int r!sult 9 Pu!ry.!:!cut!5p#at!$(*
%yst!m.out.println$)7ows aff!ct!#- ) > r!sult(*
MAT SOFT
JAVA REFERENCE GUIDE
637
INSERT Clause
HQL supports INS7'T INT! clause only where records can be inserted from one object to another
object. Following is the simple syntax of using INSERT INTO clause:
%tring hPl 9 )6=%37T 6=T? 3mploy!!$first=am!2 last=am!2 salary() >
)%313,T first=am!2 last=am!2 salary F7?M ol#T!mploy!!)*
Xu!ry Pu!ry 9 s!ssion.cr!at!Xu!ry$hPl(*
int r!sult 9 Pu!ry.!:!cut!5p#at!$(*
%yst!m.out.println$)7ows aff!ct!#- ) > r!sult(*
Aggregate Methods
HQL supports a range of aggregate methods, similar to SQL. They work the same way in HQL as in
SQL and following is the list of the available functions:
S1N1 +nctions )escription
1 avg(property name) The average of a property's value
2 count(property name or *) The number of times a property occurs in the results
3 max(property name) The maximum value of the property values
4 min(property name) The minimum value of the property values
5 sum(property name) The sum total of the property values
The distinct keyword only counts the unique values in the row set. The following query will return
only unique count:
%tring hPl 9 )%313,T count$#istinct 3.first=am!( F7?M 3mploy!! 3)*
Xu!ry Pu!ry 9 s!ssion.cr!at!Xu!ry$hPl(*
1ist r!sults 9 Pu!ry.list$(*
Pagination using Query
There are two methods of the Query interface for pagination.
S1N1 Method : )escription
1 Jery set+irst'es$t,int startPosition/
This method takes an integer that represents the first row in your result set, starting with row 0.
MAT SOFT
JAVA REFERENCE GUIDE
638
2 Jery setMax'es$ts,int max'es$t/
This method tells Hibernate to retrieve a fixed number max'es$ts of objects.
Using above two methods together, we can construct a paging component in our web or Swing
application. Following is the example which you can extend to fetch 10 rows at a time:
%tring hPl 9 )F7?M 3mploy!!)*
Xu!ry Pu!ry 9 s!ssion.cr!at!Xu!ry$hPl(*
Pu!ry.s!tFirst7!sult$C(*
Pu!ry.s!tMa:7!sults$CE(*
1ist r!sults 9 Pu!ry.list$(*
CREITERIA J?ERIES
Hibernate provides alternate ways of manipulating objects and in turn data available in RDBMS tables.
One of the methods is Criteria API which allows you to build up a criteria query object
programmatically where you can apply filtration rules and logical conditions.
The Hibernate Session interface provides createCriteria,/ method which can be used to create
a Criteria object that returns instances of the persistence object's class when your application
executes a criteria query.
Following is the simplest example of a criteria query is one which will simply return every object that
corresponds to the Employee class.
,rit!ria cr 9 s!ssion.cr!at!,rit!ria$3mploy!!.class(*
1ist r!sults 9 cr.list$(*
Restrictions with Criteria:
You can use add,/ method available for Criteria object to add restriction for a criteria query.
Following is the example to add a restriction to return the records with salary is equal to 2000:
,rit!ria cr 9 s!ssion.cr!at!,rit!ria$3mploy!!.class(*
cr.a##$7!strictions.!P$)salary)2 @EEE((*
1ist r!sults 9 cr.list$(*
Following are the few more examples covering different scenarios and can be used as per
requirement:
,rit!ria cr 9 s!ssion.cr!at!,rit!ria$3mploy!!.class(*
// To g!t r!cor#s having salary mor! than @EEE
cr.a##$7!strictions.gt$)salary)2 @EEE((*
MAT SOFT
JAVA REFERENCE GUIDE
639
// To g!t r!cor#s having salary l!ss than @EEE
cr.a##$7!strictions.lt$)salary)2 @EEE((*
// To g!t r!cor#s having fist=am! starting with /ara
cr.a##$7!strictions.li<!$)first=am!)2 )/araW)((*
// ,as! s!nsitiv! form of th! abov! r!striction.
cr.a##$7!strictions.ili<!$)first=am!)2 )/araW)((*
// To g!t r!cor#s having salary in b!tw!!n CEEE an# @EEE
cr.a##$7!strictions.b!tw!!n$)salary)2 CEEE2 @EEE((*
// To ch!c< if th! giv!n prop!rty is null
cr.a##$7!strictions.is=ull$)salary)((*
// To ch!c< if th! giv!n prop!rty is not null
cr.a##$7!strictions.is=ot=ull$)salary)((*
// To ch!c< if th! giv!n prop!rty is !mpty
cr.a##$7!strictions.is3mpty$)salary)((*
// To ch!c< if th! giv!n prop!rty is not !mpty
cr.a##$7!strictions.is=ot3mpty$)salary)((*
You can create AND or OR conditions using LogicalExpression restrictions as follows:
,rit!ria cr 9 s!ssion.cr!at!,rit!ria$3mploy!!.class(*
,rit!rion salary 9 7!strictions.gt$)salary)2 @EEE(*
,rit!rion nam! 9 7!strictions.ili<!$)first=nam!)2)/araW)(*
// To g!t r!cor#s matching with ?7 con#istions
1ogical3:pr!ssion or3:p 9 7!strictions.or$salary2 nam!(*
cr.a##$ or3:p (*
// To g!t r!cor#s matching with 0=4 con#istions
1ogical3:pr!ssion an#3:p 9 7!strictions.an#$salary2 nam!(*
cr.a##$ an#3:p (*
1ist r!sults 9 cr.list$(*
Though all the above conditions can be used directly with HQL as explained in previous tutorial.
Pagination using Criteria:
There are two methods of the Criteria interface for pagination.
S1N1 Method : )escription
MAT SOFT
JAVA REFERENCE GUIDE
640
1 p"$ic Criteria set+irst'es$t,int first'es$t/
This method takes an integer that represents the first row in your result set, starting with row 0.
2 p"$ic Criteria setMax'es$ts,int max'es$ts/
This method tells Hibernate to retrieve a fixed number max'es$ts of objects.
Using above two methods together, we can construct a paging component in our web or Swing
application. Following is the example which you can extend to fetch 10 rows at a time:
,rit!ria cr 9 s!ssion.cr!at!,rit!ria$3mploy!!.class(*
cr.s!tFirst7!sult$C(*
cr.s!tMa:7!sults$CE(*
1ist r!sults 9 cr.list$(*
Sorting the Results:
The Criteria API provides the org1hi"ernate1criterion1!rder class to sort your result set in either
ascending or descending order, according to one of your object's properties. This example
demonstrates how you would use the Order class to sort the result set:
,rit!ria cr 9 s!ssion.cr!at!,rit!ria$3mploy!!.class(*
// To g!t r!cor#s having salary mor! than @EEE
cr.a##$7!strictions.gt$)salary)2 @EEE((*
// To sort r!cor#s in #!sc!ning or#!r
crit.a##?r#!r$?r#!r.#!sc$)salary)((*
// To sort r!cor#s in asc!n#ing or#!r
crit.a##?r#!r$?r#!r.asc$)salary)((*
1ist r!sults 9 cr.list$(*
Projections & Aggregations:
The Criteria API provides the org1hi"ernate1criterion1Pro#ections class which can be used to get
average, maximum or minimum of the property values. The Projections class is similar to the
Restrictions class in that it provides several static factory methods for obtaining Pro#ectioninstances.
Following are the few examples covering different scenarios and can be used as per requirement:
,rit!ria cr 9 s!ssion.cr!at!,rit!ria$3mploy!!.class(*
// To g!t total row count.
cr.s!tProj!ction$Proj!ctions.row,ount$((*
// To g!t av!rag! of a prop!rty.
cr.s!tProj!ction$Proj!ctions.avg$)salary)((*
MAT SOFT
JAVA REFERENCE GUIDE
641
// To g!t #istinct count of a prop!rty.
cr.s!tProj!ction$Proj!ctions.count4istinct$)first=am!)((*
// To g!t ma:imum of a prop!rty.
cr.s!tProj!ction$Proj!ctions.ma:$)salary)((*
// To g!t minimum of a prop!rty.
cr.s!tProj!ction$Proj!ctions.min$)salary)((*
// To g!t sum of a prop!rty.
cr.s!tProj!ction$Proj!ctions.sum$)salary)((*
Criteria Queries Example:
Consider the following POJO class:
public class 3mploy!! {
privat! int i#*
privat! %tring first=am!*
privat! %tring last=am!*
privat! int salary*
public 3mploy!!$( {+
public 3mploy!!$%tring fnam!2 %tring lnam!2 int salary( {
this.first=am! 9 fnam!*
this.last=am! 9 lnam!*
this.salary 9 salary*
+
public int g!t6#$( {
r!turn i#*
+
public voi# s!t6#$ int i# ( {
this.i# 9 i#*
+
public %tring g!tFirst=am!$( {
r!turn first=am!*
+
public voi# s!tFirst=am!$ %tring firstTnam! ( {
this.first=am! 9 firstTnam!*
+
public %tring g!t1ast=am!$( {
r!turn last=am!*
+
public voi# s!t1ast=am!$ %tring lastTnam! ( {
this.last=am! 9 lastTnam!*
+
public int g!t%alary$( {
r!turn salary*
+
public voi# s!t%alary$ int salary ( {
this.salary 9 salary*
+
+
MAT SOFT
JAVA REFERENCE GUIDE
642
Let us create the following EMPLOYEE table to store Employee objects:
cr!at! tabl! 3MP1?A33 $
i# 6=T =?T =511 autoTincr!m!nt2
firstTnam! B07,07$@E( #!fault =5112
lastTnam! B07,07$@E( #!fault =5112
salary 6=T #!fault =5112
P76M07A Y3A $i#(
(*
Following will be mapping file.
NS:ml v!rsion9)C.E) !nco#ing9)utf;J)S.
NG4?,TAP3 hib!rnat!;mapping P5L16,
);//ib!rnat!/ib!rnat! Mapping 4T4//3=)
)http-//www.hib!rnat!.org/#t#/hib!rnat!;mapping;D.E.#t#).
Nhib!rnat!;mapping.
Nclass nam!9)3mploy!!) tabl!9)3MP1?A33).
Nm!ta attribut!9)class;#!scription).
This class contains th! !mploy!! #!tail.
N/m!ta.
Ni# nam!9)i#) typ!9)int) column9)i#).
Ng!n!rator class9)nativ!)/.
N/i#.
Nprop!rty nam!9)first=am!) column9)firstTnam!) typ!9)string)/.
Nprop!rty nam!9)last=am!) column9)lastTnam!) typ!9)string)/.
Nprop!rty nam!9)salary) column9)salary) typ!9)int)/.
N/class.
N/hib!rnat!;mapping.
Finally, we will create our application class with the main() method to run the application where we will
use Criteria queries:
import java.util.1ist*
import java.util.4at!*
import java.util.6t!rator*

import org.hib!rnat!.ib!rnat!3:c!ption*
import org.hib!rnat!.%!ssion*
import org.hib!rnat!.Transaction*
import org.hib!rnat!.%!ssionFactory*
import org.hib!rnat!.,rit!ria*
import org.hib!rnat!.crit!rion.7!strictions*
import org.hib!rnat!.crit!rion.Proj!ctions*
import org.hib!rnat!.cfg.,onfiguration*
public class Manag!3mploy!! {
privat! static %!ssionFactory factory*
public static voi# main$%tring&' args( {
try{
factory 9 n!w ,onfiguration$(.configur!$(.buil#%!ssionFactory$(*
MAT SOFT
JAVA REFERENCE GUIDE
643
+catch $Throwabl! !:( {
%yst!m.!rr.println$)Fail!# to cr!at! s!ssionFactory obj!ct.) >
!:(*
throw n!w 3:c!ption6n6nitiali/!r3rror$!:(*
+
Manag!3mploy!! M3 9 n!w Manag!3mploy!!$(*
/* 0## f!w !mploy!! r!cor#s in #atabas! */
6nt!g!r !mp64C 9 M3.a##3mploy!!$)Vara)2 )0li)2 @EEE(*
6nt!g!r !mp64@ 9 M3.a##3mploy!!$)4aisy)2 )4as)2 HEEE(*
6nt!g!r !mp64D 9 M3.a##3mploy!!$)John)2 )Paul)2 HEEE(*
6nt!g!r !mp64F 9 M3.a##3mploy!!$)Moh#)2 )Aas!!)2 DEEE(*
/* 1ist #own all th! !mploy!!s */
M3.list3mploy!!s$(*
/* Print Total !mploy!!'s count */
M3.count3mploy!!$(*
/* Print Toatl salary */
M3.total%alary$(*
+
/* M!tho# to ,730T3 an !mploy!! in th! #atabas! */
public 6nt!g!r a##3mploy!!$%tring fnam!2 %tring lnam!2 int salary({
%!ssion s!ssion 9 factory.op!n%!ssion$(*
Transaction t: 9 null*
6nt!g!r !mploy!!64 9 null*
try{
t: 9 s!ssion.b!ginTransaction$(*
3mploy!! !mploy!! 9 n!w 3mploy!!$fnam!2 lnam!2 salary(*
!mploy!!64 9 $6nt!g!r( s!ssion.sav!$!mploy!!(*
t:.commit$(*
+catch $ib!rnat!3:c!ption !( {
if $t:G9null( t:.rollbac<$(*
!.print%tac<Trac!$(*
+finally {
s!ssion.clos!$(*
+
r!turn !mploy!!64*
+
/* M!tho# to 7304 all th! !mploy!!s having salary mor! than @EEE */
public voi# list3mploy!!s$ ({
%!ssion s!ssion 9 factory.op!n%!ssion$(*
Transaction t: 9 null*
try{
t: 9 s!ssion.b!ginTransaction$(*
,rit!ria cr 9 s!ssion.cr!at!,rit!ria$3mploy!!.class(*
// 0## r!striction.
cr.a##$7!strictions.gt$)salary)2 @EEE((*
1ist !mploy!!s 9 cr.list$(*
for $6t!rator it!rator 9
!mploy!!s.it!rator$(* it!rator.has=!:t$(*({
3mploy!! !mploy!! 9 $3mploy!!( it!rator.n!:t$(*
MAT SOFT
JAVA REFERENCE GUIDE
644
%yst!m.out.print$)First =am!- ) > !mploy!!.g!tFirst=am!$((*
%yst!m.out.print$) 1ast =am!- ) > !mploy!!.g!t1ast=am!$((*
%yst!m.out.println$) %alary- ) > !mploy!!.g!t%alary$((*
+
t:.commit$(*
+catch $ib!rnat!3:c!ption !( {
if $t:G9null( t:.rollbac<$(*
!.print%tac<Trac!$(*
+finally {
s!ssion.clos!$(*
+
+
/* M!tho# to print total numb!r of r!cor#s */
public voi# count3mploy!!$({
%!ssion s!ssion 9 factory.op!n%!ssion$(*
Transaction t: 9 null*
try{
t: 9 s!ssion.b!ginTransaction$(*
,rit!ria cr 9 s!ssion.cr!at!,rit!ria$3mploy!!.class(*
// To g!t total row count.
cr.s!tProj!ction$Proj!ctions.row,ount$((*
1ist row,ount 9 cr.list$(*
%yst!m.out.println$)Total ,oint- ) > row,ount.g!t$E( (*
t:.commit$(*
+catch $ib!rnat!3:c!ption !( {
if $t:G9null( t:.rollbac<$(*
!.print%tac<Trac!$(*
+finally {
s!ssion.clos!$(*
+
+
/* M!tho# to print sum of salari!s */
public voi# total%alary$({
%!ssion s!ssion 9 factory.op!n%!ssion$(*
Transaction t: 9 null*
try{
t: 9 s!ssion.b!ginTransaction$(*
,rit!ria cr 9 s!ssion.cr!at!,rit!ria$3mploy!!.class(*
// To g!t total salary.
cr.s!tProj!ction$Proj!ctions.sum$)salary)((*
1ist total%alary 9 cr.list$(*
%yst!m.out.println$)Total %alary- ) > total%alary.g!t$E( (*
t:.commit$(*
+catch $ib!rnat!3:c!ption !( {
if $t:G9null( t:.rollbac<$(*
!.print%tac<Trac!$(*
+finally {
s!ssion.clos!$(*
+
+
+
MAT SOFT
JAVA REFERENCE GUIDE
645
Compilation and Execution:
Here are the steps to compile and run the above mentioned application. Make sure you have set PATH
and CLASSPATH appropriately before proceeding for the compilation and execution.
1. Create hibernate.cfg.xml configuration file as explained in configuration chapter.
2. Create Employee.hbm.xml mapping file as shown above.
3. Create Employee.java source file as shown above and compile it.
4. Create ManageEmployee.java source file as shown above and compile it.
5. Execute ManageEmployee binary to run the program.
You would get following result, and records would be created in EMPLOYEE table.
Ujava Manag!3mploy!!
.......B076?5% 1?8 M3%%083% "611 46%P10A 373........
First =am!- 4aisy 1ast =am!- 4as %alary- HEEE
First =am!- John 1ast =am!- Paul %alary- HEEE
First =am!- Moh# 1ast =am!- Aas!! %alary- DEEE
Total ,oint- F
Total %alary- CHEEE
If you check your EMPLOYEE table, it should have following records:
mysPl. s!l!ct * from 3MP1?A33*
>;;;;>;;;;;;;;;;;;>;;;;;;;;;;;>;;;;;;;;>
a i# a firstTnam! a lastTnam! a salary a
>;;;;>;;;;;;;;;;;;>;;;;;;;;;;;>;;;;;;;;>
a CF a Vara a 0li a @EEE a
a CH a 4aisy a 4as a HEEE a
a CM a John a Paul a HEEE a
a CI a Moh# a Aas!! a DEEE a
>;;;;>;;;;;;;;;;;;>;;;;;;;;;;;>;;;;;;;;>
F rows in s!t $E.EE s!c(
mysPl.
NATIVE SJL
You can use native SQL to express database queries if you want to utilize database-specific features
such as query hints or the CONNECT keyword in Oracle. Hibernate 3.x allows you to specify
handwritten SQL, including stored procedures, for all create, update, delete, and load operations.
Your application will create a native SQL query from the session with the createSJ0Jery,/method
on the Session interface.:
MAT SOFT
JAVA REFERENCE GUIDE
646
public %X1Xu!ry cr!at!%X1Xu!ry$%tring sPl%tring( throws ib!rnat!3:c!ption
After you pass a string containing the SQL query to the createSQLQuery() method, you can associate
the SQL result with either an existing Hibernate entity, a join, or a scalar result using addEntity(),
addJoin(), and addScalar() methods respectively.
Scalar queries:
The most basic SQL query is to get a list of scalars (values) from one or more tables. Following is the
syntax for using native SQL for scalar values:
%tring sPl 9 )%313,T firstTnam!2 salary F7?M 3MP1?A33)*
%X1Xu!ry Pu!ry 9 s!ssion.cr!at!%X1Xu!ry$sPl(*
Pu!ry.s!t7!sultTransform!r$,rit!ria.0160%TT?T3=T6TATM0P(*
1ist r!sults 9 Pu!ry.list$(*
Entity queries:
The above queries were all about returning scalar values, basically returning the "raw" values from the
resultset. The following is the syntax to get entity objects as a whole from a native sql query via
addEntity().
%tring sPl 9 )%313,T * F7?M 3MP1?A33)*
%X1Xu!ry Pu!ry 9 s!ssion.cr!at!%X1Xu!ry$sPl(*
Pu!ry.a##3ntity$3mploy!!.class(*
1ist r!sults 9 Pu!ry.list$(*
Named SQL queries:
The following is the syntax to get entity objects from a native sql query via addEntity() and using
named SQL query.
%tring sPl 9 )%313,T * F7?M 3MP1?A33 "373 i# 9 -!mploy!!Ti#)*
%X1Xu!ry Pu!ry 9 s!ssion.cr!at!%X1Xu!ry$sPl(*
Pu!ry.a##3ntity$3mploy!!.class(*
Pu!ry.s!tParam!t!r$)!mploy!!Ti#)2 CE(*
1ist r!sults 9 Pu!ry.list$(*
Native SQL Example:
Consider the following POJO class:
public class 3mploy!! {
privat! int i#*
privat! %tring first=am!*
privat! %tring last=am!*
MAT SOFT
JAVA REFERENCE GUIDE
647
privat! int salary*
public 3mploy!!$( {+
public 3mploy!!$%tring fnam!2 %tring lnam!2 int salary( {
this.first=am! 9 fnam!*
this.last=am! 9 lnam!*
this.salary 9 salary*
+
public int g!t6#$( {
r!turn i#*
+
public voi# s!t6#$ int i# ( {
this.i# 9 i#*
+
public %tring g!tFirst=am!$( {
r!turn first=am!*
+
public voi# s!tFirst=am!$ %tring firstTnam! ( {
this.first=am! 9 firstTnam!*
+
public %tring g!t1ast=am!$( {
r!turn last=am!*
+
public voi# s!t1ast=am!$ %tring lastTnam! ( {
this.last=am! 9 lastTnam!*
+
public int g!t%alary$( {
r!turn salary*
+
public voi# s!t%alary$ int salary ( {
this.salary 9 salary*
+
+
Let us create the following EMPLOYEE table to store Employee objects:
cr!at! tabl! 3MP1?A33 $
i# 6=T =?T =511 autoTincr!m!nt2
firstTnam! B07,07$@E( #!fault =5112
lastTnam! B07,07$@E( #!fault =5112
salary 6=T #!fault =5112
P76M07A Y3A $i#(
(*
Following will be mapping file.
NS:ml v!rsion9)C.E) !nco#ing9)utf;J)S.
NG4?,TAP3 hib!rnat!;mapping P5L16,
);//ib!rnat!/ib!rnat! Mapping 4T4//3=)
)http-//www.hib!rnat!.org/#t#/hib!rnat!;mapping;D.E.#t#).
Nhib!rnat!;mapping.
MAT SOFT
JAVA REFERENCE GUIDE
648
Nclass nam!9)3mploy!!) tabl!9)3MP1?A33).
Nm!ta attribut!9)class;#!scription).
This class contains th! !mploy!! #!tail.
N/m!ta.
Ni# nam!9)i#) typ!9)int) column9)i#).
Ng!n!rator class9)nativ!)/.
N/i#.
Nprop!rty nam!9)first=am!) column9)firstTnam!) typ!9)string)/.
Nprop!rty nam!9)last=am!) column9)lastTnam!) typ!9)string)/.
Nprop!rty nam!9)salary) column9)salary) typ!9)int)/.
N/class.
N/hib!rnat!;mapping.
Finally, we will create our application class with the main() method to run the application where we will
use Native SJ0 queries:
import java.util.**

import org.hib!rnat!.ib!rnat!3:c!ption*
import org.hib!rnat!.%!ssion*
import org.hib!rnat!.Transaction*
import org.hib!rnat!.%!ssionFactory*
import org.hib!rnat!.%X1Xu!ry*
import org.hib!rnat!.,rit!ria*
import org.hib!rnat!.ib!rnat!*
import org.hib!rnat!.cfg.,onfiguration*
public class Manag!3mploy!! {
privat! static %!ssionFactory factory*
public static voi# main$%tring&' args( {
try{
factory 9 n!w ,onfiguration$(.configur!$(.buil#%!ssionFactory$(*
+catch $Throwabl! !:( {
%yst!m.!rr.println$)Fail!# to cr!at! s!ssionFactory obj!ct.) >
!:(*
throw n!w 3:c!ption6n6nitiali/!r3rror$!:(*
+
Manag!3mploy!! M3 9 n!w Manag!3mploy!!$(*
/* 0## f!w !mploy!! r!cor#s in #atabas! */
6nt!g!r !mp64C 9 M3.a##3mploy!!$)Vara)2 )0li)2 @EEE(*
6nt!g!r !mp64@ 9 M3.a##3mploy!!$)4aisy)2 )4as)2 HEEE(*
6nt!g!r !mp64D 9 M3.a##3mploy!!$)John)2 )Paul)2 HEEE(*
6nt!g!r !mp64F 9 M3.a##3mploy!!$)Moh#)2 )Aas!!)2 DEEE(*
/* 1ist #own !mploy!!s an# th!ir salary using %calar Xu!ry */
M3.list3mploy!!s%calar$(*
/* 1ist #own compl!t! !mploy!!s information using 3ntity Xu!ry */
M3.list3mploy!!s3ntity$(*
+
/* M!tho# to ,730T3 an !mploy!! in th! #atabas! */
public 6nt!g!r a##3mploy!!$%tring fnam!2 %tring lnam!2 int salary({
%!ssion s!ssion 9 factory.op!n%!ssion$(*
MAT SOFT
JAVA REFERENCE GUIDE
649
Transaction t: 9 null*
6nt!g!r !mploy!!64 9 null*
try{
t: 9 s!ssion.b!ginTransaction$(*
3mploy!! !mploy!! 9 n!w 3mploy!!$fnam!2 lnam!2 salary(*
!mploy!!64 9 $6nt!g!r( s!ssion.sav!$!mploy!!(*
t:.commit$(*
+catch $ib!rnat!3:c!ption !( {
if $t:G9null( t:.rollbac<$(*
!.print%tac<Trac!$(*
+finally {
s!ssion.clos!$(*
+
r!turn !mploy!!64*
+
/* M!tho# to 7304 all th! !mploy!!s using %calar Xu!ry */
public voi# list3mploy!!s%calar$ ({
%!ssion s!ssion 9 factory.op!n%!ssion$(*
Transaction t: 9 null*
try{
t: 9 s!ssion.b!ginTransaction$(*
%tring sPl 9 )%313,T firstTnam!2 salary F7?M 3MP1?A33)*
%X1Xu!ry Pu!ry 9 s!ssion.cr!at!%X1Xu!ry$sPl(*
Pu!ry.s!t7!sultTransform!r$,rit!ria.0160%TT?T3=T6TATM0P(*
1ist #ata 9 Pu!ry.list$(*
for$?bj!ct obj!ct - #ata(
{
Map row 9 $Map(obj!ct*
%yst!m.out.print$)First =am!- ) > row.g!t$)firstTnam!)((*
%yst!m.out.println$)2 %alary- ) > row.g!t$)salary)((*
+
t:.commit$(*
+catch $ib!rnat!3:c!ption !( {
if $t:G9null( t:.rollbac<$(*
!.print%tac<Trac!$(*
+finally {
s!ssion.clos!$(*
+
+
/* M!tho# to 7304 all th! !mploy!!s using 3ntity Xu!ry */
public voi# list3mploy!!s3ntity$ ({
%!ssion s!ssion 9 factory.op!n%!ssion$(*
Transaction t: 9 null*
try{
t: 9 s!ssion.b!ginTransaction$(*
%tring sPl 9 )%313,T * F7?M 3MP1?A33)*
%X1Xu!ry Pu!ry 9 s!ssion.cr!at!%X1Xu!ry$sPl(*
Pu!ry.a##3ntity$3mploy!!.class(*
1ist !mploy!!s 9 Pu!ry.list$(*
for $6t!rator it!rator 9
!mploy!!s.it!rator$(* it!rator.has=!:t$(*({
MAT SOFT
JAVA REFERENCE GUIDE
650
3mploy!! !mploy!! 9 $3mploy!!( it!rator.n!:t$(*
%yst!m.out.print$)First =am!- ) > !mploy!!.g!tFirst=am!$((*
%yst!m.out.print$) 1ast =am!- ) > !mploy!!.g!t1ast=am!$((*
%yst!m.out.println$) %alary- ) > !mploy!!.g!t%alary$((*
+
t:.commit$(*
+catch $ib!rnat!3:c!ption !( {
if $t:G9null( t:.rollbac<$(*
!.print%tac<Trac!$(*
+finally {
s!ssion.clos!$(*
+
+
+
Compilation and Execution:
Here are the steps to compile and run the above mentioned application. Make sure you have set PATH
and CLASSPATH appropriately before proceeding for the compilation and execution.
1. Create hibernate.cfg.xml configuration file as explained in configuration chapter.
2. Create Employee.hbm.xml mapping file as shown above.
3. Create Employee.java source file as shown above and compile it.
4. Create ManageEmployee.java source file as shown above and compile it.
5. Execute ManageEmployee binary to run the program.
You would get following result, and records would be created in EMPLOYEE table.
Ujava Manag!3mploy!!
.......B076?5% 1?8 M3%%083% "611 46%P10A 373........
First =am!- Vara2 %alary- @EEE
First =am!- 4aisy2 %alary- HEEE
First =am!- John2 %alary- HEEE
First =am!- Moh#2 %alary- DEEE
First =am!- Vara 1ast =am!- 0li %alary- @EEE
First =am!- 4aisy 1ast =am!- 4as %alary- HEEE
First =am!- John 1ast =am!- Paul %alary- HEEE
First =am!- Moh# 1ast =am!- Aas!! %alary- DEEE
If you check your EMPLOYEE table, it should have following records:
mysPl. s!l!ct * from 3MP1?A33*
>;;;;>;;;;;;;;;;;;>;;;;;;;;;;;>;;;;;;;;>
a i# a firstTnam! a lastTnam! a salary a
>;;;;>;;;;;;;;;;;;>;;;;;;;;;;;>;;;;;;;;>
a @M a Vara a 0li a @EEE a
a @I a 4aisy a 4as a HEEE a
MAT SOFT
JAVA REFERENCE GUIDE
651
a @J a John a Paul a HEEE a
a @K a Moh# a Aas!! a DEEE a
>;;;;>;;;;;;;;;;;;>;;;;;;;;;;;>;;;;;;;;>
F rows in s!t $E.EE s!c(
mysPl.
)ay VP: 7nterprise Beans
7JBM
EJB stands for "Enterprise JavaBeans" which are distributed network aware components for developing secure,
scalable, transactional and multi-user components in a J2EE environment.
Above definition actually describes EJBs from functional point of view i.e. what they do. A more structural definition
would be : "EJBs are collection of Java classes, interfaces and XML files adhering to given rules".
Written in the Java programming language, an enterprise bean is a server-side component that encapsulates the
business logic of an application.
Benefits of 7nterprise Beans
For several reasons, enterprise beans simplify the development of large, distributed applications. First, because
the EJB container provides system-level services to enterprise beans, the bean developer can concentrate on
solving business problems. The EJB container--not the bean developer--is responsible for system-level services
such as transaction management and security authorization.
Second, because the beans--and not the clients--contain the application's business logic, the client developer can
focus on the presentation of the client. The client developer does not have to code the routines that implement
business rules or access databases. As a result, the clients are thinner, a benefit that is particularly important for
MAT SOFT
JAVA REFERENCE GUIDE
652
clients that run on small devices.
Third, because enterprise beans are portable components, the application assembler can build new applications
from existing beans. These applications can run on any compliant J2EE server.
9hen to Bse 7nterprise Beans
You should consider using enterprise beans if your application has any of the following requirements:
The application must be scalable. To accommodate a growing number of users, you may need to distribute
an application's components across multiple machines. Not only can the enterprise beans of an application
run on different machines, but their location will remain transparent to the clients.
Transactions are required to ensure data integrity. Enterprise beans support transactions, the mechanisms
that manage the concurrent access of shared objects.
The application will have a variety of clients. With just a few lines of code, remote clients can easily locate
enterprise beans. These clients can be thin, various, and numerous.
The 7JB 7cosystem
To have an EJB deployment up and running, one needs more than an application server and components. There are
six more parties that are involved:
1. The Bean provider: The bean provider supplies the business components to the enterprise applications.
These business components are not complete applications but can be combined to form complete
enterprise applications. These bean providers could be an ISV selling components or an internal
component provider.
2. The Application Assembler: The application assembler is responsible for integrating the components. This
party writes applications to combine components so as to develop the target application that can be
deployed under various environments.
3. The EJB Deployer: After the application developer builds the application, the application must be deployed
on the server. This involves configuring the security parameter settings, performance tuning, etc. An
application assembler is not familiar with these issues. This is where the EJB deployer comes into play.
4. The System Administrator: The system administrator is responsible for the upkeep and monitoring of the
deployed system and may make use of monitoring and management tools to closely observe the deployed
system.
5. The Container and Server providers: The container provider supplies the EJB container (an application
server). This is the runtime environment where the beans live. The container supplies the middleware
services to the beans and manages them. Some of the various containers are: BEA's WebLogic, iPlanet's
iPlanet Application Server, IBM's WebSphere, Oracle's Oracle 9i Application Server and Oracle 10g
Application Server, and the JBoss open source Application Server. The server provider is the same as the
container provider.
MAT SOFT
JAVA REFERENCE GUIDE
653
6. The Tool Vendors: There are various IDEs available to assist the developer in rapidly building and
debugging components, for example Eclipse, NetBeans, and JBuilder. For the modeling of components one
can use Rational Rose. There are many other tools, some used for testing (JUnit) and others used for
building (Ant, XDoclet)
The 7JB Container
Enterprise beans are software components that run in a special environment called
an EJB container. The container hosts and manages an enterprise bean in the same manner
that the Java Web Server hosts a servlet or an HTML browser hosts a Java applet. An
enterprise bean cannot function outside of an EJB container. The EJB container manages
every aspect of an enterprise bean at runtimes including remote access to the bean,
security, persistence, transactions, concurrency, and access to and pooling of resources.
The container isolates the enterprise bean from direct access by client applications. When a
client application invokes a remote method on an enterprise bean, the container first
intercepts the invocation to ensure persistence, transactions, and security are applied
properly to every operation a client performs on the bean. The container manages security,
transactions, and persistence automatically for the bean, so the bean developer doesn't
have to write this type of logic into the bean code itself. The enterprise bean developer can
focus on encapsulating business rules, while the container takes care of everything else.
Containers will manage many beans simultaneously in the same fashion that the Java
WebServer manages many servlets. To reduce memory consumption and processing,
containers pool resources and manage the lifecycles of all the beans very carefully. When a
bean is not being used, a container will place it in a pool to be reused by another client, or
possibly evict it from memory and only bring it back when its needed. Because client
MAT SOFT
JAVA REFERENCE GUIDE
654
applications don't have direct access to the beans--the container lies between the client and
bean--the client application is completely unaware of the containers resource management
activities. A bean that is not in use, for example, might be evicted from memory on the
server, while its remote reference on the client remains intact. When the client invokes a
method on the remote reference, the container simply re-incarnates the bean to service the
request. The client application is unaware of the entire process.
An enterprise bean depends on the container for everything it needs. If an enterprise bean
needs to access a JDBC connection or another enterprise bean, it does so through the
container; if an enterprise bean needs to access the identity of its caller, obtain a reference
to itself, or access properties it does so through the container. The enterprise bean interacts
with its container through one of three mechanisms: callback methods, the EJBContext
interface, or the Java Naming and Directory Interface (JNDI).
Ca$$"ac= Methods
Every bean implements a subtype of the 3nt!rpris!L!an interface which defines several
methods, called callback methods. Each callback method alerts the bean TO a different
event in its lifecycle and the container will invoke these methods to notify the bean when it's
about to activate the bean, persist its state to the database, end a transaction, remove the
bean from memory, etc. The callback methods give the bean a chance to do some
housework immediately before or after some event.
7JBContext
Every bean obtains an 3JL,ont!:t object, which is a reference directly to the container.
The 3JL,ont!:t interface provides methods for interacting with the container so that that
bean can request information about its environment like the identity of its client, the status
of a transaction, or to obtain remote references to itself.
Java Naming and )irectory Interface
Java Naming and Directory Interface (JNDI) is a standard extension to the Java platform for
accessing naming systems like LDAP, NetWare, file systems, etc. Every bean automatically
has access to a special naming system called the Environment Naming Context (ENC). The
ENC is managed by the container and accessed by beans using JNDI. The JNDI ENC allows a
bean to access resources like JDBC connections, other enterprise beans, and properties
specific to that bean.
7nterprise Beans
To create an EJB server-side component, an enterprise bean developer provides two
interfaces that define a bean's business methods, plus the actual bean implementation
class. The client then uses a bean's public interfaces to create, manipulate, and remove
beans from the EJB server. The implementation class, to be called the bean class, is
instantiated at runtime and becomes a distributed object.
MAT SOFT
JAVA REFERENCE GUIDE
655
Enterprise beans live in an EJB container and are accessed by client applications over the
network through their remote and home interfaces. The remote and home interfaces expose
the capabilities of the bean and provide all the method needed to create, update, interact
with, and delete the bean. A bean is a server-side component that represents a business
concept like a Customer or a HotelClerk.
'emote and (ome Interfaces
The remote and home interfaces represent the bean, but the container insulates the beans
from direct access from client applications. Every time a bean is requested, created, or
deleted, the container manages the whole process.
The home interface represents the life-cycle methods of the component (create, destroy,
find) while the remote interface represents the business method of the bean. The remote
and home interfaces extend the javax.ejb.EJBObject and javax.ejb.EJBHome interfaces
respectively. These EJB interface types define a standard set of utility methods and provide
common base types for all remote and home interfaces.
MAT SOFT
JAVA REFERENCE GUIDE
656
Clients use the bean's home interface to obtain references to the bean's remote interface.
The remote interface defines the business methods like accessor and mutator methods for
changing a customer's name, or business methods that perform tasks like using the
HotelClerk bean to reserve a room at a hotel. Below is an example of how a Customer bean
might be accessed from a client application.
Three types of 7nterprise Beans
The following sections discuss each type in more detail.
MAT SOFT
JAVA REFERENCE GUIDE
657
7nterprise Bean
Type
Prpose
Session Performs a task for a client
Entity Represents a business entity object that exists in persistent storage
Message-Driven
Acts as a listener for the Java Message Service API, processing
messages asynchronously
Session Bean
A session bean represents a single client inside the J2EE server . To access an application
that is deployed on the server, the client invokes the session bean's methods. The session
bean performs work for its client, shielding the client from complexity by executing business
tasks inside the server.
As its name suggests, a session bean is similar to an interactive session. A session bean is
not shared--it may have just one client, in the same way that an interactive session may
have just one user. Like an interactive session, a session bean is not persistent. (That is, its
data is not saved to a database.) When the client terminates, its session bean appears to
terminate and is no longer associated with the client.
Session Bean C$ass
The session bean class for this example is called CartBean. Like any session bean, the
CartBean class must meet these requirements:
It implements the SessionBean interface.
The class is defined as public.
The class cannot be defined as abstract or final.
It implements one or more ejbCreate methods.
It implements the business methods .
MAT SOFT
JAVA REFERENCE GUIDE
658
It contains a public constructor with no parameters.
It must not define the finalize method.
The source code for the CartBean class follows.
import java.util.*;
import 9%<%A.ejb.*;
public class CartBean implements SessionBean {
String customerName;
String customerId;
Vector contents;
public void ejbCreate(String person)
throws CreateException {
if (person == null) {
throw new CreateException("Null person not allowed.");
}
else {
customerName = person;
}
customerId = "0";
contents = new Vector();
}
public void ejbCreate(String person, String id)
throws CreateException {
if (person == null) {
throw new CreateException("Null person not allowed.");
}
else {
customerName = person;
}
IdVerifier idChecker = new IdVerifier();
if (idChecker.validate(id)) {
customerId = id;
MAT SOFT
JAVA REFERENCE GUIDE
659
}
else {
throw new CreateException("Invalid id: "+ id);
}
contents = new Vector();
}
public void addBook(String title) {
contents.addElement(title);
}
public void removeBook(String title) throws BookException {
boolean result = contents.removeElement(title);
if (result == false) {
throw new BookException(title + "not in cart.");
}
}
public Vector getContents() {
return contents;
}
public CartBean() {}
public void ejbRemove() {}
public void ejbActivate() {}
public void ejbPassivate() {}
public void setSessionContext(SessionContext sc) {}
}
State Management Modes
There are two types of session beans: stateful and stateless.
Statef$ Session Beans
The state of an object consists of the values of its instance variables. In a stateful session
bean, the instance variables represent the state of a unique client-bean session. Because
the client interacts ("talks") with its bean, this state is often called the conversational state.
The state is retained for the duration of the client-bean session. If the client removes the
bean or terminates, the session ends and the state disappears. This transient nature of the
state is not a problem, however, because when the conversation between the client and the
bean ends there is no need to retain the state.
MAT SOFT
JAVA REFERENCE GUIDE
660
State$ess Session Beans
A stateless session bean does not maintain a conversational state for a particular client.
When a client invokes the method of a stateless bean, the bean's instance variables may
contain a state, but only for the duration of the invocation. When the method is finished, the
state is no longer retained. Except during method invocation, all instances of a stateless
bean are equivalent, allowing the EJB container to assign an instance to any client.
Because stateless session beans can support multiple clients, they can offer better
scalability for applications that require large numbers of clients. Typically, an application
requires fewer stateless session beans than stateful session beans to support the same
number of clients.
At times, the EJB container may write a stateful session bean to secondary storage.
However, stateless session beans are never written to secondary storage. Therefore,
stateless beans may offer better performance than stateful beans.
9hen to Bse Session Beans
In general, you should use a session bean if the following circumstances hold:
At any given time, only one client has access to the bean instance.
The state of the bean is not persistent, existing only for a short period of time
(perhaps a few hours).
Stateful session beans are appropriate if any of the following conditions are true:
The bean's state represents the interaction between the bean and a specific client.
The bean needs to hold information about the client across method invocations.
The bean mediates between the client and the other components of the application,
presenting a simplified view to the client.
Behind the scenes, the bean manages the work flow of several enterprise beans.
To improve performance, you might choose a stateless session bean if it has any of these
traits:
The bean's state has no data for a specific client.
In a single method invocation, the bean performs a generic task for all clients. For
example, you might use a stateless session bean to send an e-mail that confirms an
online order.
MAT SOFT
JAVA REFERENCE GUIDE
661
The bean fetches from a database a set of read-only data that is often used by
clients. Such a bean, for example, could retrieve the table rows that represent the
products that are on sale this month.
9hat Is an 7ntity BeanM
Entity beans deal with data. They typically represent nouns, such as a frequent flier
account, customer, or payment. Plain old Java objectscome into existence when they are
created in a program. When the program terminates, the object is lost. But an entity bean
stays around until it is deleted. A program can create an entity bean and then the program
can be stopped and restarted--but the entity bean will continue to exist. After being
restarted, the program can again find the entity bean it was working with and continue
using it.
Plain old Java objects are used only by one program. An entity bean, on the other hand, can
be used by any program on the network. Client programs just need to find the entity bean
via JNDI in order to use it. Entity beans must have a unique primary key that is used to find
the specific entity bean they want to manipulate. For example, an "employee" entity bean
may use the employee's social security number as its primary key. Methods of an entity
bean run on a "server" machine. When a client program calls an entity bean's method, the
client program's thread stops executing and control passes over to the server. When
the method returns from the server, the local thread resumes execution.
Container&Managed Persistence
The term container-managed persistence means that the EJB container handles all database
access required by the entity bean. The bean's code contains no database access (SQL)
calls. As a result, the bean's code is not tied to a specific persistent storage mechanism
(database). Because of this flexibility, even if you redeploy the same entity bean on
different J2EE servers that use different databases, you won't need to modify or recompile
the bean's code. In short, your entity beans are more portable.
In order to generate the data access calls, the container needs information that you provide
in the entity bean's abstract schema.
%"stract Schema
Part of an entity bean's deployment descriptor, the abstract schema defines the bean's
persistent fields and relationships. The term abstract distinguishes this schema from the
physical schema of the underlying data store. In a relational database, for example, the
physical schema is made up of structures such as tables and columns. You specify the name
of an abstract schema in the deployment descriptor. This name is referenced by queries
written in the Enterprise JavaBeans Query Language ("EJB QL"). For an entity bean with
container-managed persistence, you must define an EJB QL query for every finder method
(except findByPrimaryKey). The EJB QL query determines the query that is executed by the
MAT SOFT
JAVA REFERENCE GUIDE
662
EJB container when the finder method is invoked. You'll probably find it helpful to sketch
the abstract schema before writing any code. Figure represents a simple abstract schema
that describes the relationships between three entity beans. These relationships are
discussed further in the sections that follow.
A High-Level View of an Abstract Schema
Persistent +ie$ds
The persistent fields of an entity bean are stored in the underlying data store. Collectively,
these fields constitute the state of the bean. At runtime, the EJB container automatically
synchronizes this state with the database. During deployment, the container typically maps
the entity bean to a database table and maps the persistent fields to the table's columns.
A CustomerEJB entity bean, for example, might have persistent fields such as firstName,
lastName, phone, and emailAddress. In container-managed persistence, these fields are
virtual. You declare them in the abstract schema, but you do not code them as instance
variables in the entity bean class. Instead, the persistent fields are identified in the code by
access methods (getters and setters).
'e$ationship +ie$ds
A relationship field is like a foreign key in a database table--it identifies a related bean. Like
a persistent field, a relationship field is virtual and is defined in the enterprise bean class
with access methods. But unlike a persistent field, a relationship field does not represent the
bean's state.
MAT SOFT
JAVA REFERENCE GUIDE
663
JMS message listener, which is similar to an event listener, except that it receives messages
instead of events. The messages may be sent by any J2EEcomponent--an application client,
another enterprise bean, a Web component--or by a JMS application or system that does
not use J2EE technology. The most visible difference between message-driven beans and
session or entity beans is that clients do not access message-driven beans through
interfaces. Unlike a session or entity bean, a message-driven bean has only a bean class.
In several respects, a message-driven bean resembles a stateless session bean:
A message-driven bean's instances retain no data or conversational state for a
specific client.
All instances of a message-driven bean are equivalent, allowing the EJB container to
assign a message to any message-driven bean instance. The container can pool
these instances to allow streams of messages to be processed concurrently.
A single message-driven bean can process messages from multiple clients.
The instance variables of a message-driven bean can contain some state across the
handling of client messages--for example, a JMS API connection, an open database
connection, or an object reference to an enterprise bean. Session beans and entity beans
allow you to send JMS messages and to receive them synchronously, but not
asynchronously. To avoid tying up server resources, you may prefer to not use blocking
synchronous receives in a server-side component. To receive messages asynchronously,
instead, use a message-driven bean.
9hat Ma=es Message&)riven Beans )ifferent from Session and 7ntity
BeansM
The most visible difference between message-driven beans and session and entity beans is
that clients do not access message-driven beans through interfaces. Interfaces are
described in the section Unlike a session or entity bean, a message-driven bean has only a
bean class.
In several respects, a message-driven bean resembles a stateless session bean.
A message-driven bean's instances retain no data or conversational state for a
specific client.
All instances of a message-driven bean are equivalent, allowing the EJB container to
assign a message to any message-driven bean instance. The container can pool
these instances to allow streams of messages to be processed concurrently.
A single message-driven bean can process messages from multiple clients.
The instance variables of the message-driven bean instance can contain some state across
the handling of client messages--for example, a JMS API connection, an open database
MAT SOFT
JAVA REFERENCE GUIDE
664
connection, or an object reference to an enterprise bean object.
When a message arrives, the container calls the message-driven bean's onMessage method
to process the message. The onMessage method normally casts the message to one of the
five JMS message types and handles it in accordance with the application's business logic.
The onMessage method may call helper methods, or it may invoke a session or entity bean
to process the information in the message or to store it in a database.
A message may be delivered to a message-driven bean within a transaction context, so that
all operations within the onMessage method are part of a single transaction. If message
processing is rolled back, the message will be redelivered.
9hen to Bse Message&)riven Beans
Session beans and entity beans allow you to send JMS messages and to receive them
synchronously, but not asynchronously. To avoid tying up server resources, you may prefer
not to use blocking synchronous receives in a server-side component. To receive messages
asynchronously, use a message-driven bean.
7JB Interfaces
All bean classes must implement javax.ejb.EnterpriseBean, or one of its subinterfaces, at some level.
o javax.ejb.EnterpriseBean extends java.io.Serializable.
Session beans implement javax.ejb.SessionBean.
o javax.ejb.SessionBean extends javax.ejb.EnterpriseBean.
o It defines methods: ejbActivate, ejbPassivate, ejbRemove, and setSessionContext.
Entity Beans implement javax.ejb.EntityBean.
o javax.ejb.EntityBean extends javax.ejb.EnterpriseBean.
o It defines methods: ejbActivate, ejbPassivate, ejbRemove, setEntityContext, ejbLoad, ejbStore,
and unsetEntityContext.
Message Driven Beans implement javax.ejb.MessageDrivenBean.
o javax.ejb.MessageDrivenBean extends javax.ejb.EnterpriseBean.
o It defines methods: ejbRemove and setMessageDrivenContext.
MAT SOFT
JAVA REFERENCE GUIDE
665
9hat Constittes an 7JBM
7JB !"#ect
Client never invokes methods directly on an actual bean instance. All invocations go through the EJB object, which
is a tool-generated class. Message requests are intercepted by the EJB object and then delegated to the actual
bean instance. That is why it is called a request interceptor.
'emote Interface
A bean class exposes business methods that are cloned by the EJB object. But how do the tools that generate the
EJB object know which methods to clone? The answer is the remote interface. This interface duplicates all the
methods that the corresponding bean class exposes (remember that they must comply with the EJB specification).
Remote clients then access the bean via this remote interface. All remote interfaces must extend
javax.ejb.EJBObject.
(ome !"#ect
How do clients acquire references to EJB objects? The client asks for the EJB object from the EJB object factory.
This factory is responsible for instantiating and destroying the EJB objects. This factory is called the Home object.
(ome Interface
How does a home object know how you would like to initialize your EJB object? This information is provided to the
container through the home interface. The home interface contains the methods for creating, destroying, and
finding EJB objects. All home interfaces are derived from the javax.ejb.EJBHome interface and all home objects
implement the home interface. This interface extends java.rmi.Remote.
0oca$ Interfaces
Creating beans through the home interface and then calling the beans though the remote interface is very slow.
Local interfaces speed up beans' calls. Use local objects (implemented from a local interface rather than from a
remote interface) instead of EJB objects whenever possible. Also, use local home objects (implemented from a local
home interface rather than from a home interface) instead of home objects. Local interfaces extend
javax.ejb.EJBLocalObject and local home interfaces extend javax.ejb.EJBLocalHome.
)ep$oyment )escriptors
You state your deployment configuration in the deployment descriptor file named ejb-jar.xml.
Different application servers may have their own additional proprietary deployment descriptor files. These XML files
can either be edited by hand or with a tool provided by the container vendor. You can specify:
Bean management and lifecycle requirements.
Persistence requirements for entity beans.
Transaction requirements.
Security requirements, including access control entries.
MAT SOFT
JAVA REFERENCE GUIDE
666
7JB&J%' fi$e
Once you have finished compiling your classes and creating all of the necessary configuration files, you can place
all of these files into an EJB-JAR file for deployment. EJB-JAR files are zip files that contain Java classes and all the
other files needed for deployment. You can generate these files by hand or with tools, such as Apache Ant.
7JB 7xamp$e
The )irectory Strctre:
Create the following directory structure under some logical parent directory,
such as c:\ejb_example. This directory structure is for development purposes only; the deployment files will be
zipped into a jar file in a moment and deployed to jboss.
srcK
YGGc$ientK
Y YGGGcomK
Y YGGGexamp$esK
Y YGGGc$ient #ava fi$es
YGGserverK
Y YGGcomK
Y YGGGexamp$esK
Y YGGGserver ,"ean/ 4a8a 6l%s
YGGshared
Y YGGcomK
Y YGGGexamp$esK
Y YGGGremote and home #ava fi$es
Y
assem"$eK
YGGGc$ient and server #ars
Y
targetK
YGGGc$ientK
Y YGGGcomK
Y Y YGGGexamp$esK
Y Y YGGGc$ient< remote and home #ava c$asses
Y YGGG#ndi1properties
YGGGserverK
YGGcomK
Y YGGGexamp$esK
Y YGGGserver ,"ean/< remote and home 4a8a !lass%s
YGGGM7T%&IN+K
YGGGe#"&#ar1xm$
The Bean C$ass
create the bean class as src\server\com\examples\HelloBean.java. This class is a stateless session bean and
contains our business logic. In this case it prints out the exciting and always useful "Hello! World".
MAT SOFT
JAVA REFERENCE GUIDE
667
package com.examples;
import 9%<%A.ejb.*;
public class HelloBean implements SessionBean
{
public void ejbCreate() {}
public void ejbActivate() {}
public void ejbPassivate() {}
public void ejbRemove() {}
public void setSessionContext(SessionContext sc){}
public String sayHello ()
{
System.out.println ("Someone called sayHello()");
return "Hello! World;
}
}
The 'emote Interface
Create the remote interface as src\shared\com\examples\Hello.java. This is the interface
that remote clients talk to instead of talking directly to the bean class, HelloBean. Notice
that its only method is sayHello(), which is the business method in HelloBean.
package com.examples;
import javax.ejb.*;
import java.rmi.*;
public interface Hello extends EJBObject
{
public String sayHello() throws RemoteException;
}
The (ome Interface
Create the home interface as src\shared\com\examples\HelloHome.java. This interface will
be used to create an instance of the Hello interface when we want to execute the sayHello()
business logic.
MAT SOFT
JAVA REFERENCE GUIDE
668
package com.examples;
import javax.ejb.*;
import java.rmi.*;
public interface Hello extends EJBObject
{
public String sayHello() throws RemoteException;
}
The C$ient
create the client as src\client\com\examples\HelloClient.java. This is the "remote" client that
will use our session bean. First, it uses the InitialContext to get a handle to HelloHome. It
then uses the HelloHome interface to create hello. hello is a remote interface representing
our bean class. After hello is used to execute the business logic (sayHello), the bean is
released via the remove method.
package com.examples;
import javax.ejb.*;
import java.rmi.*;
import javax.rmi.*;
import javax.naming.*;
public class HelloClient
{
public static void main (String[] args) throws Exception
{
Context c = new InitialContext();
Object o = c.lookup ("Hello");
HelloHome home =
(HelloHome)PortableRemoteObject.narrow (o,HelloHome.class);
Hello hello = home.create();
System.out.println (hello.sayHello());
hello.remove();
}
}
e#"&#ar1xm$
Create the ejb-jar.xml file in target\server\META-INF. This deployment descriptor contains
MAT SOFT
JAVA REFERENCE GUIDE
669
information that the jboss EJB container needs in order to deploy and run our EJB.
<!DOCTYPE ejb-jar PUBLIC "-//S.0 M#,-($'$"16$, Inc.//DTD Enterprise
J%<%B1%0$ 2.0//EN" "http://java.sun.com/dtd/ejb-jar_2_0.dtd">
<ejb-jar>
<enterprise-beans>
<session>
<ejb-name>Hello</ejb-name>
<home>com.examples.HelloHome</home>
<remote>com.examples.Hello</remote>
<ejb-class>com.examples.HelloBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Container</transaction-type>
</session>
</enterprise-beans>
</ejb-jar>
#ndi1properties
Create the jndi.properties file in target\client. This file defines properties that are required in
order to use JNDI to find EJBs on the network.
java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.provider.url=jnp://localhost:1099
)ep$oying 7JB
Compi$e C$asses
The following commands should be executed from the top of the directory structure created
earlier (c:\ejb_example on my computer). Also, you'll need to ensure your 9%<%, command
is working and that you have the proper development kits installed. (These commands are
for Microsoft Windows. If running this example on another operating system, just edit these
commands as required.) The LIBDIR variable should point to the directory that
contains 95($$-j2ee.jar.
(The line breaks are for formatting only. Execute these on one line.)
javac -,*%$$/%"2 %LIBDIR%\jboss-j2ee.jar -d
target\client src\client\com\examples\*.java
src\shared\com\examples\*.java
MAT SOFT
JAVA REFERENCE GUIDE
670
javac -classpath %LIBDIR%\jboss-j2ee.jar -d
target\server src\server\com\examples\*.java
src\shared\com\examples\*.java
Create the Jar +i$es
Remember that EJBs execute in an EJB container on the server. In our case this will be the
jboss application server. We need to package the server code into a jar file named
helloserver.jar. This jar will be copied into the proper jboss deployment directory in the next
step. Likewise, we need to package the client code, the code that will call and use the EJB,
into a jar file named helloclient.jar. The client code can be run from any computer on the
network, but in our case we'll just run jboss in one DOS window and the client in another
DOS window on the same computer.
Execute the following command from your c:\ejb_example\target\client directory. (Don't
forget the trailing "." at the end.)
jar cvf ..\..\assemble\helloclient.jar .
Execute the next command from your c:\ejb_example\target\server directory. (Again, there
is a trailing ".".)
jar cvf ..\..\assemble\helloserver.jar .
After executing these jar commands you should have a helloclient.jar and a helloserver.jar
in the assemble directory.
)ep$oy to #"oss
1. Create a JBOSS_HOME environment variable and set it to the jboss installation
MAT SOFT
JAVA REFERENCE GUIDE
671
directory (for instance, c:\jboss-3.2.5).
2. Create a LIBDIR environment variable and set it to the client directory under
JBOSS_HOME (for instance, %JBOSS_HOME%\client).
3. Place the helloserver.jar in the %JBOSS_HOME%\server\default\deploy directory.
4. From the command prompt:
%JBOSS_HOME%\bin\run.bat
When jboss starts up, you should see logging statements indicating that the Hello EJB has
been deployed. Here is what I have in my command window:
08:56:07,656 INFO [EjbModule] Deploying Hello
08:56:08,424 INFO [EJBDeployer] Deployed: file:c:\jboss-
4.0.1sp1\server\default\deploy\helloserver.jar
'n The C$ient
To run the client, open a new DOS window (you should have jboss already running in a
separate window).
1. Create a JBOSS_HOME environment variable and set it to the jboss installation
directory (for instance, c:\jboss-3.2.5)
2. Create a LIBDIR environment variable and set it to the client directory under
JBOSS_HOME (for instance, %JBOSS_HOME%\client)
3. Change directory to the assemble directory that contains helloclient.jar
4. From the command prompt (all as one line)
MAT SOFT
JAVA REFERENCE GUIDE
672
java -classpath helloclient.jar;%LIBDIR%\jnp-client.jar;%LIBDIR%\jboss-common-
client.jar;
%LIBDIR%\jboss-j2ee.jar;%LIBDIR%\jboss-net-client.jar;%LIBDIR%\jbossall-client.jar;;
%LIBDIR%\jnet.jar
com.examples.HelloClient
In your client DOS window, you should see "Hello! World" print out. In the server DOS
window, you should see "Someone called sayHello()" print out. The client just executed our
sayHello business method from within the jboss application server.
)ay VH: Strts
W2%" #$ W15 A//*#,%"#(0 D1<1*(/610" M(31*$K
W15 A//*#,%"#(0 D1<1*(/610" 6(31* #$ /-(<#3#0+ % $"%03%-3 &%' "( 31<1*(/ % &15
%//*#,%"#(04
I0 &2%" /*%,1 &2%" "1,20(*(+' #$ $.#"%5*1 )(- 31<1*(/#0+ % &15 %//*#,%"#(0 #$
0("2#0+ 5." LW15 A//*#,%"#(0 D1<*1/610" 6(31*$M4
M(31*$
T21$1 %-1 "&( 6(31*$
M(31*;1
M(31*;2
M(31*;1 2%$ $(61 3-%&5%,:$ #0 (-31-13 "( (<1-,(61 "2($1 /-(5*16$ &1 +( )(-
M(31*;2 31$#+07%*$( ,%**13 %$ MVC 6(31*8
W2' W15 A//*#,%"#(0 D1<1*(/610" 6(31*$K
MAT SOFT
JAVA REFERENCE GUIDE
673
W210 %0 %//*#,%"#(0 #$ +#<10 )(- "&( 31<1*(/1-$ "210 "21 31$#+0$ +#<10 5' "21 "&(
31<1*(/1-$ )(- "21 $%61 %//*#,%"#(0 6%' 0(" 51 $%61 51,%.$1 "21 %//*#,%"#(0
31$#+0 31/103$ (0 2(& % 31<1*(/1- #$ .031-$"%03#0+ % &15 %//*#,%"#(04
I) (01 31<1*(/1- &%0"$ "( .031-$"%03 "21 31$#+0 +#<10 5' ("21- 31<1*(/1- "210 #"
51,(61$ <1-' 3#N,.*"4
I0 (-31-13 "( $(*<1 "21$1 %//*#,%"#(0 31$#+0 /-(5*16$ %03 %*$( "( #0)(-6 "2%" LW2%"
"1,20(*(+' #$ $.#"%5*1 )(- &2%" /*%,1 L> &1 +(" &15 %//*#,%"#(0 31<1*(/610"
6(31*$4
M(31*1
I0 6(31*;1 %-,2#"1,".-1 "21 6%#0 3-%&5%,: #$ P%+1 C10"-#, /-(5*164T21 %//*#,%"#(0$
31<1*(/13 5' .$#0+ 6(31*;1 %-,2#"1,".-1 ,(0"%#0$ % $1-#1$ () JSP &#"2 %** "21 *(+#,$
-1D.#-13 )(- "21 %//*#,%"#(04
I0 "2#$ M(31*;1 % JSP "1,20(*(+' #$ -1$/(0$#5*1 )(- #6/*1610"#0+ %** *(+#,$ *#:1 "21
/-1$10"%"#(0 *(+#,>5.$$#01$$ *(+#, %03 "21 3%"%5%$1 *(+#,4
M(31*;1
D-%&5%,:$ () M(31*;1
A** *(+#,$ %-1 #6/*1610"13 .$#0+ % $#0+*1 "1,20(*(+'7JSP8 $( 3#<#$#(0 () *%5(.- #$ 0("
/($$#5*14
A,"#(0S1-<*1"
14 T21 (0*' (01 $1-<*1" ,*%$$ "2%" #$ +#<10 5' $"-."$ )-%61&(-: #$ A,"#(0S1-<*1"4
24 A,"#(0S1-<*1" ,*%$$ #$ $%#3 "( 51 ,(0"-(**1- () % $"-."$ %//*#,%"#(04
34 I" #$ %<%#*%5*1 #0 "21 /%,:%+1 (-+4%/%,214$"-."$4%,"#(0
K1' /(#0"$
14 T21 2#+2 *1<1* (591," () $"-."$ )-%61 &(-: #$ A,"#(0S1-<*1" %03 "21 (591," () "2#$
,*%$$ #$ ,-1%"13 5' "21 &15,(0"%#01- %03 %** "21 -16%#0#0+ "21 (591,"$ () $"-."$
%//*#,%"#(0 %-1 ,-1%"13 5' "2#$ A,"#(0S1-<*1"4
24 A,"#(0S1-<*1" 6%0%+1$ "21 10"#-1 ,(0"-(* O(& #0)(-6%"#(0 )-(6 1A"1-0%*
,(0C+.-%"#(0 C*1 &1 ,%** "2#$ C*1 %$ S"-."$ ,(0C+.-%"#(0 C*1
A,"#(0F(-6
T21 /.-/($1 () A,"#(0F(-6 #$ "( $"(-1 % ,*#10" <%*.1$ %" $1-<1- $#314
MAT SOFT
JAVA REFERENCE GUIDE
674
A,"#(0F(-6 #$ %*$( ,%**13 %$ % F(-6B1%0 (- % 9%<% B1%0 #0 $"-."$4I0 (-31-13 "( .$1
F(-6B1%0 ,*%$$1$ #0 $"-."$ &1 0113 "( $.5,*%$$ (.- ,*%$$ )-(6 A,"#(0F(-6
I" #$ %<%#*%5*1 #0 (-+4%/%,214$"-."$4%,"#(0 /%,:%+14
K1' /(#0"$
F(-6 B1%0 ,*%$$1$ >&1 0113 "( ,(0C+.-1 #0 S"-."$ ,(0C+.-%"#(0 C*14T( ,(0C+.-1 %0
A,"#(0F(-6 ,*%$$ #0 $"-."$;,(0C+4A6* C*1 "21 1*1610" #$ P)(-6;51%0Q>"2#$ 1*1610"
6.$" 51 #0,*.313 #0$#31 P)(-6;51%0$Q 1*1610"4
P$"-."$;,(0C+Q
P)(-6;51%0$Q
P)(-6;51%0 0%61RM*(+#,%* 0%61M "'/1RM,*%$$ 0%61MSQ
P)(-6;51%0$Q
PS$"-."$;,(0C+Q
A,"#(0 ,*%$$
T2#$ ,*%$$ #$ .$13 "( #6/*1610" 1#"21- 5.$#01$$ *(+#,4
I0 (-31-13 "( ,-1%"1 (.- (&0 A,"#(0 ,*%$$ "210 (.- ,*%$$ $2(.*3 1A"103 "21 5%$1
,*%$$ A,"#(04
A,"#(0 #$ % ,*%$$ +#<10 #0 (-+4%/%,214$"-."$4%,"#(04
I0 A,"#(0 ,*%$$ &1 (<1--#31 $#0+*1 61"2(3 ,%**13 1A1,."178 )(- #6/*1610"#0+
5.$$#01$$ *(+#,4
K1' /(#0"$
P.5*#, ,*%$$ L(+#0A,"#(0 1A"103$ A,"#(0
T
P.5*#, A,"#(0F(-&%-3 1A1,."17A,"#(0M%//#0+ 6%/>A,"#(0F(-6
)(-6>@""/S1-<*1"R1D.1$" -1D>@""/S1-<*1"R1$/(0$1 -1$8"2-(&$ EA,1/"#(0
T
;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;
MAT SOFT
JAVA REFERENCE GUIDE
675
U
U
K1' /(#0"$
A,"#(0 ,*%$$ 6.$" %*$( 51 ,(0C+.-13 #0 "21 $"-."$ ,(0C+4A6* C*1
P$"-."$;,(0C+Q
P%,"#(0;6%//#0+$Q
P%,"#(0 /%"2RMS%,"#(0/%"2 610"#(013 #0 JSPM 0%61RM0%61 #0 "21 )(-6;51%0 "%+M
"'/1RMA,"#(0 ,*%$$ 0%61MQ
P)(-&%-3 0%61RM$.,1$$M /%"2RMS$.,,1$$49$/MSQ
P)(-&%-3 0%61RM)%#*.-1M /%"2RMS)%#*.-149$/MSQ
PS%,"#(0Q
PS%,"#(0;6%//#0+$Q
PS$"-."$;,(0C+Q
A,"#(0F(-&%-3
/.5*#, A,"#(0F(-&%-3 1A1,."17A,"#(0M%//#0+ 6%/>A,"#(0F(-6
)(-6>;;;;;;;;;>;;;;;;;;;;;;;8T
A,"#(0F(-&%-3 %)R6%/4C03F(-&%-37L$.,1$$M8V
-1".-0 %)V
U
K1' /(#0"$
MAT SOFT
JAVA REFERENCE GUIDE
676
A,"#(0F(-&%-3 ,*%$$ $"(-1$ $(61 2#0" <%*.17*(+#,%* 0%618 %03 /-(<#31$ "2#$
#0)(-6%"#(0 "( ,(0"-(**1- %03 "21 ,(0"-(**1- $1*1,"$ "21 %//-(/-#%"1 <#1& /%+1
%6(0+ 6.*"#/*1 <#1& /%+1$ () "21 %//*#,%"#(04
A,"#(0M%//#0+
T2#$ ,*%$$ (591," ,(0"%#0$ #0)(-6%"#(0 %5(." %0 %,"#(0 .$13 5' "21 ,(0"-(**1- #0
(-31- "( #310"#)' "21 5.$$#01$$ ,*%$$ *(+#, "2%" #$ $.#"%5*1 #0 (-31- "( 2%03*1 "21
+#<10 -1D.1$"4
?$#0+ R1$(.-,1B.03*1 #0 $"-."$
T21 R1$(.-,1 B.03*1 #$ %*$( ,%**13 %$ % P-(/1-"#1$ C*14
I0 % R1$(.-,1 B.03*1 "21 3%"% &#** 51 $"(-13 #0 "21 )(-6 () L:1';<%*.1M /%#-$ )(-6%"
V%*#3%"#(0 #0 S"-."$
I0 $"-."$ )-%61 &(-: >&1 ,%0 %//*' "21 <%*#3%"#(0$ (0 "21 .$1- #0/." #0 "&(
%//-(%,21$
14P-(+-%6%"#, %//-(%,2
24D1,*%-%"#<1 %//-(%,2
MAT SOFT
JAVA REFERENCE GUIDE
677
P-(+-%6%"#, %//-(%,2 61%0$ "21 /-(+-%661- 2%$ "( 6%0.%**' (<1--#31 <%*#3%"178
61"2(3 () A,"#(0F(-6 ,*%$$4
D1,*%-%"#<1 %//-(%,2 61%0$ "21 <%*#3%"#(0$ %-1 %//*#13 "2-(.+2 %0 IML C*1
,-1%"#(04
P-(+-%66%"#, %//-(%,2
I) %0' 1--(- #$ (,.--13 3.-#0+ "21 <%*#3%"#(0 "210 &1 2%<1 "( ,(0$"-.," %0 (591," ()
A,"#(0M1$$%+1 ,*%$$ 4
W2#*1 ,(0$"-."#0+ A,"#(0M1$$%+1 (591," &1 0113 "( /%$$ "21 :1' () "21 5.03*1 #0
(-31- "( +1" "21 1--(- 61$$%+1 )-(6 "21 5.03*14
E%,2 A,"#(0M1$$%+1 (591," &1 2%<1 "( %33 "21 A,"#(0E--(-$ ,*%$$ (591,"4
D#$/*%'#0+ E--(- 61$$%+1 (0 JSP
W2#*1 3#$/*%'#0+ %0 1--(- 61$$%+1 &1 ,%0 3#$/*%' 1--(- 61$$%+1 )(- 1%,2 /-(/1-"'
$1/%-%"1*' 4F(- "2#$ &1 $2(.*3 .$1
P2"6*G1--(-$Q "%+ &#"2 /-(/1-"' %""-#5."14
P2"6*G1--(-$ /-(/1-"'RM.0%61MSQ
DynaActionForm is class given in "org.apache.struts.action package and it is extended from
ActionForm.
In manual ActionForm there is a problem and that is if any modifications are done in the jsp design
then we need to modify our ActionForm class also according to the new design.
Because ActionForm is a java file, so when ever the java file is modified then we need to recompile ,
reload the application and some times we have to restart the server this problem can be eliminated or
removed by using DynaActionForm class.
DynaActionForm class is directly configured into struts configuration file we need not create a
separate java file for the FormBeanClass
<struts-config>
<form-beans>
<form-bean name="LoginFormBean" type="org.apache.struts.action.DynaActionForm">
MAT SOFT
JAVA REFERENCE GUIDE
678
<form-property name="uname" type="java.lang.String"/>
<form-property name="pwd" type="java.lang.String"/>


</form-bean>
</form-beans>
If we use DynaActionForm then the validation on the input is possible at Action class.
If we use validation at Action class then we need to store each ActionMessage object into ActionErrors
object.Finally we need to store ActionErrors object into HttpServletRequest object.
In order to store an ActionErrors object into HttpServletRequest object we need to call
saveErrors().This method is given by the super class Action.
If we store ActionErrors object into HttpServletRequest object then only the error messages can be
displayed by using <html:errors> on the browser.
While executing the logic of an action class ,if any problem occurred on the client browser that
exception stack trace will be printed but the clients are unknown about the exceptions ,so they cant
understand the problem.
In order to overcome this problem and in order to display complete message on the browser we
Need to handle that exceptions.
In struts we can do exceptional handling in two approaches
1. Declarative exception approach
2.Programmatic exceptional approach
Programmatic approach:
In Programmatic approach we need to put the logic of Action class with in the try and catch blocks,if
any exception is occurred then we can return some error hint and for that an error page will be
selected by the controller and finally the error page will display some meaning full message on to the
browser.
Declarative approach:
We use a new element called <exception> in the struts config file under <action> element.
In struts config file
MAT SOFT
JAVA REFERENCE GUIDE
679
<action path=/test name=form1 type=testaction>
<exception key=some.error type=java.lang.Exception path=/Error.jsp/>
</action>
In the above configuration the <exception> tag is return inside <action>, so it is a local exceptional
handling.
The error message must be taken from the resource bundle in order to display the message on the
browser we must use <html:errors> tag in Error.jsp
The advantage of declarative approach is when multiple action classes are there then instead of
writing local exception handling for each action separately we can also perform global-exception
handling
<global-exceptions> tag must be before <action-mappings> tag in the struts config file.
If we want to write global exception hanlding then we should put exception tag inside <global-
exceptions>

You might also like