Professional Documents
Culture Documents
A B O U T T H E JPT
Java JPT
Java is a high-level programming language originally dev eloped by Sun Microsystems and released in
1995. Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.
This tutorial gives a complete understanding on Java.
This reference will take you through simple and practical approach while learning Java
Programming language.
Audience
This reference has been prepared for the beginners to
adv anced concepts related to Java Programming languages.
help
them
understand
the
basic
to
Prerequisites
Before you start doing practice with various types of examples given in this reference, I'm making an
assumption that you are already aware about what is a computer program and what is a
computer programming language.
the content and graphics on this tutorial are the property of Sk. Bilal Ahmed. Any content from
JPT or this tu torial may not be redistributed or reproduced in any way, shape, or form without the
written permission of tutorialspoin t.com. Failure to do so is a violation of copy right laws.
This JPT may contain inaccuracies or errors and tutorials provides no guarantee regarding the accuracy
of the colleting several Info or its contents including this tutorial. If you discov er tha t the JPT Info or this
tutorial content contains some errors, please contact us at shaikbilalahmed @sify.com or +91
81437 8696 8
Table of Content
Java Tutorial ............................................................................ 2
Audience .................................................................................. 2
Prerequisites ............................................................................ 2
Copyright & Disclaimer Notice.................................................. 2
Java Overview ....................................................................... 13
Histor y of Ja va: ........................................................................................14
Tools you will need :..................................................................................14
Wha t is Next ? ..........................................................................................14
Java Methods......................................................................... 95
Creating a Method:...................................................................................95
Example : ..................................................................................................96
Calling a Method : .....................................................................................96
Example : ..................................................................................................96
The void Keyword : ...................................................................................97
Example : ..................................................................................................97
JAVA PROGRAMMING TUTORIAL
BILAL AHMED SHAIK
Reading Directories:...............................................................................121
Example : ................................................................................................179
CHAPTER
Java Overview
ava programm ing language was originally de veloped b y Sun Micros ys tems , which was initiated by James
Gos ling and releas ed in 1995 as core component of Sun Microsy st ems s Java platform (Java 1.0 [J2SE]).
As of December 08 the lates t releas e of the Java Standard Edition is 6 (J2SE). With the ad vancement of Java
and its wide spread popularity, m ultiple configurations were built to s uite various types of platforms . Ex: J2EE for
Enterpris e Applications , J2ME for Mobile Applications .
Sun Micros ys tems has renam ed the new J2 vers ions as Java SE, Ja va EE and Ja va ME res pectivel y. Ja va is
guaranteed to be Write Once, Ru n An yw here
Java is :
Object Oriented : In ja va e ver ything is an Object. Ja va can be eas ily e xtended s ince it is bas ed on the
Object m odel.
Platform independent: Unlike m any other programming languages including C and C++ when Java is
compiled, it is not compiled into platform s pecific machine, rather i nto platform independent byte code.
This byte code is dis tributed o ver the web and interpreted by virtual Machine (JVM) on
whichever platform it is being run.
Simple :Java is des igned to be eas y to learn. If you unders tand the basic concept of OOP java would be
eas y to m as ter.
Secure : With Ja va's secure feature it enables to develop virus -free, tam per-free s ys tems . Authentication
techniques are based on public-key encryption.
Architectural- neutra l :Ja va com piler generates an architecture-neutral object file form at which m akes
the compiled code to be executable on m any process ors , with the pres ence Java runtim e s ys tem .
Portable :being architectural neutral and havi ng no im plem entation dependent as pects of
the s pecification m akes Java portable. Compiler and Ja va is written in ANSI C with a clean
portability boundary which is a POSIX s ubs et.
Robust :Ja va m akes an effort to elim inate error prone s ituations by em phasizing m ainly on com pile time
error checking and runtim e checking.
Multi-t hreaded : With Ja va's m ulti-threaded feature it is poss ible to write programs that can do m any
tas ks s im ultaneously. This des ign feature allows de velopers to cons truct smoothly running
interactive applications .
Interpreted :Ja va b yte code is trans lated on the fly to nati ve m achin e ins tructions and is not
s tored anywhere. The de velopm ent process is m ore rapid and analytical s ince the linking is an
increm ental and light weight process .
High Performance : With the us e of Jus t-In-Tim e com pilers Java enables high perform ance.
Distribute d :Ja va is des igned for the dis tributed environment of the internet.
Dynamic : Java is considered to be m ore dynamic than C or C++ s ince it is des igned to adapt to an
evol ving environment. Java programs can carry extens ive am ount of run -tim e inform ation that can be
us ed to verify and res olve access es to objects on run-tim e.
History of Java:
James Gosling initiated the Java language project in June 1991 for us e in one of his many s et-top box projects .
The language, initially called Oak after an oak tree tha t s tood outs ide Gos ling's office, als o went by the nam e
Green and ended up later renam ed as Java, from a lis t of random words .
Sun releas ed the firs t public im plem entation as Java 1.0 in 1995. It prom ised Write Once, Run
An yw here (WORA), pro viding no-cos t run-tim es on popular platforms .
On 13 Novem ber 2006, Sun rel eas ed m uch of Ja va as free and open s ource s oftware under the terms of the
GNU General Public Licens e (GPL).
On 8 Ma y 2007 Sun finished the process , making all of Ja va's core code free an d open-source, aside from a
sm all portion of code to which Sun did not hold the cop yright.
Java JDK 5
This tutorial will provide the necessary s kills to create GUI, networking, and Web applications using Java.
What is Next ?
Next chapter will guide you to where you can obtain Ja va and its docum entation. Finally, it ins tructs you on how to
ins tall Java and prepare an environm ent to de velop Ja va applications .
CHAPTER
efore we proceed further it is im portant that we s et up the java environment correctly. This section
guides you on how to download and s et up Java on your m achine. Pleas e follow the following s teps to s et up the
environment.
Java SE is freely a vailable from the link Download Ja va. So you downlo ad a version bas ed on your operating
s ys tem .
Follow the ins tructions to download ja va and run the .exe to ins tall Java on your m achine. Once you
ins talled
Java on your m achine, you w ould need to s et en vironm ent variables to point to correct ins tallation directories :
Click on the 'Environm ent variables ' button under the 'Ad vanced' tab.
Now alter the 'Path' variable so that it als o contains the path to the Java e xecutable . Exam ple, i f the path is
currently
s et
to
'C:\WINDOWS\S YSTE M32',
then
change
your
path
to
read
'C:\WINDOWS\SYSTE M32;c:\Program Files \java\jdk\bin'.
Edit
the
'C:\autoe xe c.bat'
file
and
add
'SET P ATH=%P ATH%;C:\Program Files \java\jdk\bin'
the
following
li ne
at
the
end:
Notepad : On Windows machine you can us e any s im ple text editor like Notepad (Recomm ended for this
tutorial), Te xtPad .
Netbeans :is a Ja va IDE that is open s ource and free which can be downloaded
from http://www.netbeans .org/index.htm l.
Eclipse : is also a java IDE de veloped b y the eclips e open source c omm unity and can be
downloaded from http://www.eclipse.org/.
What is Next ?
Next chapter will teach you how to write and run your firs t ja va program and som e of the im portant basic s yntaxes
in java needed for de veloping appli cations .
CHAPTER
hen we cons ider a Java program it can be defined as a collection of objects that com municate via
invoking each others m ethods . Let us now briefly look into what do class , object, m ethods and ins tance variables
m ean.
Object - Objects have s tates and beha viors . Exam ple: A dog has s tates -color, nam e, breed as well
as behaviors -wagging, barking, eating. An object is an ins tance of a class .
Class - A class can be defined as a tem plate/ blue print that des cribe the behaviors /s tates that object o f its
type s upport.
Methods - A m ethod is bas ically a beha vior. A class can contain m any m ethods . It is in m ethods where the
logics are written, data is manipulated and all the actions are executed.
Instance Variables - Each object has its unique set of ins tance variables . An object's s tate is created by the
values ass igned to these ins tance variables .
Open a command prom pt window and go o the directory where you s aved the class . As sum e its C:\.
Type ' ja vac MyFirs tJavaProgram .ja va ' and press enter to com pile your code. If there are no errors in your
code the comm and prom pt will take you to the ne xt line.( As s um ption : The path variable is s et).
You will be able to s ee ' Hello Wo rld ' printed on the window.
Basic Syntax:
About Ja va programs , it is very im portant to keep in m ind the following points .
Case Sensitivity - Ja va is cas e s ensitive which means identifier Hello and hello would ha ve differen t
m eaning in Java.
Class Names - For all class nam es the firs t letter s hould be in Upper Case.
If s everal words are us ed to form a nam e of the class each inner words firs t letter s hould be in Upper Case.
public static void main(String args[]) - ja va program process ing s tarts from the main() m ethod which is a
m andatory part o f e ver y ja va program .
Java Identifiers:
All ja va com ponents require nam es . Nam es used for class es , variables and m ethods are called identifiers .
In java there are s everal points to rem ember about identifiers . They are as follows :
All identifiers should begin with a letter (A to Z or a to z ), currency character ($) or an unders core (_).
1_ value
Java Modifiers:
Like other languages it is poss ible to m odify class es , methods etc b y us ing m odifiers . There are two categories of
m odifiers .
We will be looking into m ore details about m odifiers in the next s ection.
Java Variables:
We would s ee following type of variab les in Java:
Local Variables
Class Variables (Static Variables )
Java Arrays:
Arra ys are objects that s tore m ultiple variables of the sam e type. Howe ver an Arra y its elf is an object on the heap.
We will look into how to declare, cons truct and initiali ze in the upcom ing chapters .
Java Enums:
Enums were introduced in java 5.0. Enums res trict a variable to ha ve one of onl y a few predefined values . The
values in this enum erated lis t are called enums .
With the us e of enums it is possible to reduce the number of bugs in your code.
For exam ple if we cons ider an application for a fres h juice s hop it would be possible to res trict the glass size to
sm all, medium and Large. This would m ake s ure that it would not allow anyone to order an y size other than the
sm all, m edium or large.
Example:
class FreshJuice {
enum FreshJuiceSize{ SMALL, MEDUIM, LARGE }
FreshJuiceSize size;
}
public class FreshJuiceTest {
public static void main(String args[]){
FreshJuice juice = new FreshJuice();
juice.size = FreshJuice. FreshJuiceSize.MEDUIM ;
}
}
Note : enums can be declared as their own or inside a class . Methods , variables , cons tructors can be defined
inside enums as well.
Java Keywords:
The following lis t s hows the res erved words in Java. Thes e res erved words m ay not be us ed as cons tant
or variable or an y other identifier nam es .
abs tract
assert
boolean
break
byte
case
catch
char
class
cons t
continue
default
do
double
else
enum
extends
final
finally
float
for
goto
if
im plem ents
im port
ins tanceof
int
interface
long
native
new
package
private
protected
public
return
s hort
s tatic
s trictfp
s uper
s witch
s ynchronized
this
throw
throws
transient
try
void
volatile
while
Comments in Java
Java s upports single line and m ulti-line comm ents very s im ilar to c and c++. All characters available ins ide any
comm ent are ignored by Ja va com piler.
public class MyFirstJavaProgram{
/* This is my first java program.
* This will print 'Hello World' as the output
* This is an example of multi-line comments.
*/
Inheritance:
In java class es can be derived from class es . Basically if you need to create a new class and here is already a
class that has s ome of the code you require , then it is possible to derive your new class from the already e xis ting
code.
This concept allows you to reus e the fields and m ethods of the exis ting class with out having to rewrite the code in
a new class . In this s cenario the exis ting class is called the s uper class and the derived class is called
the s ubclass .
Interfaces:
In Java language an interface can be defined as a contract between objects on how to comm unicate with each
other. Interfaces play a vital role when it com es to the concept of inheritance.
An interface defines the m ethods , a deriving class (s ubclass ) s hould us e. But the im plem entation of the m e thods
is totally up to the s ubclass .
What is Next ?
The next s ection explains about Objects and class es in Java programm ing. At the end of the sess ion you will be
able to get a clear picture as to what are objects and what are class es in java.
CHAPTER
ava is an Object Oriented Lan guage. As a language that has the Object Oriented feature Ja va s upports the
Polym orphism
Inheritance
Encaps ulation
Abs traction
Class es
Objects
Ins tance
Method
Mes sage Pars ing
In this chapter we will look into the concepts Classes and Objects .
Object - Objects have s tates and beha viors . Exam ple: A dog has s tates -color, nam e, breed as well
as behaviors -wagging, barking, eating. An object is an ins tance of a class .
Class - A class can be defined as a tem plate/ blue print that des cribe the behaviors /s tates that object o f its
type s upport.
Objects in Java:
Let us now look deep into what are objects . If we cons ider the real -world we can find m any objects around us ,
Cars , Dogs , Hum ans etc. All thes e objects have a s tate and behavior.
If we cons ider a dog then its s tate is - name, breed, color, and the beha vior is - barking, wagging , running
If you com pare the s oftware object with a real world object, the y ha ve ver y s im ilar characteris tics .
Software objects als o have a s tate and behavior. A s oftware object's s tate is s tored in fields and behavior
is s hown via methods .
So in s oftware developm ent methods operate on the internal s tate of an object and the object-to-object
comm unication is done via m ethods .
Classes in Java:
A class is a blue print from which individual objects are created.
A s am ple of a class is given below:
public class Dog{
String breed;
int age;
String color;
void barking(){
}
void hungry(){
}
void sleeping(){
}
}
A class can contain any of the foll owing variable types .
Local variables . variables d efined ins ide methods , cons tructors or blocks are called local variables .
The variable will be declared and initiali zed within the m ethod and the variable will be des troyed when the
m ethod has completed.
Instance variables . Ins tance variables are variables within a class but outside any m ethod. Thes e variables
are ins tantiated when the class is loaded. Ins tance variables can be accessed from ins ide any
m ethod,
cons tructor or blocks of that particular class .
Class variables . Class variables are variables declared with in a class , outside any m ethod, with the s tatic
keyword.
A clas s can have any num ber of methods to access the value of various kind of m ethods . In the abo ve e xam ple,
barking(), hungry() and sleeping() are m ethods .
Below m entioned are s om e of the im portant topics that need to be dis cuss ed when looking into class es of the
Java Language .
Constructors:
When dis cuss ing about classes one of the mos t im portant sub topic would be cons tructors . Every class has a
cons tructor. If we do not explicitl y write a cons tructor for a class the java com piler builds a default cons tructor for
that class .
Each time a new object is created at leas t one cons tructor will be invoked. The m ain rule of cons tructors is that
they s hould have the s am e nam e as the class . A class can have m ore than one cons tructor.
Exam ple of a cons tructor is given below:
public class Puppy{
public puppy(){
}
public puppy(String name){
// This constructor has one parameter, name.
}
}
Java als o s upports Singleton Class es where you would be able to create onl y one ins tance of a class .
Creating an Object:
As m entioned previously a class provides the blueprints for objects . So basically an object is created from a class .
In java the new ke y word is us ed to create new objects .
There are three s teps when creating an object from a class :
Example:
This exam ple explains how to access ins tance variables and methods of a class :
public class Puppy{
int puppyAge;
public Puppy(String name){
// This constructor has one parameter, name.
System.out.println("Passed Name is :" + name );
}
public void setAge( int age ){
puppyAge = age;
}
public int getAge( ){
The public class name should be the nam e of the source file as well which s hould be appended by .java at
the end. For e xample : The class nam e is . pub lic class Em ployee{} Then the source file s hould be
as Em ployee.java .
If the class is defined ins ide a package, then the package s tatem ent should be the firs t s tatem ent in
the s ource file.
If im port s tatem ents are pres ent then they m us t be written between the package s tatem ent and the class
declaration. If there are no package s tatem ents then the import s tatem ent should be the firs t line in
the s ource file.
Im port and package s tatem ents will im ply to all the class es pres ent in the s ource file. It is not poss ible to
declare different im port and/or package s tatements to different class es in the s ource file.
Class es have s everal access levels and there are different types of class es ; abs tract class es , final classes etc. I
will be explaining abou t all thes e in the access m odifiers chapter.
Apart from the above m entioned types of class es , Java als o has s ome special classes called Inner class es and
Anon ym ous class es .
Java Package:
In sim ple it is a way of categori zing the class es and interfaces . When developing applications in Ja va, hundreds
of class es and interfaces will be written, therefore categorizing thes e class es is a mus t as well as makes life m uch
easier.
Import statements:
In java i f a full y qualified name, which includes the package and the class nam e, is given then the com piler can
easily locate the source code or class es . Im port s tatem ent is a way of gi ving the proper location for the com piler
to find that particular class .
For exam ple following line would as k com piler to load all the class es available in direc tory ja va_ins tallation/java/io
import java.io.*;
As mentioned previously in this tutorial processing s tarts from the main m ethod. Therefore in-order for us to run
this Employee class there should be m ain m ethod and objects s hould be created. We will be creating a s eparate
class for thes e tas ks .
Given below is the Em ployeeTest class which creates two ins tances of the class Employee and invokes
the m ethods for each object to assign values for each variable.
Save the following code in Em plo yeeTes t.java file
import java.io.*;
public class EmployeeTest{
public static void main(String args[]){
/* Create two objects using constructor */
Employee empOne = new Employee("James Smith");
Employee empTwo = new Employee("Mary Anne");
// Invoking methods for each object created
empOne.empAge(26);
empOne.empDesignation("Senior Software Engineer");
empOne.empSalary(1000);
empOne.printEmployee();
empTwo.empAge(21);
empTwo.empDesignation("Software Engineer");
empTwo.empSalary(500 );
empTwo.printEmployee();
}
}
Now compile both the classes and then run EmployeeTest to s ee the result as follows :
C :> javac Employee.java
C :> vi EmployeeTest.java
C :> javac EmployeeTest.java
C :> java EmployeeTest
Name:James Smith
Age:26
Designation:Senior Software Engineer
Salary:1000.0
Name:Mary Anne
Age:21
Designation:Software Engineer
Salary:500.0
What is Next ?
Next s ess ion will dis cuss bas ic data types in java and how the y can be used when developing ja va applications .
CHAPTER
ariables are nothing but res erved m em ory locations to s tore values . This m eans that when you create a
byte:
Byte data t ype is a 8-bit s igned two's com plem ent integer.
Default value is 0
Byte data t ype is us ed to s ave space in large arrays , m ainly in place of integers , since a byte is four tim es
sm aller than an int.
short:
Short data type is a 16-bit signed two's com plem ent integer.
Short data type can als o be us ed to save m em ory as byte data type. A s hort is 2 times smaller than an int
Default value is 0.
int:
int data type is a 32-bit signed two's com plem ent integer.
Int is generally us ed as the default data type for integral values unless there is a concern about m em ory.
long:
Long data type is a 64-bit signed two's com plem ent integer.
float:
Float data type is a s ingle-precis ion 32-bit IEEE 754 floating point.
Float is m ainly us ed to s ave mem ory in large arra ys of floating point num bers .
double:
This data type is generally used as the default data type for decim al values . generall y the defaul t choice .
Double data type s hould ne ver be us ed for precis e values s uch as currency.
boolean:
There are only two poss ible values : true and fals e.
This data type is used for sim ple flags that track true/fals e conditions .
char:
Reference variables are created us ing defined cons tructors of the class es . They are us ed to access objects .
These variables are declared to be of a s pecific type that cannot be changed. For e xample,
Em ployee, Pupp y etc.
Class objects , and various type o f arra y variables com e under reference data type .
A reference variable can be us ed to refer to an y object of the declared type or an y com patible type .
Java Literals:
A literal is a s ource code repres entation of a fi xed value. The y are repres ented directly in the code withou t an y
computation.
Literals can be ass igned to any primitive t ype variable. For e xam ple:
byte a = 68;
char a = 'A'
byte, int, long , and s hort can be e xpress ed in decimal(bas e 10),hexadecim al(bas e 16) or octal(bas e 8) num ber
s ys tems as well.
Prefix 0 is us ed to indicates octal and prefix 0 x indicates hexadecim al when using thes e number s ys tems
for literals . For exam ple:
int decimal = 100;
int octal = 0144;
int hexa = 0x64;
String literals in Java are s pecified like they are in m os t other languages by enclosing a s equence of characters
between a pair of double quotes . Exam ples of s tring literals are:
"Hello World"
"two\nlines"
"\"This is in quotes\""
String and char types of literals can contain an y Unicode characters . For e xam ple:
char a = '\u0001';
String a = "\u0001";
Java language supports few s pecial es cape sequences for String and char literals as well. They are :
Notation
Character r epresented
\n
Newline (0 x0a)
\r
\f
\b
\s
Space (0 x20)
\t
tab
\"
Double quote
\'
Single quote
\\
backslas h
\ddd
\uxxxx
What is Next ?
This chapter explained you various data types , Ne xt topic e xplains different variable types and their us age. This
will give you a good unders tanding about how the y can be us ed in the java class es , interfaces etc.
CHAPTER
n Java, all variables m us t be declared before the y can be used. The basic form of a variable declaration is
s hown here:
type identifier [ = value][, identifier [= value] ...] ;
The type is one of Java's datatypes . The identifier is the nam e of the variable. To declare m ore than one variable
of the s pecified type , us e a comm a-s eparated lis t.
Here are several exam ples of vari able declarations of various types . Note that s om e include an initialization.
int a, b, c;
// declares three ints, a, b, and c.
int d = 3, e, f = 5; // declares three more ints, initializing
// d and f.
byte z = 22;
// initializes z.
double pi = 3.14159; // declares an approximation of pi.
char x = 'x';
// the variable x has the value 'x'.
This chapter will explain various variable types available in Ja va Language. There are three kinds of variables in
Java:
Local variables
Local variables :
Local variables are created when the method, cons tructor or block is entered and the variable will be
des troyed once it e xits the m ethod, cons tructor or block..
Local variables are vis ible only within the declared m ethod, cons tructor or block.
There is no default value for l ocal variables s o local variables should be declared and an initial valu e s hould
be assigned before the firs t us e.
Example:
Here age is a local variable. This is defined ins ide pupAge() m ethod and its s cope is lim ited to this m ethod only.
public class Test{
public void pupAge(){
int age = 0;
age = age + 7;
System.out.println("Puppy age is : " + age);
}
Example:
Following exam ple uses age without initiali zing it, so it would gi ve an error at the tim e of com pilation.
public class Test{
public void pupAge(){
int age;
age = age + 7;
System.out.println("Puppy age is : " + age);
}
public static void main(String args[]){
Test test = new Test();
test.pupAge();
}
}
This would produce following error while com piling it:
Test.java:4:variable number might not have been initialized
age = age + 7;
^
1 error
Instance variables :
Ins tance variables are declared in a class , but outs ide a method, cons tructor or any block.
When a space is allocated for an object in the heap a s lot for each ins tance variable value is created.
Ins tance variables are created when an object is created with the us e of the k ey word 'new' and des troyed
when the object is des troyed.
Ins tance variables hold values that mus t be referenced by m ore than one m ethod, cons tructor or block, or
essential parts of an object.s s tate that m us t be pres ent through out the class .
The ins tance variables are visible for all m ethods , cons tructors and block in the class . Norm ally it is
recomm ended to m ake these variables private (access level).Howe ver vis ibility for s ubclasses can be given
for thes e variables with the us e of access m odifiers .
Ins tance variables have default values . For numbers the default value is 0, for Booleans it is fals e and for
object references it is null. Values can be assigned during the declaration or within the cons tructor.
Ins tance variables can be access ed directly by calling the variable nam e ins ide the class . However within
s tatic m ethods and different class ( when ins tance variables are given ac cess ibility) the s hould be
called us ing the fully qualified nam e .Ob jectReference.Variab leName.
Example:
import java.io.*;
public class Employee{
// this instance variable is visible for any child class.
public String name;
// salary variable is visible in Employee class only.
private double salary;
// The name variable is assigned in the constructor.
public Employee (String empName){
name = empName;
}
// The salary variable is assigned a value.
public void setSalary(double empSal){
salary = empSal;
}
// This method prints the employee details.
public void printEmp(){
System.out.println("name : " + name );
System.out.println("salary :" + salary);
}
public static void main(String args[]){
Employee empOne = new Employee("Ransika");
empOne.setSalary(1000);
empOne.printEmp();
}
}
This would produce following result:
name
: Ransika
salary :1000.0
Class/static variables :
Class variables als o known as s tatic variables are declared with the static keyword in a clas s , but outs ide a
m ethod, cons tructor or a block.
There would only be one cop y of each class variable per class , regardless of how m any objects are created
from it.
Static variables are rarel y us ed other than being declared as cons tants . Cons tants are variables that
are declared as public/private, final and s tatic. Cons tant variables never change from their initial value .
Static variables are s tored in s tatic memory. It is rare to us e s tatic variables other than declared final and
us ed as either public or private cons tants .
Static variables are created when the program s tarts and des troyed when the program s tops .
Vis ibility is s imilar to ins tance variables . However, m os t s tatic variables are declared public s ince they m us t
be available for users of the clas s .
Default values are sam e as ins tance variables . For num bers the default value is 0, for Booleans it is fals e and
for object references it is null. Values can be ass igned during the declara tion or within the
cons tructor. Additionall y values can be ass igned in special s tatic initializer blocks .
Static variables can be accessed by calling with the class name . ClassNam e.Variab leName.
When declaring class variables as public s tatic final, then variables names (cons tants ) are all in upper cas e.
If the s tatic variables are not public and fi nal the nam ing s yntax is the same as ins tance and local variables .
Example:
import java.io.*;
public class Employee{
// salary variable is a private static variable
private static double salary;
// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";
public static void main(String args[]){
salary = 1000;
System.out.println(DEPARTMENT+"average salary:"+salary);
}
}
This would produce following result:
Development average salary:1000
Note : If the variables are access
Em ployee.DEPARTMEN T
from
What is Next ?
You alread y ha ve us ed access m odifiers ( public & private ) in this chapter. The next chapter will e xplain you
Acces s Modifiers and Non Access Modifiers in detail.
CHAPTER
odifiers are keywords that you add to thos e definitions to change their meanings . The Java language
Example:
Variables and m ethods can be declared without an y m odifiers , as in the following exam ples :
String version = "1.5.1";
boolean processOrder() {
return true;
}
Example:
The following class uses private access control:
public class Logger { private
String format; public
String getFormat() {
return this.format;
}
public void setFormat(String format) {
this.format = format;
}
}
Here, the form at variable o f the Logg er class is private, s o there's no way for other classes to retrieve or s et its
value directl y.
So to m ake this variable available to the outs ide world, we defined two public m ethods : getForm at(), which returns
the value o f form at, and setFormat(String), which s ets its value.
Example:
The following function us es public access control:
public static void main(String[] arguments) {
// ...
}
The m ain() method of an application has to be public. Otherwis e, it could not be called b y a Ja va interpreter (s uch
as java) to run the class .
Example:
The following parent class us es protected access control, to allow its child class override openSpeak er() m ethod:
class AudioPlayer {
protected boolean openSpeaker(Speaker sp) {
// implementation details
}
}
class StreamingAudioPlayer {
boolean openSpeaker(Speaker sp) {
// implementation details
}
}
Here if we define openSpeak er() method as private then it would not be accessible from any other class other
than AudioPlayer. If we define it as public then it would becom e access ible to all the outs ide world. But
our intens ion is to expose this m ethod to its s ubclass only, thats why we us ed protected m odifier.
Methods declared protected in a s uperclass m us t either be protected or public in s ubclasses ; they canno t be
private.
Methods declared without access control (no m odifier was used) can be declared m ore private in s ubclasses .
Methods declared private are no t inherited at all, so there is no rule for them .
To us e a m odifier, you include its ke yword in the definition of a class , m ethod, or variable . The m odifier precedes
the res t of the s tatem ent, as in the following examples (Italic ones ):
public class className {
// ...
}
private boolean myFlag;
static final double weeks = 9.5;
protected static final int BOXWIDTH = 42;
public static void main(String[] arguments) {
// body of method
}
The final modifier for finalizing the im plementations of classes , m ethods , and variables .
The ab stract m odifier for creating abs tract class es and methods .
The synchronized and volatile m odifiers , which are us ed for threads .
What is Next ?
In the next s ection I will be dis cuss ing about Bas ic Operators used in the Java Language. The chapter will gi ve
you an o ver view o f how these operators can be us ed during application developm ent.
CHAPTER
ava pro vides a rich s et of operators to m anipulate variables . We can di vide all the Ja va operators into the
following groups :
Relational Operators
Bitwis e Operators
Logical Operators
Mis c Operators
Description
Example
A + B will gi ve 30
A - B will gi ve -10
A * B will gi ve 200
B / A will gi ve 2
Modulus - Divides left hand operand b y right hand operand and returns
rem ainder
B % A will gi ve 0
++
B++ gives 21
--
B-- gives 19
Exampl e
The following sim ple exam ple program dem ons trates the arithm etic operators . Copy and pas te following
Java program in Tes t.java file and com pile and run this program :
public class Test {
public static void main(String args[]) {
int a = 10;
int b = 20;
int c = 25;
int d = 25;
System.out.println("a + b = " + (a + b) );
System.out.println("a - b = " + (a - b) );
System.out.println("a * b = " + (a * b) );
System.out.println("b / a = " + (b / a) );
System.out.println("b % a = " + (b % a) );
System.out.println("c % a = " + (c % a) );
System.out.println("a++
= " + (a++) );
System.out.println("b-= " + (a--) );
// Check the difference in d++ and ++d
System.out.println("d++
= " + (d++) );
System.out.println("++d
= " + (++d) );
}
}
This would produce following res ult:
a +
a a *
b /
b %
c %
a++
b-d++
++d
b
b
b
a
a
a
= 30
= -10
= 200
= 2
= 0
= 5
= 10
= 11
= 25
= 27
Example
==
Checks if the value o f two operands are equal or not, if yes then
condition becom es true.
(A == B) is not true .
!=
Checks if the value o f two operands are equal or not, if values are not
equal then condition becom es true.
(A != B) is true.
>
Checks if the value o f left operand is greater than the value of right
operand, if yes then condition becomes true.
<
Checks if the value o f left operand is less than the value of right
operand, if yes then condition becomes true.
>=
Checks if the value o f left operand is greater than or equal to the value
of right operand , i f yes then condition becomes true.
(A < B) is true.
(A >= B) is not true .
<=
Checks if the value o f left operand is less than or equal to the value of
right operand, if yes then condition becom es true.
(A <= B) is true.
Example
The following s im ple exam ple program demons trates the relational operators . Copy and pas te following
Java program in Tes t.java file and compile and run this program . :
public class Test {
public static void main(String args[]) {
int a = 10;
int b = 20;
System.out.println("a == b = " + (a == b) );
System.out.println("a != b = " + (a != b) );
System.out.println("a > b = " + (a > b) );
System.out.println("a < b = " + (a < b) );
System.out.println("b >= a = " + (b >= a) );
System.out.println("b <= a = " + (b <= a) );
}
}
This would produce following result:
a
a
a
a
b
b
== b = false
!= b = true
> b = false
< b = true
>= a = true
<= a = false
Operator Description
Example
&
<<
>>
>>>
Example
The following s im ple example program dem ons trates the bitwis e operators . Copy and pas te following
Java program in Tes t.java file and com pile and run this program :
public class Test {
public
int
int
int
c = a & b;
/* 12 = 0000 1100 */
System.out.println("a & b = " + c );
c = a | b;
/* 61 = 0011 1101 */
System.out.println("a | b = " + c );
c = a ^ b;
/* 49 = 0011 0001 */
System.out.println("a ^ b = " + c );
c = ~a;
/*-61 = 1100 0011 */
System.out.println("~a = " + c );
c = a << 2;
/* 240 = 1111 0000 */
System.out.println("a << 2 = " + c );
c = a >> 2;
/* 215 = 1111 */
System.out.println("a >> 2 = " + c );
c = a >>> 2;
/* 215 = 0000 1111 */
System.out.println("a >>> 2 = " + c );
}
}
Example
&&
Called Logical AND operator. If both the operands are non zero then
then condition becom es true.
(A && B) is fals e.
||
(A || B) is true.
!( A && B) is true.
Called Logical NOT Operator. Us e to re vers es the logical s tate of its
operand. If a condition is true then Logical NOT operator will m ake fals e.
Example
The following s im ple exam ple program dem ons trates the logical operators . Copy and pas te following
Java program in Tes t.java file and com pile and run this program :
public class Test {
public static void main(String args[]) {
boolean a = true;
boolean b = false;
System.out.println("a && b = " + (a&&b));
System.out.println("a || b = " + (a||b) );
System.out.println("!(a && b) = " + !(a && b));
}
}
This would produce following result:
a && b = false
a || b = true
!(a && b) = true
Example
+=
C += A is equivalen t to C = C + A
-=
C -= A is equivalen t to C = C - A
*=
/=
%=
C %= A is equivalen t to C = C % A
<<=
>>=
&=
C &= 2 is s am e as C = C & 2
^=
C ^= 2 is s am e as C = C ^ 2
|=
C |= 2 is sam e as C = C | 2
Example:
The following s im ple exam ple program dem ons trates the assignment operators operators . Copy and
pas te following Java program in Tes t.java file and com pile and run this program :
public class Test {
public
int
int
int
c = a + b;
System.out.println("c = a + b = " + c );
c += a ;
System.out.println("c += a
= " + c );
c -= a ;
System.out.println("c -= a = " + c );
c *= a ;
System.out.println("c *= a = " + c );
a = 10;
c = 15;
c /= a ;
System.out.println("c /= a = " + c );
a = 10;
c = 15;
c %= a ;
System.out.println("c %= a
= " + c );
c <<= 2 ;
System.out.println("c <<= 2 = " + c );
c >>= 2 ;
System.out.println("c >>= 2 = " + c );
c >>= 2 ;
System.out.println("c >>= a = " + c );
c &= a ;
System.out.println("c &= 2
= " + c );
c ^= a ;
System.out.println("c ^= a
= " + c );
c |= a ;
System.out.println("c |= a
= " + c );
}
}
This would produce following result:
c
c
c
c
c
c
c
c
c
c
c
c
= a + b = 30
+= a = 40
-= a = 30
*= a = 300
/= a = 1
%= a = 5
<<= 2 = 20
>>= 2 = 5
>>= 2 = 1
&= a = 0
^= a
= 10
|= a
= 10
Misc Operators
There are few other operators s upported by Ja va Language.
Conditional Operator ( ? : ):
Conditional operator is als o known as the ternary operator. This operator cons is ts of three operands and is us ed
to evaluate boolean e xpress ions . The goal of the operator is to decide which value s hould be assigned to the
variable. The operator is written as :
variable x = (expression) ? value if true : value if false
Following is the example:
public class Test {
public static void main(String args[]){
int a , b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " +
b );
instanceOf Operator:
This operator is us ed only for object reference variables . The operator checks whether the object is of a particular
type(class type or interface type). ins tanceOf operator is wriiten as :
( Object reference variable ) instanceOf
(class/interface type)
If the object referred b y the variable on the left s ide of the operator passes the IS -A check for the class /interface
type on the righ t s ide then the result will be true. Following is the exam ple:
String name = = 'James';
boolean result = name instanceOf String;
// This will return true since name is type of String
This operator will s till return true if the object being compared is the assignm ent com patible with the type on the
right. Following is one more exam ple:
class Vehicle {}
public class Car extends Vehicle {
public static void main(String args[]){
Vehicle a = new Car();
boolean result = a instanceof Car;
System.out.println( result);
}
}
This would produce following result:
true
Categor y
Operator
Associativity
Pos tfix
() [] . (dot operator)
Left to right
Unary
++ - - ! ~
Right to left
Multiplicati ve
* /%
Left to right
Additi ve
+-
Left to right
Shift
Left to right
Relational
Left to right
Equality
== !=
Left to right
Bitwis e AND
&
Left to right
Bitwis e XOR
Left to right
Bitwis e OR
Left to right
Logical AND
&&
Left to right
Logical OR
||
Left to right
Conditional
?:
Right to left
As s ignm ent
Right to left
Comm a
Left to right
What is Next ?
Next chapter would e xplain about loop control in Ja va programm ing. The chapter will des cribe various types of
loops and how thes e loops can be used in Java program developm ent and for what purpos es they are
being used.
CHAPTER
here may be a s itution when we need to execute a block of code s everal num ber of tim es , and is often
referred to as a loop.
Java has very fle xible three looping m echanisms . You can us e one of the following three loops :
while Loop
do...while Loop
for Loop
As of ja va 5 the enhanced for loop w as introduced. This is mainly used for Arrays .
Syntax:
The s yntax o f a while loop is :
while(Boolean_expression)
{
//Statements
}
When executing , i f the b oolean_expression res ult is true then the actions ins ide the loop will be executed. This
will continue as long as the express ion res ult is true.
Here key poin t o f the while loop is that the loop m ight not e ver run. When the e xpress ion is tes ted and the result
is fals e, the loop body will be s kipped and the firs t s tatem ent after the while loop will be executed .
Example:
public class Test {
public static void main(String args[]) {
int x = 10;
while( x < 20 ) {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}
This would produce following result:
value
value
value
value
value
value
value
value
value
value
of
of
of
of
of
of
of
of
of
of
x
x
x
x
x
x
x
x
x
x
: 10
: 11
: 12
: 13
: 14
: 15
: 16
: 17
: 18
: 19
Syntax:
The s yntax o f a do...while loop is :
do
{
//Statements
}while(Boolean_expression);
Notice that the Boolean e xpression appears at the end of the loop, s o the s tatem ents in the loop execute once
before the Boolean is tes ted.
If the Boolean e xpress ion is true, the flow of control jum ps back up to do, and the s tatem ents in the loop execute
again. This process repeats until the Boolean express ion is fals e.
Example:
public class Test {
public static void main(String args[]){
int x = 10;
do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
}
}
This would produce following result:
value
value
value
value
of
of
of
of
x
x
x
x
:
:
:
:
10
11
12
13
value
value
value
value
value
value
of
of
of
of
of
of
x
x
x
x
x
x
: 14
: 15
: 16
: 17
: 18
: 19
Syntax:
The s yntax o f a for loop is :
for(initialization; Boolean_expression; update)
{
//Statements
}
Here is the flow of control in a for loop:
The initialization s tep is executed firs t, and onl y once. This s tep allows you to declare and initiali ze an y loop
control variables . You are no t required to put a s tatement here, as long as a sem icolon appears .
Next, the Boolean e xpress ion is evaluated. If it is true, the body of the loop is execu ted. If it is false, the body
of the loop does not e xecute and flow of control jumps to the next s tatem ent pas t the for loop.
After the bod y o f the for loop e xecutes , the flow of control jum ps back up to the update s tatem ent.
This s tatem ent allows you to update an y loop control variables . This s tatem ent can be left blank, as long
as a sem icolon appears after the Boolean express ion.
The Boolean expres sion is now evaluated again. If it is true, the loop executes and the process repeats its elf
(body o f loop, then update s tep,then Boolean e xpress ion). After the Boolean e xpress ion is fals e, the for loop
term inates .
Example:
public class Test {
public static void main(String args[]) {
for(int x = 10; x < 20; x = x+1) {
System.out.print("value of x : " + x );
System.out.print("\n");
}
}
}
This would produce following result:
value
value
value
value
of
of
of
of
x
x
x
x
:
:
:
:
10
11
12
13
value
value
value
value
value
value
of
of
of
of
of
of
x
x
x
x
x
x
: 14
: 15
: 16
: 17
: 18
: 19
Syntax:
The s yntax o f enhanced for loop is :
for(declaration : expression)
{
//Statements
}
Declaration . The newl y declared block variable , which is of a type compatible with the elements of the array
you are access ing. The variable will be a vailable within the for block and its value would be the s ame as the
current arra y element.
Expression . This evaluate to the array you need to loop through. The express ion can be an array variable
or m ethod call that returns an array.
Example:
public class Test {
public static void main(String args[]){
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ){
System.out.print( x );
System.out.print(",");
}
System.out.print("\n");
String [] names ={"James", "Larry", "Tom", "Lacy"};
for( String name : names ) {
System.out.print( name );
System.out.print(",");
}
}
}
This would produce following result:
10,20,30,40,50,
James,Larry,Tom,Lacy,
The break keyword will s top the execution of the innerm os t loop and s tart executing the ne xt line o f code after the
block.
Syntax:
The s yntax o f a break is a s ingle s tatement ins ide any loop:
break;
Example:
public class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 ) {
break;
}
System.out.print( x );
System.out.print("\n");
}
}
}
This would produce following result:
10
20
In a for loop, the continue ke yword causes flow of control to imm ediately jump to the update s tatem ent.
In a while loop or do/while loop , fl ow of control imm ediately jum ps to the Boolean express ion.
Syntax:
The s yntax o f a continue is a s ingle s tatem ent inside any loop:
continue;
Example:
public class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 ) {
continue;
}
System.out.print( x );
System.out.print("\n");
}
}
}
This would produce following result:
10
20
40
50
What is Next ?
In the following chapter we will be learning about decision m aking s tatem ents in Java programm ing.
CHAPTER
10
Java Decision Making
here are two types of decis ion m aking s tatements in Java. The y are:
if s tatements
The if Statement:
An i f s tatem ent cons is ts of a Boolean e xpression followed by one or m ore s tatem ents .
Syntax:
The s yntax o f an i f s tatement is :
if(Boolean_expression)
{
//Statements will execute if the Boolean expression is true
}
If the boolean e xpress ion evaluates to true then the block of code inside the if s tatem ent will be e xecuted. If not
the firs t s et of code after the end o f the if s tatem ent(after the clos ing curly brace) will be executed .
Example:
public class Test {
public static void main(String args[]){
int x = 10;
if( x < 20 ){
System.out.print("This is if statement");
}
}
}
This would produce following result:
This is if statement
Syntax:
The s yntax o f a if...els e is :
if(Boolean_expression){
//Executes when the Boolean expression is true
}else{
//Executes when the Boolean expression is false
}
Example:
public class Test {
public static void main(String args[]){
int x = 30;
if( x < 20 ){
System.out.print("This is if statement");
}else{
System.out.print("This is else statement");
}
}
}
This would produce following result:
This is else statement
An if can ha ve zero or one els e's and it m us t com e after any els e if's .
An if can ha ve zero to m any else if's and they m us t com e before the els e.
Once an els e if succeeds , none of he rem aining els e if's or els e's will be tes ted.
Syntax:
The s yntax o f a if...els e is :
if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
}else if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}else if(Boolean_expression 3){
//Executes when the Boolean expression 3 is true
}else {
Example:
public class Test {
public static void main(String args[]){
int x = 30;
if( x == 10 ){
System.out.print("Value of X is 10");
}else if( x == 20 ){
System.out.print("Value of X is 20");
}else if( x == 30 ){
System.out.print("Value of X is 30");
}else{
System.out.print("This is else statement");
}
}
}
This would produce following result:
Value of X is 30
Syntax:
The s yntax for a nes ted if...els e is as follows :
if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}
}
You can nes t else if...else in the s im ilar way as we have nes ted if s tatem ent.
Example:
public class Test {
public static void main(String args[]){
int x = 30;
int y = 10;
if( x == 30 ){
if( y == 10 ){
System.out.print("X = 30 and Y = 10");
}
}
}
Syntax:
The s yntax o f enhanced for loop is :
switch(expression){
case value :
//Statements
break; //optional
case value :
//Statements
break; //optional
//You can have any number of case statements.
default : //Optional
//Statements
}
The following rules apply to a s witch s tatem ent:
The variable us ed in a switch s tatem ent can only be a b yte, s hort, int, or char.
You can ha ve an y num ber of cas e s tatem ents within a s witch. Each cas e is followed by the value to
be compared to and a colon.
The value for a cas e mus t be the s am e data type as the variable in the switch, and it m us t be a cons tant or a
literal.
When the variable being s witched on is equal to a cas e, the s tatem ents following that case will exec ute until
a b reak s tatement is reached.
When a b reak s tatem ent is reached, the switch term inates , and the flow of control jum ps to the ne xt
line following the switch s tatem ent.
Not e very cas e needs to contain a break. If no break appears , the flow o f control will fall throughto
s ubs equent cas es until a break is reached.
A switch s tatem ent can ha ve an optional default case, which mus t appear a t the end o f the switch.
The default case can be used for performing a tas k when none of the cas es is true. No break is needed
in the default cas e.
Example:
public class Test {
public static void main(String args[]){
char grade = args[0].charAt(0);
switch(grade)
{
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
case 'C' :
System.out.println("Well done");
break;
case 'D' :
System.out.println("You passed");
case 'F' :
System.out.println("Better try again");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}
Com pile and run above program us ing various com mand line argum ents . This would produce following res ult:
$ java Test a
Invalid grade
Your grade is a a
$ java Test A
Excellent!
Your grade is a A
$ java Test C
Well done
Your grade is a C
$
What is Next?
Next chapter dis cuses about the Num ber class (in the java.lang package) and its subclasses in Java Language.
We will be looking into som e of the s ituations where you would us e ins tantiations of thes e class es rather than the
primitive data types , as well as class es s uch as formatting, m athematical functions that you need to know abo ut
when working with Num bers .
CHAPTER
11
Java Numbers
ormally, when we work with Num bers , we us e primitive data types s uch as byte, int, long , double etc.
Example:
int i = 5000;
float gpa = 13.65;
byte mask = 0xaf;
However in de velopment we com e across s ituations were we need to us e objects ins tead of prim itive data types .
In-order to achieve this Java pro vides wrapper class es for each prim itive data type.
All the wrapper class es ( Integer, Long, Byte, Double, Float, Short) are subclass es of the abs tract class Num ber.
This wrapping is taken care of by the compiler The process is called boxing. So when a prim itive is us ed when an
object is required the compiler boxes the prim itive type in its wrapper class . Sim ilarly the com piler unboxes the
object to a prim itive as well. The Number is part of the ja va.lang package.
Here is an exam ple of boxing and unb o xing:
public class Test{
public static void main(String args[]){
Integer x = 5; // boxes int to an Integer object
x = x + 10;
// unboxes the Integer to a int
System.out.println(x);
}
}
Number Methods:
Here is the lis t of the ins tance m ethods that all the subclass es of the Num ber class im plem ent:
What is Next ?
In the next s ection we will be going through the Character class in Java. You will be learning how to us e object
Characters and prim itive data type char in Ja va.
CHAPTER
12
Java Characters
ormally, when we work with characters , we use prim itive data types char.
Example:
char ch = 'a';
// Unicode for uppercase Greek omega character
char uniChar = '\u039A';
// an array of chars
char[] charArray ={ 'a', 'b', 'c', 'd', 'e' };
However in de velopment we com e across situations were we need to us e objects ins tead of prim itive data types .
In-order to achieve this Java pro vides wrapper class e Character for prim itive data type char.
The Character class offers a num ber of us eful class (i.e., s tatic) m ethods for m anipulating characters . You can
create a Character object with the Ch aracter cons tructor:
Character ch = new Character('a');
The Java com piler will als o create a Character object for you under some circums tances . For exam ple, if you
pass a primitive char into a m ethod that expects an object, the com piler autom atically con verts the char to
a Character for you . This feature is called autoboxing or unbo xing, if the con vers ion goes the other way.
Example:
// Here following primitive char 'a'
// is boxed into the Character object ch
Character ch = 'a';
// Here primitive 'x' is boxed for method test,
// return is unboxed to char 'c'
char c = test('x');
Escape Sequences:
A character preceded b y a backs lash (\) is an es cape s equence and has s pecial m eaning to the com piler.
The newline character (\n) has been us ed frequently in this tutorial in Sys tem .out.println() s tatem ents to advance
to the next line after the s tring is printed.
Following table shows the Java es cape sequences :
Escape Sequence
Des cription
\t
\b
\n
\r
\f
\'
\"
\\
When an es cape sequence is encountered in a print s tatement, the compiler interprets it accordingly.
Example:
If you wan t to pu t quotes within quotes you m us t us e the es cape s equence, \", on the interior quotes :
public class Test {
public static void main(String args[]) {
System.out.println("She said \"Hello!\" to me.");
}
}
This would produce following result:
She said "Hello!" to me.
Character Methods:
Here is the lis t of the im portant ins tance m ethods that all the s ubclass es of the Character class im plem ent:
For a com plete lis t of m ethods , please refer to the java.lang.Character API s pecification.
What is Next?
In the next s ection we will be going through the String class in Java. You will be learning how to declare and use
Strings efficiently as well as s om e of the im portant m ethods in the String class .
CHAPTER
13
Java Strings
Creating Strings:
The m os t direct wa y to create a s tring is to write:
String greeting = "Hello world!";
Whenever i t encounters a s tring literal in your code, the compiler creates a String object with its valuein this cas e,
"Hello world!'.
As with any other object, you can create String objects by us ing the new keyword and a cons tructor. The String
class has eleven cons tructors that allow you to provide the initial value of the s tring us ing different s ources , such
as an array of characters :
public class StringDemo{
public static void main(String args[]){
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'};
String helloString = new String(helloArray);
System.out.println( helloString );
}
}
This would produce following result:
hello
Note : The String class is immutable, s o that once it is created a String object cannot be changed. If there is a
necess ity to m ake alot of m odifications to Strings of characters then you should us e String Buffe r &
String Builder Classes .
String Length:
Methods us ed to obtain inform ation about an object are known as access or m ethods . One accessor m ethod that
you can use with s trings is the length() m ethod, which returns the number of characters contained in the s tring
object.
After the following two lines of code ha ve been e xecuted, len equals 17:
public class StringDemo {
public static void main(String args[]) {
String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
System.out.println( "String Length is : " + len );
}
}
This would produce following result:
String Length is : 17
Concatenating Strings:
The String class includes a method for concatenating two s trings :
string1.concat(string2);
This returns a new s tring that is s tring1 with s tring2 added to it at the end. You can als o us e the concat() m ethod
with s tring literals , as in:
"My name is ".concat("Zara");
Strings are more comm only concatenated with the + operator, as in:
"Hello," + " world" + "!"
which results in:
"Hello, world!"
Let us look at the followinge e xam ple:
public class StringDemo {
public static void main(String args[]) { String
string1 = "saw I was ";
System.out.println("Dot " + string1 + "Tod");
}
}
This would produce following result:
Dot saw I was Tod
String Methods:
Here is the lis t m ethods s upported by String class :
CHAPTER
Java Arrays
14
ava pro vides a data s tructure, the arra y, which s tores a fixed-s ize s equential collection of elem ents of the
s ame type. An arra y is us ed to s tore a collection of data, but it is often more useful to think of an array as
a collection of variables of the same type.
Ins tead of declaring individual variables , s uch as number0, num ber1, ..., and num ber99, you declare one arra y
variable such as numbers and use num bers [0], num bers [1], and ..., num bers [99] to represent individual variables .
This tutorial introduces how to declare array variables , create arra ys , and process arrays us ing indexed varia bles .
// preferred way.
or
dataType arrayRefVar[];
//
Note : The s tyle dataT ype[] arra yRefVar is preferred. The s tyle dataT ype arra yRefVar[] com es from the C/C++
language and was adopted in Java to accomm odate C/C++ programm ers .
Example:
The following code snippets are examples of this s yntax:
double[] myList;
// preferred way.
or
double myList[];
//
Creating Arrays:
You can create an arra y b y us ing the new operator with the following s ynta x:
arrayRefVar = new dataType[arraySize];
The above s tatem ent does two things :
It as s igns the reference of the newl y created arra y to the variable arra yRefVar.
Declaring an array variable , creating an arra y, and ass igning the reference of the arra y to the variable can be
combined in one s tatement, as s hown below:
dataType[] arrayRefVar = new dataType[arraySize];
Alternati vel y you can create arra ys as follows :
dataType[] arrayRefVar = {value0, value1, ..., valuek};
The array elem ents are access ed through the index. Arra y indices are 0-based; tha t is , the y s tart from
0 to arrayRefVar.length-1 .
Example:
Following s tatement declares an array variable, m yLis t, creates an arra y o f 10 elem ents of double type ,
and ass igns its reference to m yLis t.:
double[] myList = new double[10];
Following picture represents array m yLis t. Here m yLis t holds ten double values and the indices are from 0 to 9.
Processing Arrays:
When processing array elem ents , we often use either for loop or foreach loop becaus e all of the elements in an
array are o f the s ame type and the s ize of the arra y is known.
Example:
Here is a complete exam ple of s howing how to create, initiali ze and process arrays :
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (int i = 0; i < myList.length; i++) {
Example:
The following code dis plays all the elem ents in the array m yLis t:
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (double element: myList) {
System.out.println(element);
}
}
}
This would produce following result:
1.9
2.9
3.4
3.5
CHAPTER
15
Java Date & Time
ava pro vides the Date class available in ja va.util package, this class encapsulates the current date and
tim e.
The Date class s upports two cons tructors . The firs t cons tructor initializes the object with the current date
and tim e.
Date( )
The following cons tructor accepts one argum ent that equals the number of m illis econds that have elaps ed s ince
m idnight, January 1 , 1970
Date(long millisec)
Once you ha ve a Date object a vailabl e, you can call an y of the following support m etho ds to play with dates :
SN Methods w ith Description
1
Object clone( )
Duplicates the invoking Date object.
long getTime( )
Returns the num ber of m illis econds that have elapsed s ince January 1, 1970 .
8
10
String t oString( )
Converts the invoking Date object into a s tring and returns the res ult.
Date Comparison:
There are following three ways to com pare two dates :
You can us e getTim e( ) to obtain the num ber of m illis econds that have elapsed s ince midnight, January 1 ,
1970, for both objects and then compare thes e two values .
You can us e the m ethods before( ), after( ), and equals ( ). Becaus e the 12th of the m onth com es before the
18th, for e xam ple, new Date (99, 2, 12).before(new Date (99, 2, 18)) returns true.
You can us e the com pareTo( ) m ethod, which is defined by the Comparable interface and implemented by
Date.
Description
Example
AD
2001
Month in year
July or 07
Day in m onth
10
12
22
Minute in hour
30
Second in minute
55
Millisecond
234
Day in week
Tues day
Day in year
360
Week in year
40
Week in m onth
A. M./P. M. m arker
PM
24
10
Tim e zone
'
Delimiter
"
Single quote
Description
Example
F
D
24-hour tim e
18:05:19
12-hour tim e
06:05:19 pm
18:05
2004
04
20
February
Feb
02
03
Monda y
Mon
069
18
18
2004-02-09
02/09/2004
06
Two-digit hour (withou t leading zeroes ), betw een 1 and
12
Two-digit m inutes (with leading zeroes )
05
19
047
047000000
PM
pm
-0800
Tim e zone
PST
1078884319
Q
Milliseconds since 1970-01-01 00:00:00 GMT
1078884319047
There are other useful class es related to Date and tim e. For m ore detail you can refer to Ja va
Standard docum entation.
GregorianCalendar Class:
GregorianCalendar is a concrete implementation of a Calendar class that im plements the norm al Gregorian
calendar with which you are fam iliar. I did not dis cuss Calender class in this tutorial, you can look s tandard Java
docum entation for this .
The getInstance( ) method of Calendar returns a GregorianCalendar initialized with the current date and tim e in
the default locale and tim e zone. GregorianCalendar defines two fields : AD and BC. Thes e represent the two eras
defined by the Gregorian calendar.
There are als o s everal cons tructors for GregorianCalendar objects :
Gregorian Calendar()
Cons tructs a default GregorianCalendar us ing the current time in the default tim e zone with the
default locale .
Gregorian Calendar(int year , int month, i nt date, int hour, int minute)
Cons tructs a GregorianCalendar with the given date and tim e s et for the default time zone with the
default locale .
Gregorian Calendar(int year , int month, int date, int hour, int minute, int second)
Cons tructs a GregorianCalendar with the given date and tim e s et for the default time zone with the
default locale .
Gregorian Calendar(Locale aLocale)
Cons tructs a GregorianCalendar based on the current tim e in the default tim e zone with the gi ven
locale.
Here is the lis t of few us eful support m ethods provided by GregorianCalendar class :
SN Medthos w ith Description
1
10
11
12
Date getTime()
Gets this Calendar's current tim e.
13
long getTimeInMillis()
Gets this Calendar's current tim e as a long.
14
TimeZone getTimeZone()
Gets the tim e zone.
15
16
int hashCode()
Override has hCode.
17
18
19
20
21
void set(int year , int mont h, int date , int hour, int minute)
Sets the values for the fields year, m onth, date, hour, and minute.
22
voi d set(int year , int month, int date, int hour, int minute, int second)
Sets the values for the fields year, m onth, date, hour, m inute, and second.
23
24
25
26
27
String t oString()
Return a s tring repres entation of this calendar.
Example:
import java.util.*;
public class GregorianCalendarDemo {
public static void main(String args[]) {
String months[] = {
"Jan", "Feb", "Mar", "Apr",
"May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec"};
int year;
// Create a Gregorian calendar initialized
// with the current date and time in the
// default locale and timezone.
GregorianCalendar gcalendar = new GregorianCalendar();
// Display current time and date information.
System.out.print("Date: ");
System.out.print(months[gcalendar.get(Calendar.MONTH)]);
System.out.print(" " + gcalendar.get(Calendar.DATE) + " ");
System.out.println(year = gcalendar.get(Calendar.YEAR));
System.out.print("Time: ");
System.out.print(gcalendar.get(Calendar.HOUR) + ":");
System.out.print(gcalendar.get(Calendar.MINUTE) + ":");
System.out.println(gcalendar.get(Calendar.SECOND));
// Test if the current year is a leap year
if(gcalendar.isLeapYear(year)) {
System.out.println("The current year is a leap year");
}
else {
System.out.println("The current year is not a leap year");
}
}
}
This would produce following result:
Date: Apr 22 2009
Time: 11:25:27
The current year is not a leap year
For a com plete lis t of cons tant a vail able in Calender class , you can refer to s tandard Java docum entation.
CHAPTER
16
Java Regular Expressions
ava
pro vides the ja va.util.rege x package for pattern matching with regular e xpress ions . Java regul ar
express ions are very s im ilar to the Perl programm ing language and very eas y to learn .
A regular e xpression is a special sequence of characters that helps you match or find other s trings or s ets
of s trings , us ing a s pecialized s yntax held in a pattern. The y can be us ed to search, edit, or m anipulate text
and data.
The java.util.rege x package primaril y cons is ts of the following three class es :
Pattern Class : A Pattern object is a compiled repres entation of a regular e xpress ion. The Pattern
class provides no public cons tructors . To create a pattern, you mus t firs t invoke one of its public s tatic
compile m ethods , which will then return a Pattern object. Thes e m ethods accept a regular express ion
as the firs t argum ent.
Matcher Class: A Matcher object is the engine that interprets the pattern and performs m atch operations
agains t an input s tring. Like the Pattern class , Matcher defines no public cons tructors . You obtain a Matcher
object b y in voking the m atcher m ethod on a Pattern object.
PatternSyntax Exception : A PatternS ynta xE xception object is an unchecked exce ption that indicates a
s yntax error in a regular e xpress ion pattern.
Capturing Groups:
Capturing groups are a way to treat m ultiple characters as a s ingle unit. They are created b y placing
the characters to be grouped inside a s et of parentheses . For exam ple, the regular express ion (dog) creates a
s ingle group containing the letters "d", "o", and "g".
Capturing groups are num bered by counting their opening parenthes es from left to right. In the e xpres sion
((A)(B(C))), for e xam ple, there are four s uch groups :
((A)(B(C)))
(A)
(B(C))
(C)
To find out how m any groups are pres ent in the e xpression, call the groupCount method on a m atcher object. The
groupCount m ethod returns an int s howing the num ber of capturing groups present in the m atcher's pattern.
There is als o a s pecial group, group 0, which alwa ys repres ents the entire expr ess ion. This group is not included
in the total reported by groupCount.
Example:
Following exam ple illus trate how to find a digit s tring from the given alphanum eric s tring:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexMatches
{
public static void main( String args[] ){
// String to be scanned to find the pattern.
String line = "This order was places for QT3000! OK?";
String pattern = "(.*)(\\d+)(.*)";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(line);
if (m.find( )) {
System.out.println("Found value: " + m.group(0) );
System.out.println("Found value: " + m.group(1) );
System.out.println("Found value: " + m.group(2) );
} else {
System.out.println("NO MATCH");
}
}
}
This would produce following result:
Found value: This order was places for QT3000! OK?
Found value: This order was places for QT300
Found value: 0
Matches any s ingle character e xcept newline. Using m option allows it to m atch
newline as well.
[...]
[^...]
\A
\z
\Z
re*
re+
re?
re{ n}
re{ n,}
re{ n, m }
a| b
Matches either a or b.
(re)
(?: re)
(?> re)
\w
\W
\s
\S
Matches nonwhitespace.
\d
\D
Matches nondigits .
\A
\Z
Matches end of s tring. If a new line e xis ts , it m atches jus t before newline.
\z
\G
\n
\b
Matches word boundaries when outs ide brackets . Matches backs pace (0x08) when
inside brackets .
\B
\Q
\E
Index Methods:
Index m ethods provide useful index val ues that s how precis ely where the m atch was found in the input s tring:
SN Methods w ith Description
2
3
Returns the offs et after the las t character of the s ubs equence captured by the given group during
the previous match operation.
Study Methods:
Study m ethods review the input s tring and return a boolean indicating whether or not the pattern is found:
SN Methods w ith Description
1
Replacement Methods:
Replacem ent m ethods are us eful methods for replacing text in an input s tring:
SN Methods w ith Description
1
Replaces the firs t s ubsequence of the input s equence that m atches the pattern with the given
replacem ent s tring.
public static String quote Replacement(String s)
Returns a literal replacem ent String for the s pecified String. This m ethod produces a String that
will work as a literal replacem ent s in the appendReplacem ent m ethod of the Matcher class .
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexMatches
{
private static final String REGEX = "\\bcat\\b";
private static final String INPUT =
"cat cat cat cattie cat";
public static void main( String args[] ){
Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(INPUT); // get a matcher object
int count = 0;
while(m.find()) {
count++;
System.out.println("Match number "+count);
System.out.println("start(): "+m.start());
System.out.println("end(): "+m.end());
}
}
}
This would produce following result:
Match number
start(): 0
end(): 3
Match number
start(): 4
end(): 7
Match number
start(): 8
end(): 11
Match number
start(): 19
end(): 22
1
2
3
4
You can see that this exam ple uses word boundaries to ensure that the letters "c" "a" "t" are not m erely
a s ubs tring in a longer word. It als o gives s ome us eful information about where in the input s tring the match
has occurred.
The s tart m ethod returns the s tart inde x of the s ubs equence capture d by the given group during the pre vious
m atch operation, and end returns the index of the las t character matched, plus one.
CHAPTER
17
Java Methods
Java m ethod is a collection of s tatem ents that are grouped together to perform an operation. When
you call the Sys tem .out.println m ethod, for e xam ple, the s ys tem actually executes s everal s tatem ents in order to
display a m essage on the cons ole.
Now you will learn how to create your own methods with or without return values , in voke a m ethod with or without
param eters , overload m ethods us ing the sam e names , and apply m ethod abs traction in the program des ign.
Creating a Method:
In general, a method has the following s yntax:
modifier returnValueType methodName(list of parameters) {
// Method body;
}
A m ethod definition cons is ts of a method header and a m ethod body. Here are all the parts of a m ethod:
Modifiers: The m odifier, which is optional, tells the com piler how to call the m ethod. This defines the access
type of the m ethod.
Return Type : A m ethod m ay return a value . The return ValueType is the data type of the value the m ethod
returns . Som e m ethods perform the des ired operations without returning a value . In th is cas e, the
returnValueType is the keyword void.
Method Name : This is the actual name of the m ethod. The m ethod nam e and the param eter lis t together
cons titute the m ethod s ignature.
Parameters: A param eter is like a placeholder. When a m ethod is invoked, you pass a value to the
param eter. This value is referred to as actual parameter or argument. The param eter lis t refers to the type,
order, and num ber of the param eters of a m ethod. Parameters are optional; that is , a m ethod may contain no
param eters .
Method Body: The m ethod body contains a collection of s tatem ents that define what the method does .
Note : In certain other languages , m ethods are referred to as procedures and functions . A m ethod 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 s ource code of the abo ve defined m ethod called max(). This m ethod takes two param eters num 1 and
num2 and returns the maxim um between the two:
/** Return the max between two numbers */
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
}
return result;
Calling a Method:
In creating a m ethod, you gi ve a definition of what the m ethod is to do. To us e a m ethod, you ha ve to call or
invoke it. There are two wa ys to call a m ethod; the choice is bas ed on whether the method returns a value or not.
When a program calls a m ethod, program control is trans ferred to the called m ethod. A called m ethod returns
control to the caller when its return s tatem ent is executed or when its m ethod-ending clos ing brace is reached.
If the m ethod returns a value, a call to the m ethod is us ually treated as a value. For e xam ple:
int larger = max(30, 40);
If the m ethod returns void, a ca ll to the m ethod mus t be a s tatem ent. For exam ple, the m ethod println returns
void. The following call is a s tatement:
System.out.println("Welcome to Java!");
Example:
Following is the example to demons trate how to define a m ethod and how to call it:
public class TestMax {
/** Main method */
public static void main(String[] args) {
int i = 5;
int j = 2;
int k = max(i, j);
System.out.println("The maximum between " + i +
" and " + j + " is " + k);
}
/** Return the max between two numbers */
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
}
This would produce following res ult:
The maximum between 5 and 2 is 5
This program contains the m ain m ethod and the m ax m ethod. The m ain m ethod is jus t like any other m ethod
except tha t i t is invoked b y the J VM.
The main m ethod's header is always the s ame, like the one in this exam ple, with the m odifiers public and s tatic,
return value type void, m ethod nam e m ain, and a param eter of the String[] typ e. String[] indicates that
the param eter is an array of String .
Example:
public class TestVoidMethod {
public static void main(String[] args) {
printGrade(78.5);
}
public static void printGrade(double score) {
if (score >= 90.0) {
System.out.println('A');
}
else if (score >= 80.0) {
System.out.println('B');
}
else if (score >= 70.0) {
System.out.println('C');
}
else if (score >= 60.0) {
System.out.println('D');
}
else {
System.out.println('F');
}
}
}
This would produce following result:
C
Here the printGrade m ethod is a void method. It does not return any value. A call to a void method m us t be a
s tatem ent. So, it is invoked as a s tatem ent in line 3 in the m ain method. This s tatem ent is like any Ja va s tatem ent
term inated with a s emicolon.
Example:
Following is a program that demons trates the effect of pass ing by value. The program creates a m ethod for
s wapping two variables . The s wap method is invoked by passing two argum ents . Interes tingly, the values of the
argum ents are not changed after the m ethod is invoked.
public class TestPassByValue {
public static void main(String[] args) {
int num1 = 1;
int num2 = 2;
System.out.println("Before swap method, num1 is " +
num1 + " and num2 is " + num2);
// Invoke the swap method
swap(num1, num2);
System.out.println("After swap method, num1 is " +
num1 + " and num2 is " + num2);
}
/** Method to swap two variables */
public static void swap(int n1, int n2) {
System.out.println("\tInside the swap method");
System.out.println("\t\tBefore swapping n1 is " + n1
+ " n2 is " + n2);
// Swap n1 with n2
int temp = n1;
n1 = n2;
n2 = temp;
System.out.println("\t\tAfter swapping n1 is " + n1
+ " n2 is " + n2);
}
}
This would produce following result:
Before swap method, num1 is 1 and num2 is 2
Inside the swap method
Before swapping n1 is 1 n2 is 2
After swapping n1 is 2 n2 is 1
After swap method, num1 is 1 and num2 is 2
Overloading Methods:
The m ax m ethod that was used earlier works only with the int data type . But what if you need to find which of two
floating-point numbers has the m aximum value? The solution is to create another m ethod with the s am e name but
different param eters , as s hown in the following code:
public static double max(double num1, double num2) {
if (num1 > num2)
return num1;
else
return num2;
}
If you call m ax with int param eters , the m ax m ethod that expects int param eters will be invoked; if you call m ax
with double parameters , the max m ethod that expects double param eters will be invoked. This is referred
to as method overloading; that is , two m ethods have the s am e nam e but different parameter lis ts within one
class .
The Java com piler determines which method is used bas ed on the m ethod s ignature. Overloading m ethods can
m ake programs clearer and m ore readable. Methods that perform closely related tas ks s hould be given the sam e
name.
Overloaded methods m us t have differen t param eter lis ts . You canno t o verload m ethods bas ed on
different m odifiers or return types . Som etim es there are two or m ore poss ible m atches for an invocation of a
m ethod due to s im ilar m ethod signature, s o the compiler cannot determ ine the m os t specific m atch. This is
referred to as am biguous invocation.
You can declare a local variable with the s am e nam e m ultiple tim es in different non-nes ting blocks in a m ethod,
but you canno t declare a local variable twice in nes ted blocks .
Example:
The following program dis plays all of the comm and-line argum ents that it is called with:
public class CommandLine {
public static void main(String args[]){
for(int i=0; i<args.length; i++){
System.out.println("args[" + i + "]: " +
args[i]);
}
}
}
Try e xecuting this program , as s hown here:
java CommandLine this is a command line 200 -100
This would produce following result:
args[0]:
args[1]:
args[2]:
args[3]:
args[4]:
args[5]:
args[6]:
this
is
a
command
line
200
-100
The Constructors:
A cons tructor initializes an object when it is created. It has the s am e nam e as its class and is s yntactically s im ilar
to a m ethod. However, cons tructors have no e xplicit return type.
Typicall y, you will us e a cons tructor to give initial values to the ins tance variables defined b y the class , or
to perform any other s tartup procedures required to create a fully form ed object.
All class es have cons tructors , whether you define one or not, becaus e Ja va automatically pro vides a
default cons tructor that initiali zes all m ember variables to zero. Howe ver, once you define your own
cons tructor, the default cons tructor is no longer us ed.
Example:
Here is a s im ple exam ple that us es a cons tructor:
// A simple constructor.
class MyClass {
int x;
// Following is the constructor
MyClass() {
x = 10;
}
}
You would call cons tructor to initiali ze objects as follows :
public class ConsDemo {
public static void main(String args[]) {
MyClass t1 = new MyClass();
MyClass t2 = new MyClass();
System.out.println(t1.x + " " + t2.x);
}
}
Mos t often you will need a cons tructor that accepts one or more parameters . Param eters are added to
a cons tructor in the s ame way that the y are add ed to a method:jus t declare them inside the parentheses after
the cons tructor's nam e.
Example:
Here is a s im ple exam ple that uses a cons tructor:
// A simple constructor.
class MyClass {
int x;
// Following is the constructor
MyClass(int i ) {
x = i;
}
}
You would call cons tructor to initiali ze objects as follows :
public class ConsDemo {
Variable Arguments(var-args):
JDK 1.5 enables you to pas s a variable num ber of argum ents of the s ame type to a m ethod. The param eter in the
m ethod is declared as follows :
typeName... parameterName
In the method declaration, you specify the type followed b y an ellipsis (...) Only one variable -length param eter
m ay be specified in a method, and this param eter m us t be the las t param eter. An y regular param et ers
m us t precede it.
Example:
public class VarargsDemo {
public static void main(String args[]) {
// Call method with variable args
printMax(34, 3, 3, 2, 56.5);
printMax(new double[]{1, 2, 3});
}
public static void printMax( double... numbers) {
if (numbers.length == 0) {
System.out.println("No argument passed");
return;
}
double result = numbers[0];
for (int i = 1; i < numbers.length; i++)
if (numbers[i] > result)
result = numbers[i];
System.out.println("The max value is " + result);
}
}
This would produce following result:
The max value is 56.5
The max value is 3.0
To add a finalizer to a class , you s im ply define the finalize( ) m ethod. The Ja va runtime calls that
m ethod whenever it is about to recycle an object of that class .
Ins ide the finalize( ) m ethod you will specify thos e actions that mus t be perform ed before an object is des troyed.
The finalize( ) m ethod has this general form :
protected void finalize( )
{
// finalization code here
}
Here, the ke yword protected is a s pecifier that pre vents access to finalize( ) b y code defined outs ide its class .
This means that you canno t know when.or e ven if.finali ze( ) will be e xecuted . For e xam ple, i f yo ur program ends
before garbage collection occurs , finali ze( ) will not e xecute.
CHAPTER
18
Java Files & I/O
he Java io package contains nearly e ver y clas s you m ight ever need to perform input and outpu t (I/O) in
Java. All thes e s treams represent an input s ource and an output des tination. The s tream in the java.io package
s upports many data s uch as prim itives , Object, locali zed characters etc.
A s tream can be defined as a s equence of data. The InputStream is us ed to read data from a s ource and the
OutputStream is us ed for writing data to a des tination.
Java does provide s trong, fle xible s upport for I/O as it relates to files and networks but this tutoria l covers very
basic functionlity related to s treams and I/O. We would s ee m os t comm only us ed exam ple one by one:
char c;
// Create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter characters, 'q' to quit.");
// read characters
do {
c = (char) br.read();
System.out.println(c);
} while(c != 'q');
}
}
Here is a s ample run:
Enter characters, 'q' to quit.
123abcq
1
2
3
a
b
c
q
Example:
Here is a s hort exam ple that us es write( ) to output the character "A" followed b y a newline to the s creen:
import java.io.*;
// Demonstrate System.out.write().
public class WriteDemo {
public static void main(String args[]) {
int b;
b = 'A';
System.out.write(b);
System.out.write('\n');
}
}
This would produce sim ply 'A' ch aracter on the output s creen.
A
Note : You will no t often use write( ) to perform console output because print( ) and println( ) are subs tantially
easier to us e.
The two im portant s treams are FileInputStream and FileOutputStream which would be dis cuss ed in this tutorial:
FileInputStream:
This s tream is used for reading data from the files . Objects can be created us ing the keyword new and there are
s everal types of cons tructors available.
Following cons tructor takes a file nam e as a s tring to create an input s tream object to read the file:
InputStream f = new FileInputStream("C:/java/hello");
Following cons tructor takes a file object to create an input s tream object to read the file. Firs t we create a file
object us ing File() m ethod as follows :
File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);
Once you ha ve I nputStream object in hand then there is a lis t of helper m ethods which can be us ed to read to
s tream or to do other operations on the s tream .
SN Methods w ith Description
1
There are other im portant input s treams available, for more detail you can refer to the following links :
ByteArrayInputStream
The Byte Arra yInputStream class allows a buffer in the m emory to be us ed as an InputStream . The input source is
a byte arra y. There are following forms of cons tructors to create Byte Arra yInputStream objects
Takes a byte array as the param eter:
ByteArrayInputStream bArray = new ByteArrayInputStream(byte [] a);
Another form takes an array of b ytes , and two ints , where off is the firs t byte to be read and le n is the num ber of
bytes to be read.
ByteArrayInputStream bArray = new ByteArrayInputStream(byte []a,
int off,
int len)
Once you ha ve ByteArrayI nputStream object in hand then there is a lis t of helper m ethods which can be used to
read the s tream or to do other operations on the s tream .
SN Methods w ith Description
1
Example:
Following is the example to demons trate Byte Arra yInputStream and Byte Arra yOutputStream
import java.io.*;
public class ByteStreamTest {
public static void main(String args[])throws IOException {
ByteArrayOutputStream bOutput = new ByteArrayOutputStream(12);
while( bOutput.size()!= 10 ) {
// Gets the inputs from the user
bOutput.write(System.in.read());
}
byte b [] = bOutput.toByteArray();
DataInputStream
The DataInputStream is us ed in the context of DataOutputStream and can be us ed to read prim itives .
Following is the cons tructor to create an InputStream :
InputStream in = DataInputStream(InputStream in);
Once you ha ve DataI nputStream object in hand then there is a lis t of helper methods which can be us ed to read
the s tream or to do other operations on the s tream .
SN Methods w ith Description
1
public fina l int read(byte[] r , int off, int len)throw s IOEx ception
Reads up to len bytes of data from the input s tream into an array of b ytes . Returns the total
number of bytes read into the buffer otherwis e -1 if it is end of file.
Example:
Following is the exam ple to demons trate DataInputStream and DataInputStream . This exam ple reads 5
lines given in a file tes t.txt and con vert thos e lines into capital letters and finally copies them into another file
tes t1.txt.
import java.io.*;
public class Test{
public static void main(String args[])throws IOException{
DataInputStream d = new DataInputStream(new
FileInputStream("test.txt"));
DataOutputStream out = new DataOutputStream(new
FileOutputStream("test1.txt"));
String count;
while((count = d.readLine()) != null){
String u = count.toUpperCase();
System.out.println(u);
out.writeBytes(u + " ,");
} d.close();
out.close();
}
}
Here is the s ample run of the above p rogram :
THIS
THIS
THIS
THIS
THIS
IS
IS
IS
IS
IS
TEST
TEST
TEST
TEST
TEST
1
2
3
4
5
,
,
,
,
,
FileOutputStream:
FileOutputStream is us ed to create a file and write data into it.The s tream would create a file, if i t d oes n't alread y
exis t, before opening i t for output.
Here are two cons tructors which can be used to create a FileOutputStream object.
Following cons tructor takes a file nam e as a s tring to create an input s tream object to write the file:
OutputStream f = new FileOutputStream("C:/java/hello")
Following cons tructor takes a file object to create an output s tream object to write the file. Firs t we create a file
object us ing File() m ethod as follows :
File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f);
Once you ha ve OutputStream object in hand then there is a lis t of helper m ethods which can be us ed to write to
s tream or to do other operations on the s tream .
SN Methods w ith Description
1
There are other im portant output s treams available, for m ore detail you can refer to the following links :
ByteArrayOutputStream
The Byte Arra yOutputS tream class s tream creates a buffer in m em ory and all the data s ent to the s tream is s tored
in the buffer. There are following forms of cons tructors to create Byte Arra yOutputStream objects
Following cons tructor creates a buffer of 32 b yte:
OutputStream bOut = new ByteArrayOutputStream()
Following cons tructor creates a buffer of s ize int a:
OutputStream bOut = new ByteArrayOutputStream(int a)
Once you ha ve ByteArrayOutputStream object in hand then there is a lis t of helper m ethods which can be used to
write the s tream or to do other operations on the s tream .
SN Methods w ith Description
1
This m ethod creates a newly allocated Byte arra y. Its s ize would be the current s ize of the outpu t
s tream and the contents of the buffer will be copied into it. Returns the current contents of the
output s tream as a byte array.
public String toString()
Converts the buffer content into a s tring. Trans lation will be done according to the default
character encoding. Returns the String trans lated from the buffer.s content.
Example:
Following is the example to demons trate Byte Arra yOutputS tream and Byte Arra yOutputStream
import java.io.*;
public class ByteStreamTest {
public static void main(String args[])throws IOException {
ByteArrayOutputStream bOutput = new ByteArrayOutputStream(12);
while( bOutput.size()!= 10 ) {
// Gets the inputs from the user
bOutput.write(System.in.read());
}
byte b [] = bOutput.toByteArray();
System.out.println("Print the content");
for(int x= 0 ; x < b.length; x++) {
//printing the characters
System.out.print((char)b[x] + "
");
}
System.out.println("
");
int c;
ByteArrayOutputStream bInput = new ByteArrayOutputStream(b);
System.out.println("Converting characters to Upper case " );
for(int y = 0 ; y < 1; y++ ) {
while(( c= bInput.read())!= -1) {
System.out.println(Character.toUpperCase((char)c));
}
bInput.reset();
}
}
}
Here is the s ample run of the above p rogram :
asdfghjkly
Print the content
a
s
d
f
g
h
j
k
l
y
Converting characters to Upper case
A
S
D
F
G
H
J
K
L
DataOutputStream
The DataOutputStream s tream let you write the primitives to an output s ource.
Following is the cons tructor to create an DataOutputStream .
DataOutputStream out = DataOutputStream(OutputStream
out);
Once you ha ve DataOutputStream object in hand then there is a lis t of helper m ethods which can be us ed to write
the s tream or to do other operations on the s tream .
SN Methods w ith Description
1
Writes the current number of bytes written to this data output s tream . Returns the total num ber of
bytes write into the buffer.
Example:
Following is the exam ple to demons trate DataInputStream and DataInputStream . This exam ple reads 5
lines given in a file tes t.txt and con vert thos e lines into capital letters and finally copies them into another file
tes t1.txt.
import java.io.*;
public class Test{
public static void main(String args[])throws IOException{
DataInputStream d = new DataInputStream(new
FileInputStream("test.txt"));
DataOutputStream out = new DataOutputStream(new
FileOutputStream("test1.txt"));
String count;
while((count = d.readLine()) != null){
String u = count.toUpperCase();
System.out.println(u);
out.writeBytes(u + " ,");
} d.close();
out.close();
IS
IS
IS
IS
IS
TEST
TEST
TEST
TEST
TEST
1
2
3
4
5
,
,
,
,
,
Example:
Following is the example to demons trate InputStream and OutputStream :
import java.io.*;
public class fileStreamTest{
public static void main(String args[]){
try{
byte bWrite [] = {11,21,3,40,5};
OutputStream os = new FileOutputStream("C:/test.txt");
for(int x=0; x < bWrite.length ; x++){
os.write( bWrite[x] ); // writes the bytes
}
os.close();
InputStream is = new FileInputStream("C:/test.txt");
int size = is.available();
for(int i=0; i< size; i++){
System.out.print((char)is.read() + "
}
is.close();
}catch(IOException e){
System.out.print("Exception");
}
}
");
}
The above code would create file tes t.txt and would write gi ven num bers in binary form at. Sam e would be output
on the s tdout s creen.
File Class
Java File class represents the files and directory pathnam es in an abs tract m anner. This class is used for creation
of files and directories , file s earching, file deletion etc.
The File object repres ents the actual file/directory on the dis k. There are following cons tructors to create a File
object:
Following s yntax creates a new File ins tance from a parent abs tract pathnam e and a child pathname s tring.
File(File parent, String child);
Following s yntax creates a new File ins tance by con verting the gi ven pathnam e s tring into an abs tract pathnam e.
File(String pathname)
Following s yntax creates a new File ins tance from a parent pathnam e s tring and a child pathnam e s tring.
File(String parent, String child)
Following s yntax creates a new File ins tance by con verting the gi ven file: URI into an abs tract pathname.
File(URI uri)
Once you ha ve File object in hand then there is a lis t of helper m ethods which can be used m anipulate the files .
SN Methods w ith Description
1
Tes ts whether the application can read the file denoted by this abs tract pathname. Returns true if
and only i f the file s pecified by th is abs tract pathnam e exis ts and can be read by the application;
false otherwise.
public boolean canW rite()
Tes ts whether the application can modify to the file denoted by this abs tract pathnam e. Returns
true if and onl y i f the file s ys tem actually contains a file denoted by this abs tract pathname and the
application is allowed to write to the file; fals e otherwis e.
public boolean exists()
Tes ts whether the file or directory denoted b y this abs tract pathnam e exis ts . Returns true if and
only if the file or directory denoted b y this abs tract pathname exis ts ; false otherwis e
created by a Ja va application is guaranteed to be a normal file. Returns true if and onl y if the file
denoted by this abs tract pathnam e exis ts and is a normal file; fals e otherwis e
public long lastModif ied()
12
Returns the tim e that the file denoted b y this abs tract pathname was las t m odified. Returns a long
value repres enting the time the file was las t m odified, m easured in millis econds s ince the epoch
(00:00:00 GMT, January 1 , 19 70), or 0L if the file does not e xis t or if an I/O error occu rs .
Atom ically creates a new, em pty file named by this abs tract pathnam e if and only i f a file with this
name does not ye t e xis t. Returns true if the nam ed file does not exis t and was s uccess fully
created; false if the nam ed file already e xis ts .
public boolean delete()
15
Deletes the file or directory denoted b y this abs tract pathname. If this pathnam e denotes a
directory, then the directory m us t be em pty in order to be deleted. Returns true if and onl y i f the file
or directory is s uccess fully deleted; fals e otherwis e.
23
27
public static File createTempFile(String prefix, String suffix, File director y) throw s
IO Exception
Creates a new empty file in the s pecified directory, us ing the given prefi x and s uffix s trings to
generate its name. Returns an abs tract pathnam e denoting a newly-created empty file .
28
31
Example:
Following is the example to demons trate File object:
import java.io.File;
public class DirList {
public static void main(String args[]) {
String dirname = "/java";
File f1 = new File(dirname);
if (f1.isDirectory()) {
System.out.println( "Directory of " + dirname);
String s[] = f1.list();
for (int i=0; i < s.length; i++) {
File f = new File(dirname + "/" + s[i]);
if (f.isDirectory()) {
System.out.println(s[i] + " is a directory");
} else {
System.out.println(s[i] + " is a file");
}
}
} else {
System.out.println(dirname + " is not a directory");
}
}
}
This would produce following result:
Directory of /mysql
bin is a directory
lib is a directory
demo is a directory
test.txt is a file
README is a file
index.html is a file
include is a directory
FileReader Class
This class inherits from the InputStreamReader class . FileReader is us ed for reading s treams of characters .
This class has s everal cons tructors to create required objects .
Following s yntax creates a new FileReader, gi ven the File to read from .
FileReader(File file)
Following s yntax creates a new FileReader, gi ven the FileDes criptor to read from .
FileReader(FileDescriptor fd)
Following s yntax creates a new FileReader, gi ven the nam e of the file to read from .
FileReader(String fileName)
Once you ha ve FileReader object in h and then there is a lis t of helper m ethods which can be used manipulate the
files .
SN
Example:
Following is the example to demons trate class :
import java.io.*;
public class FileRead{
public static void main(String args[])throws IOException{
File file = new File("Hello1.txt");
// creates the file
file.createNewFile();
// creates a FileWriter Object
FileWriter writer = new FileWriter(file);
// Writes the content to the file
writer.write("This\n is\n an\n example\n");
writer.flush();
writer.close();
//Creates a FileReader Object
FileWriter Class
This class inherits from the OutputStream Writer class . The class is used for writing s treams of characters .
This class has s everal cons tructors to create required objects .
Following s yntax creates a FileWriter object gi ven a File object.
FileWriter(File file)
Following s yntax creates a FileWriter object gi ven a File object.
FileWriter(File file, boolean append)
Following s yntax creates a FileWriter object associated with a file des criptor.
FileWriter(FileDescriptor fd)
Following s yntax creates a FileWriter object gi ven a file name.
FileWriter(String fileName)
Following s yntax creates a FileWriter object gi ven a file nam e with a boolean indicating whether or not to append
the data written.
FileWriter(String fileName, boolean append)
Once you ha ve FileWriter object in hand then there is a lis t of helper m ethods which can be used manipulate the
files .
SN
Example:
Following is the example to dem ons trate class :
import java.io.*;
public class FileRead{
public static void main(String args[])throws IOException{
File file = new File("Hello1.txt");
// creates the file
file.createNewFile();
// creates a FileWriter Object
FileWriter writer = new FileWriter(file);
// Writes the content to the file
writer.write("This\n is\n an\n example\n");
writer.flush();
writer.close();
//Creates a FileReader Object
FileReader fr = new FileReader(file);
char [] a = new char[50];
fr.read(a); // reads the content to the array
for(char c : a)
System.out.print(c); //prints the characters one by one
fr.close();
}
}
This would produce following res ult:
This
is
an
example
Directories in Java:
Creating Directories:
There are two us eful File utility m ethods which can be us ed to create directories :
The mkdir( ) m ethod creates a directory, returning true on success and fals e on failure. Failure indicates that
the path s pecified in the File object alread y e xis ts , or that the directory cannot be created becaus e the entire
path does not exis t yet.
The mkdirs() m ethod creates both a directory and all the parents of the directory.
Following exam ple creates "/tmp/us er/java/bin" directory:
import java.io.File;
public class CreateDir {
public static void main(String args[]) {
String dirname = "/tmp/user/java/bin";
File d = new File(dirname);
// Create directory now.
d.mkdirs();
}
}
Com pile and execute above code to create "/tm p/user/java/bin".
Note : Ja va autom atically takes care of path separators on UNIX and Windows as per conventions . If you us e a
forward s lash (/) on a Windows version of Ja va, the path will s till res olve correctly.
Reading Directories:
A directory is a File that contai ns a lis t of other files and directories . When you create a File obj ect and it is a
directory, the is Directory( ) m ethod will return true.
You can call lis t( ) on that object to e xtract the lis t of other files and directories ins ide. The program s hown here
illus trates how to use lis t( ) to exam ine the contents of a directory:
import java.io.File;
public class DirList {
public static void main(String args[]) {
String dirname = "/java";
File f1 = new File(dirname);
if (f1.isDirectory()) {
System.out.println( "Directory of " + dirname);
String s[] = f1.list();
for (int i=0; i < s.length; i++) {
File f = new File(dirname + "/" + s[i]);
if (f.isDirectory()) {
System.out.println(s[i] + " is a directory");
} else {
System.out.println(s[i] + " is a file");
}
}
} else {
System.out.println(dirname + " is not a directory");
}
}
}
This would produce following result:
Directory of /mysql
bin is a directory
lib is a directory
demo is a directory
test.txt is a file
README is a file
index.html is a file
include is a directory
CHAPTER
19
Java Exceptions
n exception is a problem that aris es during the execution of a program . An e xception can occur for
A network connection has been los t in the m iddle of comm unications , or the JVM has run out of mem ory.
others
by
phys ical
res ources that have failed in som e manner.
To unders tand how exception handling works in Java, you need to unders tand the three categories of e xceptions :
Checked exceptions : A checked e xception is an excepti on that is typicall y a user error or a problem that
cannot be fores een by the programm er. For exam ple, if a file is to be opened, but the file cannot be found, an
exception occurs . These exceptions cannot sim ply be ignored at the time of com pilation.
Runt ime exceptions : A runtim e exception is an e xception that occurs that probabl y c ould ha ve
been avoided by the programm er. As opposed to checked exceptions , runtime exceptions are ignored at
the time
of com pliation.
Errors : Thes e are not e xceptions at all, but problems that arise beyond the control of the us er or
the programm er. Errors are typicall y ignored in your code because you can rarel y do an ything about an error.
For
exam ple, if a s tack overflow occurs , an error will aris e. The y are also ignored at the tim e of com pilation.
Exception Hierarchy:
All e xception classes are s ubtypes of the java.lang.Exception class . The exception class is a subclass of
the Throwable class . Other than the exception class there is another s ubclass called Error which is derived from
the Throwable class .
Errors are not norm ally trapped form the Java programs . These conditions normally happen in cas e of s evere
failures , which are not handled by the ja va programs . Errors are generated to indicate errors generated by the
runtim e environm ent. Exam ple : JVM is out of Mem ory. Norm ally programs cannot recover from errors .
The Exception class has two main s ubclasses : IOE xception class and Runtim eException Class .
Description
Arithm eticException
Arra yStoreException
In valid cas t.
IllegalArgumentException
IllegalMonitorStateException
IllegalStateException
IllegalThreadStateException
IndexOutOfBounds Exception
NullPointerException
SecurityException
StringIndexOutOfBounds
Uns upportedOperationException
Description
Class NotFoundException
CloneNotSupportedExcepti on
Attem pt to clone an object tha t does not im plem ent the Cloneable
interface.
IllegalAccess Exception
Ins tantiationException
InterruptedException
NoSuchFieldException
NoSuchMethodException
Exceptions Methods:
Following is the lis t of important m ethods available in the Throwable class .
SN Methods w ith Description
1
Returns an array containing each elem ent on the s tack trace. The elem ent at inde x 0 represen ts
the top of the call s tack, and the las t elem ent in the arra y represents the method at the bottom of
the call s tack.
public Throw able f illInStackTrace()
Fills the s tack trace of this Throwable object with the current s tack trace, adding to an y pre vious
inform ation in the s tack trace.
Catching Exceptions:
A m ethod catches an exception using a com bination of the try and catch ke ywords . A try/catch block is placed
around the code that might generate an excepti on. Code within a try/catch block is referred to as protected code,
and the s yntax for us ing try/catch looks like the following:
try
{
//Protected code
}catch(ExceptionName e1)
{
//Catch block
}
A catch s tatem ent involves declaring the type of exception you are tr ying to catch. If an e xception occurs
in protected code, the catch block (or blocks ) that follows the try is checked. If the type of e xception that occurred
is lis ted in a catch block, the exception is pass ed to the catch block much as an argument is pass ed into a
m ethod parameter.
Example:
The following is an array is declared with 2 elem ents . Then the code tries to access the 3rd elem ent of the arra y
which throws an exception.
// File Name : ExcepTest.java
import java.io.*;
public class ExcepTest{
public static void main(String args[]){
try{
int a[] = new int[2];
System.out.println("Access element three :" + a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown
:" + e);
}
System.out.println("Out of the block");
}
}
This would produce following result:
Exception thrown
Out of the block
:java.lang.Array IndexOutOfBoundsException: 3
Example:
Here is code s egment showing how to us e m ultiple try/catch s tatem ents .
try
{
file = new FileInputStream(fileName);
x = (byte) file.read();
}catch(IOException i)
{
i.printStackTrace();
return -1;
}catch(FileNotFoundException f) //Not valid!
{
f.printStackTrace();
return -1;
}
Using a finally block allows you to run an y cleanup -type s tatem ents that you wan t to e xecute , no matter what
happens in the protected code.
A finall y block appears at the end of the catch blocks and has the following s yntax:
try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}finally
{
//The finally block always executes.
}
Example:
public class ExcepTest{
public static void main(String args[]){
int a[] = new int[2];
try{
System.out.println("Access element three :" + a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown
:" + e);
}
finally{
a[0] = 6;
System.out.println("First element value: " +a[0]);
System.out.println("The finally statement is executed");
}
}
}
This would produce following result:
Exception thrown :java.lang.Array IndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed
Note the following:
It is not com puls ory to have finall y claus es when ever a try/catch block is present.
The try block canno t be present withou t either catch clause or finally claus e.
An y code canno t be pres ent in b etween the try, catch, finall y blocks .
If you want to write a checked e xception that is autom atically enforced by the Handle or Declare Rule , you
need to extend the Exception class .
If you wan t to write a runtim e exce ption, you need to e xtend the Runtim eException class .
Example:
// File Name InsufficientFundsException.java
import java.io.*;
public class InsufficientFundsException extends Exception
{
private double amount;
public InsufficientFundsException(double amount)
{
this.amount = amount;
}
public double getAmount()
{
return amount;
}
}
To dem ons trate us ing our us er-defined exception, the following Checking Account class contains a withdraw()
m ethod that throws an Ins ufficientFunds Exception.
// File Name CheckingAccount.java
import java.io.*;
public class CheckingAccount
{
private double balance;
private int number;
public CheckingAccount(int number)
{
this.number = number;
}
public void deposit(double amount)
{
balance += amount;
}
Common Exceptions:
In java it is poss ible to define two catergories of Exceptions and Errors .
JVM Exceptions : - Thes e are e xceptions /errors that are e xclus ivel y or logicall y thrown b y the J VM.
Exam ples : NullPointerException , Arra yInde xOutOfBounds Exception, ClassCas tException,
Programmatic exceptions . Thes e e xceptions are thrown e xplicitl y b y the application or the API
programm ers Examples : Illegal Argum entException, IllegalStateException.
CHAPTER
20
Java Inheritance
nheritance can be defined as the process where one object acquires the properties of another. With the us e
IS-A Relationship:
IS-A is a wa y o f s aying : This obje ct is a type of that object. Let us see how the extends keyword is us ed
to achieve inheritance .
public class Animal{
}
public class Mammal extends Animal{
}
public class Reptile extends Animal{
}
public class Dog extends Mammal{
}
Now bas ed on the above exam ple, In Object Oriented terms following are true:
With use of the extends keyword the s ubclasses will be able to inherit all the properties of the s uperclass except
for the private properties of the s uperclass .
We can ass ure that Mam mal is actually an Anim al with the use of the ins tance operator.
Example:
public class Dog extends Mammal{
public static void main(String args[]){
Animal a = new Animal();
Mammal m = new Mammal();
Dog d = new Dog();
System.out.println(m instanceof Animal);
System.out.println(d instanceof Mammal);
System.out.println(d instanceof Animal);
}
}
This would produce following result:
true
true
true
Since we have a good unders tanding of the extends ke yword let us look into how the implementskeyword
is us ed to get the IS- A relations hip.
The implements keyword is us ed by classes by inherit from interfaces . Interfaces can never be extended b y the
class es .
Example:
public interface Animal {}
public class Mammal implements Animal{
}
public class Dog extends Mammal{
}
HAS-A relationship:
These relationships are m ainly bas ed on the us age. This determ ines whether a certain class HAS-Acertain thing .
This relationship helps to reduce duplication of code as well as bugs .
Lets us look into an exam ple:
public class Vehicle{}
public class Speed{}
public class Van extends Vehicle{
private Speed sp;
}
This shows that class Van HAS-A Speed. By ha ving a separate class for Speed we do not have to put the entire
code that belongs to speed ins ide the Van class ., which m akes it poss ible to reus e the Speed class in m ultiple
applications .
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 im plem entation details from the users of the Van clas s . SO bas ically what happens is
the us ers would as k the Van class to do a certain action and the Vann class will e ither do the work by its elf or as k
another class to perform the action.
A ver y im portant fact to rem em ber is that Java onl y s upports only s ingle inheritance. This m eans that a
class cannot extend more than one class . Therefore following is illegal:
public class extends Animal, Mammal{}
However a class can im plem ent one or more interfaces . This has m ade Java get rid of the im poss ibility of m ultiple
inheritance
CHAPTER
21
Java Overriding
n the previous chapter we talked about s uper classes and sub class es . If a class inherits a m ethod from its
s uper class , then there is a chance to override the m ethod provided that it is not m arked final.
The benefit o f o verriding is : ab ility to define a beha vior that's s pecific to the s ub class type. Which m eans
a s ubclass can im plement a parent cl ass method based on its requirement.
In object oriented terms , overriding m eans to override the functionality of an y e xis ting m ethod.
Example:
Let us look at an e xam ple.
class Animal{
public void move(){
System.out.println("Animals can move");
}
}
class Dog extends Animal{
public void move(){
System.out.println("Dogs can walk and run");
}
}
public class TestDog{
public static void main(String args[]){
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
a.move();// runs the method in Animal class
b.move();//Runs the method in Dog class
}
The access level cannot be m ore res trictive than the o verridden method's access level. For e xam ple: if the
s uper class method is declared public then the overriding m ethod in the s ub class cannot be either private or
protected.
Ins tance methods can be overridden only i f the y are inherited b y the s ubclass .
A m ethod declared final cannot be o verridden.
A m ethod declared s tatic cannot be o verridden but can be re-declared.
If a m ethod cannot be inherited then i t canno t be o verridden.
A s ubclass within the sam e package as the ins tance's superclass can override any s uperclass m ethod that is
not declared pri vate or final .
A s ubclass in a different package can onl y o verride the non-final m ethods declared public or protected.
An o verriding m ethod can throw an y uncheck e xceptions , regardless of whether the overridden method throws
exceptions or not. Howe ver the o verriding m ethod s hould not throw checked e xceptions that are new
or broader than the ones declared by the o verridden m ethod. The overriding m ethod can throw narrower or
fewer exceptions than the overridden method.
CHAPTER
22
Java Polymorphism
olym orphism is the ability of an object to take on m any form s . The m os t common us e of polymorphism in
OOP occurs when a parent class reference is used to refer to a child class object.
An y ja va object tha t can pass m ore than one IS-A tes t is cons idered to be polym orphic. In Java , all ja va objects
are polym orphic since any object will pass the IS-A tes t for their own type and for the class Object.
It is important to know that the onl y p os sible way to access an object is through a reference variable . A reference
variable can be o f onl y one t ype . Once declared the type of a reference variable canno t be change d.
The reference variable can be reass igned to other objects provided that it is not declared final . The type o f the
reference variable would determ ine the m ethods that it can in voke on the object.
A reference variable can refer to an y object of its declared type or an y s ubtype of its declared type . A reference
variable can be declared as a class or interface type.
Example:
Let us look at an e xam ple.
public interface Vegetarian{}
public class Animal{}
public class Deer extends Animal implements Vegetarian{}
Now the Deer class is cons idered to be polym orphic s ince this has m ultiple inheritance. Following are true for the
above e xam ple:
When we apply the reference variable facts to a Deer object reference, the following declarations are legal:
Deer d = new Deer();
Animal a = d;
Vegetarian v = d;
Object o = d;
All the reference variables d,a,v,o refer to the s am e Deer object in the heap.
Virtual Methods:
In this s ection, I will s how you how the beha vior of o verridden m ethods in Java allows you to take advantage o f
polym orphism when designing your class es .
We already ha ve dis cussed m ethod overriding, where a child class can override a m ethod in its parent.
An o verridden m ethod is ess entially hidden in the parent class , and is not invoked unless the child class us es
the s uper keyword within the overriding method.
/* File name : Employee.java */
public class Employee
{
private String name;
private String address;
private int number;
public Employee(String name, String address, int number)
{
System.out.println("Constructing an Employee");
this.name = name;
this.address = address;
this.number = number;
}
public void mailCheck()
{
System.out.println("Mailing a check to " + this.name
+ " " + this.address);
}
public String toString()
{
return name + " " + address + " " + number;
}
public String getName()
{
return name;
}
public String getAddress()
{
return address;
}
public void setAddress(String newAddress)
{
address = newAddress;
}
public int getNumber()
{
return number;
}
}
Now suppose we extend Employee class as follows :
/* File name : Salary.java */
public class Salary extends Employee
{
private double salary; //Annual salary
public Salary(String name, String address, int number, double
salary)
{
super(name, address, number);
setSalary(salary);
}
public void mailCheck()
{
System.out.println("Within mailCheck of Salary class ");
System.out.println("Mailing check to " + getName()
+ " with salary " + salary);
}
public double getSalary()
{
return salary;
}
public void setSalary(double newSalary)
{
if(newSalary >= 0.0)
{
salary = newSalary;
}
}
public double computePay()
{
System.out.println("Computing salary pay for " + getName());
return salary/52;
}
}
Now you s tudy the following program carefull y and try to determ ine its output:
/* File name : VirtualDemo.java */
public class VirtualDemo
{
public static void main(String [] args)
{
Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP",
3, 3600.00);
Employee e = new Salary("John Adams", "Boston, MA",
2, 2400.00);
System.out.println("Call mailCheck using
Salary reference --");
s.mailCheck();
System.out.println("\n Call mailCheck using
Employee reference--");
e.mailCheck();
}
}
This would produce following result:
Constructing an Employee
Constructing an Employee
Call mailCheck using Salary reference -Within mailCheck of Salary class
Mailing check to Mohd Mohtashim with salary 3600.0
Call mailCheck using Employee reference-Within mailCheck of Salary class
Mailing check to John Adams with salary 2400.0
Here we ins tantiate two Salary objects . one us ing a Salary reference s , and the other using an
Em ployee reference e.
While invoking s.m ailCheck () the compiler sees m ailCheck() in the Salary class at com pile tim e, and the
JVM
invokes m ailCheck() in the Salary class at run time.
Invoking m ailCheck() on e is quite different b ecause e is an Em ployee reference. When the com piler
s ees e.m ailCheck (), the com piler s ees the m ailCheck() m ethod in the Em ployee clas s .
Here, a t com pile tim e, the com piler us ed m ailCheck() in Em ploye e to validate this s tatem ent. At run
tim e, however, the J VM in vokes m ailCheck() in the Salary class .
This behavior is referred to as virtual m ethod invocation, and the methods are referred to as virtual m ethods . All
m ethods in Java beha ve in this manner, whereby an o verridden m ethod is invoked at run tim e, no matter what
data type the reference is that was us ed in the s ource code at com pile tim e.
CHAPTER
23
Java Abstraction
bs traction refers to the ability to m ake a class abs tract in OOP. An abs tract class is one that cannot be
ins tantiated. All other functi onality of the class s till exis ts , and its fields , m ethods , and cons tructors are
all accessed in the s ame manner. You jus t cannot create an ins tance of the abs tract clas s .
If a class is abs tract and cannot be ins tantiated, the class does not have much us e unless it is s ubclass ed. This is
typicall y how abs tract classes come about during the des ign phas e. A paren t class contains the
common functionality of a collection of child class es , but the parent class its elf is too abs tract to be us ed on its
own.
Abstract Class:
Use the abstract keyword to declare a class abs tract. The keyword appears in the class declaration s omewhere
before the class keyword.
/* File name : Employee.java */
public abstract class Employee
{
private String name;
private String address;
private int number;
public Employee(String name, String address, int number)
{
System.out.println("Constructing an Employee");
this.name = name;
this.address = address;
this.number = number;
}
public double computePay()
{
System.out.println("Inside Employee computePay");
return 0.0;
}
public void mailCheck()
{
System.out.println("Mailing a check to " + this.name
+ " " + this.address);
}
public String toString()
{
return name + " " + address + " " + number;
}
UP",
Abstract Methods:
If you wan t a class to contain a particular m ethod but you want the actual im plem entation of that m ethod to be
determ ined by child class es , you can declare the m ethod in the parent class as abs tract.
The abs tract keyword is also us ed to declare a m ethod as abs tract. An abs tract m ethods cons is t of a m ethod
s ignature, but no m ethod body.
Abs tract m ethod would have no definition, and its s ignature is followed by a s em icolon, not curl y braces
as follows :
public abstract class Employee
{
private String name;
private String address;
private int number;
public abstract double computePay();
//Remainder of class definition
}
Declaring a m ethod as abs tract has two res ults :
The class mus t also be declared abs tract. If a class contains an abs tract m ethod, the class m us t be abs tract
as well.
An y child class m us t either override the abs tract method or declare itself abs tract.
A child class that inherits an abs tract m ethod mus t override it. If the y do not, the y m us t be abs tract,and any of
their children m us t override it.
Eventuall y, a des cendant class has to im plement the abs tract method; otherwis e, you would ha ve a hierarch y o f
abs tract classes that cannot be ins tantiated.
If Salar y is extending Em ployee class then it is required to im plement com putePay() m ethod as follows :
/* File name : Salary.java */
public class Salary extends Employee
{
private double salary; // Annual salary
public double computePay()
{
System.out.println("Computing salary pay for " + getName());
return salary/52;
}
//Remainder of class definition
}
CHAPTER
24
Java Encapsulation
ncapsulation is one of the four fundam ental OOP concepts . The other three are inheritance,
Example:
Let us look at an e xam ple that de picts encaps ulation:
/* File name : EncapTest.java */
public class EncapTest{
private String name;
private String idNum;
private int age;
public int getAge(){
return age;
}
public String getName(){
return name;
}
public String getIdNum(){
return idNum;
}
public void setAge( int newAge){
age = newAge;
}
Benefits of Encapsulation:
The fields of a class can be m ade read-only or write-onl y.
A class can have total control over wh at is s tored in its fields .
The us ers of a class do not know how the class s tores its data. A class can change the data type of a field , and
us ers of the class do not need to change an y of their code.
CHAPTER
25
Java Interfaces
n interface is a collection of abs tract methods . A clas s im plem ents an interface, thereby inheriting the
Declaring Interfaces:
The interface keyword is us ed to declare an interface. Here is a s im ple exam ple to declare an interface:
Example:
Let us look at an e xam ple that de picts encaps ulation:
/* File name : NameOfInterface.java */
import java.lang.*;
//Any number of import statements
public interface NameOfInterface
{
//Any number of final, static fields
//Any number of abstract method declarations\
}
Interfaces have the following properties :
An interface is implicitly abs tract. You do no t need to us e the abstract keyword when declaring an interface .
Each m ethod in an interface is als o im plicitly abs tract, so the abs tract keyword is not needed.
Methods in an interface are im plicitly public.
Example:
/* File name : Animal.java */
interface Animal {
public void eat();
public void travel();
}
Implementing Interfaces:
When a class implements an interface, you can think of the class as s igning a contract, agreeing to perform the
s pecific behaviors of the interface. If a class does not perform all the behaviors of the interface, the class mus t
declare itself as abs tract.
Aclass uses the implements keyword to implement an interface. The implements keyword appears in the class
declaration following the extends portion of the declaration.
/* File name : MammalInt.java */
public class MammalInt implements Animal{
public void eat(){
System.out.println("Mammal eats");
}
public void travel(){
System.out.println("Mammal travels");
}
public int noOfLegs(){
return 0;
}
Checked exceptions s hould not be declared on implementation m ethods other than the ones declared by the
interface method or s ubclasses of thos e declared by the interface m ethod.
The s ignature of the interface m ethod and the s ame return type or s ubtype s hould be m aintained
when overriding the methods .
An im plem entation class its elf can be abs tract and if s o interface m ethods need not be im plem ente d.
When implem entation interfaces there are s everal rules :
Extending Interfaces:
An interface can e xtend another interface, s imilarly to the wa y that a class can extend another class .
The extends keyword is used to extend an interface , and the child interface inherits the m ethods of the parent
interface.
The following Sports interface is extended b y Hocke y and Football interfaces .
//Filename: Sports.java
public interface Sports
{
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}
//Filename: Football.java
public interface Football extends Sports
{
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}
//Filename: Hockey.java
public interface Hockey extends Sports
{
public void homeGoalScored();
public void visitingGoalScored();
Tagging Interfaces:
The m os t comm on us e of extending interfaces occurs when the parent interface does not contain any methods .
For exam ple, the Mous eLis tener interface in the java.awt.even t package e xtended java.util.EventLis tener, which
is defined as :
package java.util;
public interface EventListener
{}
An interface with no m ethods in it is referred to as a tagging interface. There are two basic des ign purposes of
tagging interfaces :
Creates a common parent: As with the EventLis tener interface, which is extended by do zens of other interfaces
in the Java API, you can us e a tagging interface to create a comm on parent am ong a group of interfaces . For
exam ple, when an interface extends EventLis tener, the JVM knows that this particular interface is going to be
us ed in an event delegation s cenario.
Adds a data type to a class : This s ituation is where the term tagging com es from . A class that im plements a
tagging interface does not need to define any m ethods (since the interface does not have any), but the class
becom es an interface type through polymorphism .
CHAPTER
26
Java Packages
ackages
are used in Java in-order to pre vent nam ing conflicts , to control access , to m ake
s earching/locating and us age of classes , interfaces , enumerations and annotations eas ier etc.
A Package can be defined as a grouping of related types (class es , interfaces , enum erations and annotations )
providing access protection and name s pace m anagement.
Some of the exis ting packages in Java are:
Creating a package:
When creating a package, you s hould choose a nam e for the package and put a package s tatem ent with that
name at the top of every s ource file that contains the class es , interfaces , enumerations , and annotation types that
you wan t to include in the package .
The package s tatement should be the firs t line in the source file. There can be only one package s tatement in
each source file, and it applies to all types in the file.
If a package s tatement is not us ed then the class , interfaces , enumerations , and annotation types will be put into
an unnamed package.
Example:
Let us look at an e xam ple that cre ates a package called animals. It is comm on practice to us e lowercased names
of packages to avoid an y conflicts with the nam es of class es , interfaces .
Put an interface in the package anim als:
/* File name : Animal.java */
package animals;
interface Animal {
public void eat();
public void travel();
}
Now put an im plem entation in the s am e package anim als:
package animals;
/* File name : MammalInt.java */
public class MammalInt implements Animal{
public void eat(){
System.out.println("Mammal eats");
}
public void travel(){
System.out.println("Mammal travels");
}
public int noOfLegs(){
return 0;
}
public static void main(String args[]){
MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}
Now you com pile thes e two files and put them in a s ub-directory called animals and try to run as follows :
$ mkdir animals
$ cp Animal.class MammalInt.class animals
$ java animals/MammalInt
Mammal eats
Mammal travels
Example:
Here a class nam ed Boss is added to the payroll package that alread y contains Em ployee. The Boss can then
refer to the Em ployee class without us ing the payroll prefi x, as demons trated by the following Boss class .
package payroll;
public class Boss
{
public void payEmployee(Employee e)
{
e.mailCheck();
}
}
What happens i f Boss is not in the pa yroll package? The Boss class m us t then us e one of the
following techniques for referring to a class in a different package.
The full y qualified nam e of the class can be used. For exam ple:
payroll.Employee
The package can be im ported us ing the im port keyword and the wild card (*). For e xam ple:
import payroll.*;
The class itself can be im ported us ing the im port keyword. For e xam ple:
import payroll.Employee;
Note : A class file can contain any num ber of im port s tatem ents . The im port s tatem ents mus t appear after the
package s tatem ent and before the class declaration.
The nam e of the package becom es a part of the nam e of the class , as we jus t dis cussed in the previous
s ection.
The name of the package mus t m atch the directory s tructure where the corres ponding bytecode res ides .
Car.java
package vehicle;
public class Car {
// Class implementation.
}
Now put the s ource file in a directory whos e name reflects the nam e of the package to which the class belongs :
....\vehicle\Car.java
Now the qualified class nam e and pathnam e would be as below:
In general a com pany us es its reversed Internet dom ain nam e for its package nam es . Example: A com pany's
Internet dom ain nam e is apple.com , then all its package nam es would s tart with com .apple. Each com ponent of
the package nam e corresponds to a s ubdirectory.
Exam ple: The company had a com .apple.com puters package that contained a Dell.java s ource file, it would be
contained in a s eries of s ubdirectories like this :
....\com\apple\computers\Dell.java
At the tim e of compilation, the com piler creates a different output file for each class , interface and enum eration
defined in it. The base nam e of the output file is the name of the type, and its extens ion is .class
CHAPTER
27
Java Data Structures
he data s tructures provided by the Ja va utility package are ver y powerful and perform a wide range of
functions . These data s tructures consis t of the following interface and classes :
Enumeration
BitSet
Vector
Stack
Dictionary
Has htable
Properties
All thes e classes are now legacy and Ja va-2 has introduced a new fram ework called Collections
Fram ework which is dis cuss ed in next tutorial:
The Enumeration:
The Enumeration interface is n't its elf a data s tructure, but it is very im portant within the conte xt o f oth er
data s tructures . The Enumeration interface defines a m eans to retrieve s uccess ive elements from a data
s tructure.
For exam ple, Enum eration defines a m ethod called nextElem ent that is us ed to get the next elem ent in a data
s tructure that contains multiple elem ents .
The Enum eration interface defines the m ethods by which you can enum erate (obtain one at a tim e) the elem ents
in a collection of objects .
This legacy interface has been s uperceded by Iterator. Although not deprecated, Enumeration is cons idered
obsolete for new code. However, it is us ed by s everal methods defined by the legacy class es s uch as Vector and
Properties , is us ed by s everal other API class es , and is currently in widespread us e in application code.
The m ethods declared by Enum eration are s umm arized in the following table:
Example:
Following is the example s howing us age of Enum eration.
import java.util.Vector;
import java.util.Enumeration;
public class EnumerationTester {
public static void main(String args[]) {
Enumeration days;
Vector dayNames = new Vector();
dayNames.add("Sunday");
dayNames.add("Monday");
dayNames.add("Tuesday");
dayNames.add("Wednesday");
dayNames.add("Thursday");
dayNames.add("Friday");
dayNames.add("Saturday");
days = dayNames.elements();
while (days.hasMoreElements()){
System.out.println(days.nextElement());
}
}
}
This would produce following result:
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
The BitSet
The BitSet class im plem ents a group of bits , or flags , that can be set and cleared indi viduall y.
This class is very us eful in cas es where you need to keep up with a set of boolean values ; you jus t assign a bit to
each value and s et or clear i t as appropriate.
A BitSet class creates a s pecial type of arra y that holds bit values . The BitSet arra y can incre ase in size
as needed. This m akes it s im ilar to a vector of bits .
This is a legacy class but it has been completely re-engineered in Ja va 2, vers ion 1.4
The BitSet defines two cons tructors . The firs t vers ion creates a default object:
BitSet( )
The s econd vers ion allows you to s pecify its initial s ize i.e. the num ber of bits that it can hold . All bits are initiali zed
to zero.
BitSet(int size)
BitSet im plem ents the Cloneable interface and defines the methods lis ted in table below:
SN Methods w ith Description
1
int cardinality( )
Returns the num ber of s et bits in the invoking object.
void clear( )
Zeros all bits .
Object clone( )
Duplicates the invoking BitSet object.
10
11
int hashCode( )
Returns the has h code for the invoking object.
14
15
boolea n is Empty( )
Returns true if all bits in the invoking object are zero.
int le ngth( )
16 Returns the number of bits required to hold the contents of the invoking BitSet. This value is
determ ined by the location of the las t 1 bit.
21
22
int size( )
Returns the num ber of bits in the invoking BitSet object.
25
String t oString( )
Returns the s tring equivalent o f the in voking BitSet object.
void xor(BitSet bitSet)
26
XORs the contents of the in voking BitSet object with that specified by bitSet. The res ult is placed
into the invoking object
Example:
The following program illus trates s everal of the m ethods s upported by this data s tructure:
import java.util.BitSet;
public class BitSetDemo {
public static void main(String args[]) {
BitSet bits1 = new BitSet(16);
BitSet bits2 = new BitSet(16);
// set some bits
for(int i=0; i<16; i++) {
if((i%2) == 0) bits1.set(i);
if((i%5) != 0) bits2.set(i);
}
System.out.println("Initial pattern in bits1: ");
System.out.println(bits1);
System.out.println("\nInitial pattern in bits2: ");
System.out.println(bits2);
// AND bits bits2.and(bits1);
System.out.println("\nbits2 AND bits1: ");
System.out.println(bits2);
// OR bits bits2.or(bits1);
System.out.println("\nbits2 OR bits1: ");
System.out.println(bits2);
// XOR bits bits2.xor(bits1);
System.out.println("\nbits2 XOR bits1: ");
System.out.println(bits2);
}
}
This would produce following result:
Initial pattern in bits1:
{0, 2, 4, 6, 8, 10, 12, 14}
Initial pattern in bits2:
{1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14}
bits2 AND bits1:
{2, 4, 6, 8, 12, 14}
bits2 OR bits1:
{0, 2, 4, 6, 8, 10, 12, 14}
bits2 XOR bits1:
{}
The Vector
The Vector class is sim ilar to a traditional Java arra y, e xcept that it can grow as necess ary to accomm odate new
elem ents .
Like an array, elem ents of a Vector object can be access ed via an inde x into the vector.
The nice thing about us ing the Ve ctor class is that you don't ha ve to worr y abou t s etting it to a s pecific s ize upon
creation; it s hrinks and grows automatically when necess ary.
Vector im plem ents a dynam ic array. It is s im ilar to Arra yLis t, but with two differences :
Vector is s ynchronized .
Vector contains m any legacy m ethods that are not part of the collections fram ework.
Vector pro ves to be very us eful if you don't know the s ize of the arra y in ad vance , or you jus t need one that can
change s izes over the lifetime of a program .
The Vector clas s supports four cons tructors . The firs t form creates a default vector, which has an initial s ize of 10:
Vector( )
The s econd form creates a vector whos e initial capacity is s pecified by s ize:
Vector(int size)
The third form creates a vector whos e initial capacity is s pecified by s ize and whose increm ent is s pecified by
incr. The increm ent s pecifies the num ber of elem ents to allocate each tim e that a vector is res ized upward:
boolea n a dd(Object o)
Appends the s pecified element to the end of this Vector.
int capacity()
Returns the current capacity o f this vector.
voi d clear()
Rem oves all of the elem ents from this Vector.
Object clone()
Returns a clone of this vector.
10
11
12
13
Enumeration elements()
Returns an enum eration of the components of this vector.
boolean equals(Object o)
Com pares the s pecified Object with this Vector for equality.
16
17
18
int hashCode()
Returns the has h code value for this Vector.
22
boolean is Empty()
Tes ts if this vector has no com ponents .
23
24
29
30
31
boolean retainAll(Collectio n c)
Retains only the elements in this Vector that are contained in the s pecified Collection.
34
35
36
37
int size()
39
voi d trimToSize()
Trims the capacity of this vector to be the vec tor's current size.
Example:
The following program illus trates s everal of the m ethods s upported by this collection:
import java.util.*;
public class VectorDemo {
public static void main(String args[]) {
// initial size is 3, increment is 2
Vector v = new Vector(3, 2);
System.out.println("Initial size: " + v.size());
System.out.println("Initial capacity: " +
v.capacity());
v.addElement(new Integer(1));
v.addElement(new Integer(2));
v.addElement(new Integer(3));
v.addElement(new Integer(4));
System.out.println("Capacity after four additions: " +
v.capacity());
v.addElement(new Double(5.45));
System.out.println("Current capacity: " +
v.capacity());
v.addElement(new Double(6.08));
v.addElement(new Integer(7));
System.out.println("Current capacity: " +
v.capacity());
v.addElement(new Float(9.4));
v.addElement(new Integer(10));
System.out.println("Current capacity: " +
v.capacity());
v.addElement(new Integer(11));
v.addElement(new Integer(12));
System.out.println("First element: " +
(Integer)v.firstElement());
System.out.println("Last element: " +
(Integer)v.lastElement());
if(v.contains(new Integer(3)))
System.out.println("Vector contains 3.");
// enumerate the elements in the vector.
Enumeration vEnum = v.elements();
System.out.println("\nElements in vector:");
while(vEnum.hasMoreElements())
System.out.print(vEnum.nextElement() + " ");
System.out.println();
}
}
This would produce following result:
Initial size: 0
Initial capacity: 3
Capacity after four additions: 5
Current capacity: 5
Current capacity: 7
Current capacity: 9
First element: 1
Last element: 12
Vector contains 3.
Elements in vector:
1 2 3 4 5.45 6.08 7 9.4 10 11 12
The Stack
The Stack class im plem ents a las t-in-firs t-out (LIFO) s tack of elements .
You can think o f a s tack literally as a vertical s tack of objects ; when you add a new elem ent, i t gets s tacked on top
of the others .
When you pull an elem ent off the s tack, it com es off the top. In other words , the las t element you added to the
s tack is the firs t one to come back off.
Stack is a s ubclass of Vector tha t im plements a s tandard las t-in, firs t-out s tack.
Stack only defines the default cons tructor, which creates an em pty s tack. Stack includes all the methods defined
by Vector, and adds s everal of its own.
Stack( )
Apart from the methods inherited from its parent class Vector, Stack defines following m ethods :
SN Methods w ith Description
1
Object peek( )
Returns the element on the top of the s tack, but does not remove it.
Object pop( )
Returns the element on the top of the s tack, removing it in the process .
Example:
The following program illus trates s everal of the m ethods s upported by this collection:
import java.util.*;
public class StackDemo {
static void showpush(Stack st, int a) {
st.push(new Integer(a));
System.out.println("push(" + a + ")");
System.out.println("stack: " + st);
}
static void showpop(Stack st) {
System.out.print("pop -> ");
Integer a = (Integer) st.pop();
System.out.println(a);
System.out.println("stack: " + st);
}
public static void main(String args[]) {
Stack st = new Stack();
System.out.println("stack: " + st);
showpush(st, 42);
showpush(st, 66);
showpush(st, 99);
showpop(st);
showpop(st);
showpop(st);
try {
showpop(st);
} catch (EmptyStackException e) {
System.out.println("empty stack");
}
}
}
This would produce following result:
stack: [ ]
push(42)
stack: [42]
push(66)
stack: [42, 66]
push(99)
stack: [42, 66, 99]
pop -> 99
stack: [42, 66]
pop -> 66
stack: [42]
pop -> 42
stack: [ ]
pop -> empty stack
The Dictionary
The Dictionary class is an abs tract class that defines a data s tructure for mapping keys to values .
This is us eful in cas es where you want to be able to access data via a particular key rather than an integ er inde x.
Since the Dictionary class is abs tract, it pro vides only the fram ework for a key-m apped data s tructure rather than
a s pecific im plem entation.
Dictionary is an abs tract class that repres ents a key/ value s torage repos itory and operates m uch like Map.
Given a ke y and value , you can s tore the value in a Dictionary object. Once the value is s tored, you can retrie ve i t
by us ing its key. Thus , like a map, a d ictionary can be thought of as a lis t of ke y/ value pairs .
The abs tract m ethods defined by Dictionary are lis ted below:
SN Methods w ith Description
1
Enumeration elements( )
Returns an enum eration of the valu es contained in the dictionary.
boolean is Empty( )
Returns true if the dictionary is empty, and returns fals e if it contains at leas t one ke y.
Enumeration ke ys( )
Returns an enum eration of the ke ys contained in the dictionary.
Object remove(Object ke y)
Rem oves key and its value. Returns the val ue as sociated with key. If ke y is not in the dictionary, a
null is returned.
int size( )
Returns the num ber of entries in the dictionary.
The Dictionary class is obs olete. You s hould im plem ent the Map interface obtain ke y/ value s torage
functionality.
Map Interface
The Map interface m aps unique keys to values . A ke y is an object that you us e to retrieve a value a t a later date .
Gi ven a ke y and a value , you can s tore the value in a Map object. After the value is s tored, you can retrie ve i t
by us ing its key.
Se veral m ethods throw a NoSuchElem entException when no items exis t in the invoking m ap.
A Class Cas tException is thrown when an object is incom patible with the elements in a m ap.
A Class Cas tException is thrown when an object is incom patible with the elements in a m ap.
A NullPointerException is thrown if an attem pt is made to use a null object and null is not allowed in the m ap.
An Uns upportedOperationException is thrown when an attem pt is m ade to change an unm odifiable map.
voi d clear( )
Rem oves all key/value pairs from the invoking map.
boolea n c ontainsValue(Object v)
Returns true if the m ap contains v as a value. Otherwis e, returns false.
Set entrySet( )
Returns a Set tha t contai ns the entries in the map. The s et contains objects of type Map.Entr y.
This m ethod provides a s et-view of the in voking map.
Object get(Object k)
Returns the value ass ociated with the key k.
int hashCode( )
Returns the has h code for the invoking m ap.
boolea n is Empty( )
Returns true if the invoking m ap is em pty. Otherwis e, returns false.
Set keySet( )
Returns a Set that contains the ke ys in the invoking m ap. This m ethod provides a s et-view of the
keys in the invoking m ap.
Object put(Object k, Object v)
Puts an entry in the in voking m ap, o verwriting an y pre vious value ass ociated with the key. The ke y
10
and value are k and v, res pectivel y. Returns null if the ke y did not alread y e xis t. Otherwis e, the
previous value linked to the ke y is returned.
11
void putAll(Map m)
Puts all the entries from m into this map.
12
Object remove(Object k)
Rem oves the entry whos e key equals k.
13
int size( )
Returns the num ber of key/ value pairs in the m ap.
Collection values( )
14 Returns a collection containing the values in the m ap. This m ethod provides a collection -view of
the values in the m ap.
Example:
Map has its im plem entation in various class es like Has hMap, Following is the e xam ple to e xplain m ap
functionlaity:
import java.util.*;
public class CollectionsDemo {
public static void main(String[] args) {
Map m1 = new HashMap();
m1.put("Zara", "8");
m1.put("Mahnaz", "31");
m1.put("Ayan", "12");
m1.put("Daisy", "14");
System.out.println();
System.out.println(" Map Elements");
System.out.print("\t" + m1);
}
}
This would produce following result:
Map Elements
{Mahnaz=31, Ayan=12, Daisy=14, Zara=8}
The Hashtable
The Has htable class provides a m eans of organi zing data based on s om e user-defined key s tructure.
For exam ple, in an address lis t has h table you could s tore and s ort data bas ed on a key s uch as ZIP code rather
than on a pers on's name.
The s pecific m eaning of keys in regard to has h tables is totally dependent on the usage of the hash table and the
data it contains .
Has htable was part of the original ja va.util and is a concrete im plementation of a Dictionary.
However, Ja va 2 reengineered Has htable s o that it als o im plem ents the Map interface. Thus , Has htable is now
integrated into the collections fram ework. It is similar to HashMap, but is s ynchronized .
Like Has hMap, Has htable s tores key/value pairs in a has h table. When us ing a Hash table, you s pecify an object
that is us ed as a key, and the value that you wan t linked to that ke y. The ke y is then has hed, and the res ulting
hash code is used as the index at whi ch the value is s tored within the table.
The Has htable defines four cons tructors . The firs t vers ion is the default cons tructor:
Hashtable( )
The s econd vers ion creates a hash table that has an initial size s pecified by s ize:
Hashtable(int size)
The third vers ion creates a has h table that has an initial s ize specified by s ize and a fill ratio specified by fillRatio.
This ratio mus t be between 0.0 and 1.0, and it determ ines how full the has h table can be before it is
resized upward.
Hashtable(int size, float fillRatio)
The fourth vers ion creates a has h table that is initialized with the elem ents in m .
The capacity o f the has h table is s et to twice the number of elem ents in m . The default load factor of 0.75 is us ed.
Hashtable(Map m)
Apart from the methods defined by Map interface, Hashtable defines following methods :
SN Methods w ith Description
voi d clear( )
Res ets and em pties the has h table.
Object clone( )
Returns a duplicate of the invoki ng object.
Returns true if s ome key equal to ke y e xis ts within the hash table. Returns fals e if the key is n't
found.
Enumeration elements( )
Returns an enum eration of the valu es contained in the hash table.
boolean is Empty( )
Returns true if the hash table is empty; returns false if it contains at leas t one ke y.
Enumeration ke ys( )
Returns an enum eration of the ke ys contained in the hash table.
10
11
voi d rehash( )
Increases the s ize of the has h table and rehas hes all of its keys .
Object remove(Object ke y)
12 Rem oves key and its value . Retu rns the value ass ociated with key. If ke y is not in the hash table,
a null object is returned.
13
int size( )
Returns the num ber of entries in the hash table.
14
String t oString( )
Returns the s tring equivalent o f a has h table.
Example:
The following program illus trates s everal of the m ethods s upported by this data s tructure:
import java.util.*;
public class HashTableDemo {
public static void main(String args[]) {
// Create a hash map
Hashtable balance = new Hashtable();
Enumeration names;
String str;
double bal;
The Properties
Properties is a subclass of Hashtable. It is us ed to m aintain lis ts of values in which the key is a String and the
value is also a String.
The Properties class is us ed by many other Ja va class es . For exam ple, it is the type o f object returned b y
Sys tem .getProperties ( ) when obtaining environm ental values .
Properties is a subclass of Hashtable. It is us ed to m aintain lis ts of values in which the key is a String and the
value is also a String.
The Properties class is us ed by m any other Ja va classes . For exam ple, it is the type o f object returned b y
Sys tem .getProperties ( ) when obtaining environm ental values .
Properties defines the following ins tance variable. This variable holds a default property lis t as sociated with a
Properties object.
Properties defaults;
The Properties defines two cons tructors . The firs t vers ion creates a Properties object that has no default values :
Properties( )
The s econd creates an object that us es propDefault for its default values . In both cases , the property lis t is empty:
Properties(Properties propDefault)
Apart from the methods defined by Has htable, Properties defines following m ethods :
SN Methods w ith Description
1
Returns an enum eration of the ke ys . This includes thos e keys found in the default property lis t,
too.
Example:
The following program illus trates s everal of the m ethods s upported by this data s tructure:
import java.util.*;
public class PropDemo {
public static void main(String args[]) {
Properties capitals = new Properties();
Set states;
String str;
capitals.put("Illinois", "Springfield");
capitals.put("Missouri", "Jefferson City");
capitals.put("Washington", "Olympia");
capitals.put("California", "Sacramento");
capitals.put("Indiana", "Indianapolis");
// Show all states and capitals in hashtable.
states = capitals.keySet(); // get set-view of keys
Iterator itr = states.iterator();
while(itr.hasNext()) {
str = (String) itr.next();
System.out.println("The capital of " +
str + " is " + capitals.getProperty(str) + ".");
}
System.out.println();
// look for state not in list -- specify default
str = capitals.getProperty("Florida", "Not Found");
System.out.println("The capital of Florida is "
+ str + ".");
}
}
This would produce following result:
The
The
The
The
The
capital
capital
capital
capital
capital
of
of
of
of
of
CHAPTER
28
Java Collections
rior to Java 2 , Ja va pro vided ad hoc class es s uch as Dictionary, Vector, Stack, and Properties to s tore
and m anipulate groups of objects . Although thes e class es were quite us eful, they lacked a central,
unifying them e. Thus , the wa y th at you us ed Vector was different from the way that you use d Properties .
The collections framework was des igned to m eet s everal goals .
The fram ework had to be high-perform ance. The im plem entations for the fundamental collections (dynamic
arrays , linked lis ts , trees , and has h tables ) are highly efficient.
The framework had to allow different types of collections to work in a s im ilar manner and with a high degree
of interoperability.
Toward this end, the entire collections fram ework is des igned around a s et of s tandard interfaces .
Several s tandard im plem entations s uch as LinkedList, HashSet, and TreeSet, of thes e interfaces are provided
that you m ay us e as -is and you m ay als o im plem ent your own collection, if you choos e.
A collections framework is a unified architecture for representing and manipulating collections . All
collections fram eworks contain the following:
Interfaces: Thes e are abs tract data types that repres ent collections . Interfaces allow collections to be
m anipulated independently of the details o f their repres entation. In object-oriented languages ,
interfaces generally form a hierarchy.
Implementations i.e . Classes : Thes e are the concrete implementations of the collection interfaces .
In ess ence, they are reus able data s tructures .
Algorithms : Thes e are the m ethods that perform us eful com putations , s uch as searching and sorting,
on objects that im plem ent collection interfaces . The algorithms are s aid to be polym orphic: that is , the
s ame m ethod can be us ed on m any different im plem entations of the appropriate collection interface.
In addition to collections , the fram ework defines several m ap interfaces and classes . Maps s tore key/value pairs .
Although m aps are not collections in the proper use of the term , but the y are full y integrated with collections .
This enables you to work with groups of objects ; it is at the top of the collections hierarchy.
2
The Se t
This extends Collection to handle s ets , which m us t contain unique elem ents
The SortedSe t
This extends Set to handle sorted s ets
The Map
This m aps unique keys to values .
The Map.Entr y
This des cribes an element (a key/ value pair) in a m ap. This is an inner class of Map.
The Enumeration
This is legacy interface and defines the m ethods by which you can enum erate (obtain one at a
tim e) the elem ents in a collection of objects . This legacy interface has been s uperceded by
Iterator.
AbstractCollection
Im plem ents mos t of the Collection interface.
AbstractList
Extends Abs tractCollection and im plem ents m os t of the Lis t interface.
AbstractSequentialList
Extends Abs tractLis t for us e by a collection that us es sequential rather than random access of its
elem ents .
LinkedLis t
Im plem ents a linked lis t by e xtend ing Abs tractSequentialLis t.
Arra yLis t
Im plem ents a dynamic array by e xtending Abs tractLis t.
AbstractSet
Extends Abs tractCollection and im plem ents m os t of the Set interface.
Has hSet
Extends Abs tractSet for us e with a has h table.
LinkedHas hSet
Extends Has hSet to allow insertion-order iterations .
TreeSe t
Im plem ents a s et s tored in a tree. Extends Abs tractSet.
Vector
This im plem ents a dynam ic array. I t is s imilar to Arra yLis t, but with s ome differences .
Stack
Stack is a s ubclass of Vector tha t im plements a s tandard las t-in, firs t-out s tack.
Dictionary
Dictionary is an abs tract class that repres ents a key/ value s torage repository and operates m uch
like Map.
Has htable
Has htable was part of the original ja va.util and is a concrete im plementation of a Dictionary.
Properties
Properties is a s ubclass of Has htable. It is used to maintain lis ts of values in which the key is a
String and the value is also a String.
BitSet
A BitSe t class creates a s pecial type of arra y that holds bit values . This array can increase in s ize
as needed.
Summary:
The Java collections fram ework gi ves the programm er access to prepackaged data s tructures as well as
to algorithms for m anipulating them .
A collection is an object tha t can hold references to other objects . The collection interfaces declare the operations
that can be perform ed on each type o f collection.
The classes and interfaces of the collections fram ework are in package java.util.
CHAPTER
29
Java Generics
t would be nice i f we cou ld write a s ingle s ort m ethod that could s ort the elements in an Integer array, a
Generic Methods:
You can write a s ingle generic m ethod declaration that can be called wi th argum ents of different types . Bas ed on
the types of the argum ents passed to the generic m ethod, the com piler handles each m ethod call appropriately.
Following are the rules to define Generic Methods :
All generic method declarations have a t ype param eter s ection delimited by angle brackets (< and >) that
precedes the m ethod's return type ( < E > in the ne xt e xam ple).
Each type param eter section contains one or more type param eters s eparated by comm as . A t ype
param eter, als o known as a type variable , is an identifier that s pecifies a generic type name.
The type parameters can be us ed to declare the return type and act as placeholders for the types of the
argum ents passed to the generic m ethod, which are known as actual type arguments .
A generic m ethod's body is declared like that of an y other m ethod. Note that type param eters can repres ent
only reference types not prim itive types (like int, double and char).
Example:
Following exam ple illus trate how we can print arra y of different t ype us ing a single Generic m ethod:
public class GenericMethodTest
{
// generic method printArray
public static < E > void printArray( E[] inputArray )
{
Example:
Following exam ple illus trate how extends is us ed in a general s ense to mean either "extends " (as in classes ) or
"im plem ents " (as in interfaces ). This e xam ple is Generic m ethod to return the larges t o f three
Com parable objects :
public class MaximumTest
{
// determines the largest of three Comparable objects
public static <T extends Comparable<T>> T maximum(T x, T y, T z)
{
T max = x; // assume x is initially the largest
if ( y.compareTo( max ) > 0 ){
max = y; // y is the largest so far
}
if ( z.compareTo( max ) > 0 ){
max = z; // z is the largest now
}
return max; // returns the largest object
}
public static void main( String args[] )
{
System.out.printf( "Max of %d, %d and %d is %d\n\n",
3, 4, 5, maximum( 3, 4, 5 ) );
System.out.printf( "Maxm of %.1f,%.1f and %.1f is %.1f\n\n",
6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 ) );
System.out.printf( "Max of %s, %s and %s is %s\n","pear",
"apple", "orange", maximum( "pear", "apple", "orange" ) );
}
}
This would produce following result:
Maximum of 3, 4 and 5 is 5
Maximum of 6.6, 8.8 and 7.7 is 8.8
Maximum of pear, apple and orange is pear
Generic Classes:
A generic class declaration looks like a non-generic class declaration, except that the class nam e is followed by a
type param eter s ection.
As with generic m ethods , the type param eter s ection of a generic class can have one or m ore type param eters
s eparated by comm as . Thes e classes are known as param eterized classes or param eterized types becaus e they
accept one or m ore param eters .
Example:
Following exam ple illus trate how we can define a generic class :
public class Box<T> {
private T t;
public void add(T t) {
this.t = t;
}
public T get() {
return t;
}
public static void main(String[] args) {
Box<Integer> integerBox = new Box<Integer>();
Box<String> stringBox = new Box<String>();
integerBox.add(new Integer(10));
stringBox.add(new String("Hello World"));
CHAPTER
30
Java Serialization
ava pro vides a mechanism , called object s erialization where an object can be repres ented as a s equence of
bytes that includes the object's data as well as inform ation about the object's type and the types of data s tored in
the object.
After a s erialized object has been written into a file, it can be read from the file and des erialized that is , the type
inform ation and bytes that repres ent the object and its data can be us ed to recreate the object in m emory.
Mos t im press ive is that the entire process is JVM independent, m eaning an object can be s erialized on
one platform and des erialized on an entirel y different platform .
Class es ObjectInputStream and ObjectOutputStream are high-level s treams that contain the m ethods for
s erializing and deserializing an object.
The ObjectOutputStream class contains many write m ethods for writing various data types , but one m ethod in
particular s tands out:
public final void writeObject(Object x) throws IOException
The above m ethod s erializes an Object and s ends it to the output s tream . Similarly, the ObjectInputStream class
contains the following m ethod for des erializing an object:
public final Object readObject() throws IOException,
ClassNotFoundException
This m ethod retrieves the next Object out o f the s tream and des erializes it. The return value is Object, s o you will
need to cas t it to its appropriate data type.
To dem ons trate how s erialization works in Java, I am going to use the Employee class that we dis cussed early on
in the book. Suppos e that we ha ve the following Em ployee class , which implements the Serializable interface:
public class Employee implements java.io.Serializable
{
public String name;
public String address;
public int transient SSN;
public int number;
public void mailCheck()
{
System.out.println("Mailing a check to " + name
+ " " + address);
}
}
Notice that for a class to be s erialized s uccess fully, two conditions m us t be m et:
All of the fields in the class m us t be s erializable. If a field is not serializable, it mus t be m arked trans ient.
If you are curious to know if a Ja va Satandard Class is s erializable or not, check the docum entation for the c lass .
The tes t is simple: If the class implements java.io.Serializable, then it is serializable; otherwis e, it's not.
Serializing an Object:
The ObjectOutputStream class is us ed to s erialize an Object. The following Seriali zeDem o program ins tantiates
an Em ployee object and serializes it to a file.
When the program is done executing, a file named em ployee.s er is created. The program does not generate an y
output, bu t s tudy the code and try to determ ine what the program is doing.
Note : When s erializing an object to a file, the s tandard convention in Ja va is to give the file a .sere xtens ion.
import java.io.*;
public class SerializeDemo
{
public static void main(String [] args)
{
Employee e = new Employee();
e.name = "Reyan Ali";
e.address = "Phokka Kuan, Ambehta Peer";
e.SSN = 11122333;
e.number = 101;
try
{
FileOutputStream fileOut =
new FileOutputStream("employee.ser");
ObjectOutputStream out =
new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
}catch(IOException i)
{
i.printStackTrace();
}
}
}
Deserializing an Object:
The following Des erializeDemo program des erializes the Em ployee object created in the Seriali zeDem o program .
Study the program and try to determ ine its output:
import java.io.*;
public class DeserializeDemo
{
public static void main(String [] args)
{
Employee e = null;
try
{
FileInputStream fileIn =
new FileInputStream("employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Employee) in.readObject();
in.close();
fileIn.close();
}catch(IOException i)
{
i.printStackTrace();
return;
}catch(ClassNotFoundException c)
{
System.out.println(.Employee class not found.);
c.printStackTrace();
return;
}
System.out.println("Deserialized Employee...");
System.out.println("Name: " + e.name);
System.out.println("Address: " + e.address);
System.out.println("SSN: " + e.SSN);
System.out.println("Number: " + e.number);
}
}
This would produce following result:
Deserialized Employee...
Name: Reyan Ali
Address:Phokka Kuan, Ambehta Peer
SSN: 0
Number:101
Here are following im portant points to be noted:
The try/catch block tries to catch a ClassNotFoundException, which is declared by the readObject() m ethod.
For a JVM to be able to des eriali ze an object, it m us t be able to find the bytecode for the class . If the J VM
can't find a class during the des erialization of an object, it throws a Class NotFoundException.
Notice tha t the return value o f rea dObject() is cas t to an Em ployee reference.
The value of the SSN field was 11122333 when the object was s erialized, but because the field is trans ient,
this value was not s ent to the output s tream . The SSN field of the des erialized Em ployee object is 0.
CHAPTER
31
Java Networking
he term network programm ing refers to writing programs that e xecute across m ultiple devices
(computers ), in which the devices are all connected to each other us ing a network.
The java.ne t package o f the J2SE APIs contains a collection of classes and interfaces that provide the low -le vel
comm unication details , allowing you to write programs that focus on s olving the problem at hand.
The java.ne t package pro vides s upport for the two comm on network protocols :
TCP : TCP s tands for Transm ission Control Protocol, which allows for reliable communication between two
applications . TCP is typically us ed o ver the Internet Protocol, which is referred to as TCP/IP.
UDP : UDP s tands for Us er Datagram Protocol, a connection-less protocol that allows for packets of data to
be trans mitted between applications .
This tutorial gives good unders tanding on the following two s ubjects :
Socket Programming: This is m os t widely us ed concept in Networking and it has been explained in ver y
detail.
URL Processing: This wo uld be co vered s eparately. Click here to learn abou t URL Processing in
Java language .
Url Processing
URL s tands for Uniform Resource Locator and represents a res ource on the World Wide Web, s uch as a Web
page or FTP directory.
This s ection s hows you how to write Ja va programs that communicate with a URL. A URL can be broken down
into parts , as follows :
protocol://host:port/path?query#ref
Exam ples of protocols include HTTP, HTTPS , FTP, and File. The path is als o referred to as the filename, and the
hos t is also called the authority.
The following is a URL to a Web page whos e protocol is HTTP:
http://www.amrood.com/index.htm?language=en#j2se
Notice that this URL does not s pecify a port, in which case the default port for the protocol is us ed. With HTTP,
the default port is 80.
public URL(String protocol, Strin g host, int port, String f ile) throw s
MalformedURL Exception.
Creates a URL by putting together the gi ven parts .
public URL(String protocol, Strin g host, String f ile) throw s MalformedURL Exception
Identical to the previous cons tructor, e xcept that the default port for the gi ven protocol is us ed.
The URL class contains m any m ethods for access ing the various parts of the URL being repres ented.
Some of the m ethods in the URL class include the following:
SN
10
11
Example:
The following URLDemo program dem ons trates the various parts of a URL. A URL is entered on the command
line, and the URLDemo program outputs each part of the gi ven URL.
If you connect to a URL whos e protocol is HTTP, the openConnection() m ethod returns an
HttpURLConnection object.
If you connect to a U RL that repres ents a J AR file, the openConnection() m ethod returns a
JarURLConnection object.
etc...
The URLConnection class has m any m ethods for setting or determining information about the
connection, including the following :
SN Methods w ith Description
1
int getLastModified()
Returns the value of the las t-m odified header field.
Pass es in true to denote that the connection will be used for input. The default value is true
becaus e clients typically read from a URLConnection.
12
13
Example:
The following URLConnectionDem o program connects to a URL entered from the command line.
If the URL represents an HTTP res ource, the connection is cas t to HttpURLConnection , and the data in
the res ource is read one line at a time.
// File Name : URLConnDemo.java
import java.net.*;
import java.io.*;
public class URLConnDemo
{
public static void main(String [] args)
{
try
{
URL url = new URL(args[0]);
URLConnection urlConnection = url.openConnection();
HttpURLConnection connection = null;
if(urlConnection instanceof HttpURLConnection)
{
connection = (HttpURLConnection) urlConnection;
}
else
{
System.out.println("Please enter an HTTP URL.");
return;
}
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String urlString = "";
String current;
while((current = in.readLine()) != null)
{
urlString += current;
}
System.out.println(urlString);
}catch(IOException e)
{
e.printStackTrace();
}
}
}
A s am ple run of the thid program would produce following res ult:
$ java URLConnDemo http://www.amrood.com
.....a complete HTML content of home page of amrood.com.....
Socket Programming:
Sockets provide the communication m echanism between two computers us ing TCP. A clien t program creates a
s ocket on its end of the communication and attempts to connect that s ocket to a s erver.
When the connection is m ade, the s erver creates a s ocket object on its end of the communication. The client and
s erver can now communicate by writing to and reading from the s ocket.
The java.net.Socke t class represents a socket, and the java.net.ServerSocket class provides a m echanism for the
s erver program to lis ten for clients and es tablish connections with them .
The following s teps occur when es tablis hing a TCP connection between two com puters using s ockets :
The s erver ins tantiates a ServerSocket object, denoting which port num ber comm unication is to occur on.
The server invokes the accept() m ethod of the ServerSocket class . This m ethod waits until a client connects
to the s erver on the given port.
After the s erver is waiting, a clien t ins tantiates a Socket object, s pecifying the s erver nam e and port number
to connect to.
The cons tructor of the Socket cl ass attempts to connect the client to the s pecified s erver and port num ber. If
comm unication is es tablis hed, the client n ow has a Socket object capable of comm unicating with the s erver.
On the server side, the accept() m ethod returns a reference to a new s ocket on the serve r that is connected
to the client's s ocket.
After the connections are es tablis hed, comm unication can occur us ing I/O s treams . Each s ocket has both
an OutputStream and an InputStream . The client's OutputStream is connected to the s erver's InputStream , and
the client's InputStream is connected to the s erver's OutputStream .
TCP is a twoway comm unication protocol, so data can be s ent across both s treams at the s ame tim e. There are
following us efull classes providing com plete s et of methods to im plem ent s ockets .
public ServerSocket(int port, int backlog, Inet Address address) throw s IOException
Sim ilar to the previous cons tructor, the InetAddress param eter s pecifies the local IP addr ess to
bind to. The InetAddress is us ed for s ervers that m ay ha ve m ultiple IP address es , allowing the
s erver to s pecify which of its IP address es to accept client reques ts on
If the Ser verSocke t cons tructor does not throw an e xception, it m eans that your application has
s uccess fully bound to the s pecified port and is ready for client reques ts .
Here are som e of the comm on m ethods of the ServerSocket class :
SN Methods w ith Description
1
Waits for an incoming client. This method blocks until either a client connects to the s erver on the
s pecified port or the s ocket tim es out, ass uming that the tim e-out value has been s et us ing the
s etSoTim eout() method. Otherwise, this m ethod blocks indefinitely
Binds the socket to the s pecified server and port in the SocketAddress object. Us e this m ethod if
you ins tantiated the ServerSocke t us ing the no-argum ent cons tructor.
When the ServerSocke t in vokes 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 e xis ts between the client and s erver, and comm unication can begin.
public Socket(String host, int port, InetAddress loc alAddress, int localPort) throw s
IOException .
Connects to the specified hos t and port, creating a s ocket on the local hos t at the s pecified
address and port.
public Socket(InetAddress host, int port, InetAddress localAddress, int localPort) throw s
IOException .
This m ethod is identical to the previous cons tructor, except that the hos t is denoted by an
InetAddress object ins tead of a String
public Socket()
Creates an unconnected s ocket. Use the connect() m ethod to connect this s ocket to a s erver.
When the Socket cons tructor returns , it does not sim ply ins tantiate a Socket object bu t i t actuall y a ttem pts
to connect to the s pecified s erver and port.
Some m ethods of interes t in the Socket class are lis ted here. Notice that both the client and server ha ve a Socke t
object, s o these methods can be invoked b y both the client and s erver.
SN Methods w ith Description
public void connect(SocketAddress host, int timeout) throw s IOException
1
This m ethod connects the s ocket to the s pecified hos t. This m ethod is needed only when you
ins tantiated the Socket using the no-argum ent cons tructor.
String toString()
Converts this IP address to a String.
+ client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out =
new DataOutputStream(outToServer);
out.writeUTF("Hello from "
+ client.getLocalSocketAddress());
InputStream inFromServer = client.getInputStream();
DataInputStream in =
new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
client.close();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
{
System.out.println("Socket timed out!");
break;
}catch(IOException e)
{
e.printStackTrace();
break;
}
}
}
public static void main(String [] args)
{
int port = Integer.parseInt(args[0]);
try
{
Thread t = new GreetingServer(port);
t.start();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
Com pile client and s erver and then s tart s erver as follows :
$ java GreetingServer 6066
Waiting for client on port 6066...
Check client program as follows :
$ java GreetingClient localhost 6066
Connecting to localhost on port 6066
Just connected to localhost/127.0.0.1:6066
Server says Thank you for connecting to /127.0.0.1:6066
Goodbye!
CHAPTER
32
Java Sending Email
o s end an email us ing your Java Application is s im ple enough but to s tart with you s hould have Ja vaMail
API and Ja va Activation Framew ork (J AF) ins talled on your m achine.
You can download lates t vers ion of Ja va Mail (Vers ion 1.2) from Java's s tandard website.
You can download lates t vers ion of JAF (Vers ion 1.1.1) from Java's s tandard website.
Download and unzip thes e files , in the newl y created top le vel directories you will find a num ber of jar files for both
the applications . You need to add mail.jar and activation.jar files in your CL ASSP ATH .
java.util.*;
javax.mail.*;
javax.mail.internet.*;
javax.activation.*;
type : This would be s et to TO, CC or BCC. Here CC repres ents Carbon Copy and BCC repres ents Black
Carbon Copy. Exam ple Message.RecipientType.TO
addresses: This is the array of em ail ID. You would need to us e InternetAddress () m ethod while s pecifying
em ail IDs
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendHTMLEmail
{
public static void main(String [] args)
{
// Recipient's email ID needs to be mentioned.
String to = "abcd@gmail.com";
// Sender's email ID needs to be mentioned
String from = "web@gmail.com";
// Assuming you are sending email from localhost
String host = "localhost";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
try{
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Set Subject: header field
message.setSubject("This is the Subject Line!");
// Send the actual HTML message, as big as you like
message.setContent("<h1>This is actual message</h1>",
"text/html" );
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
Com pile and run this program to s end an HTML em ail:
$ java SendHTMLEmail
Sent message successfully....
java.util.*;
javax.mail.*;
javax.mail.internet.*;
javax.activation.*;
CHAPTER
33
Java Multithreading
ava pro vides built-in s upport for m ultithreaded programming. A m ultithreaded program contains two or m ore
parts that can run concurrentl y. Ea ch part of s uch a program is called a thread, and each thread defines
a s eparate path of execution .
A m ultithreading is a specialized form of multitas king. Multitas king threads require less overhead than multitas king
process es .
I need to define another term related to threads : process: A process cons is ts of the m emory s pace allocated by
the operating s ys tem that can contain one or m ore threads . A thread cannot e xis t on its own; it m us t be a part of a
process . A process rem ains running until all of the non-daemon threads are done executing.
Multithreading enables you to write very efficien t programs that m ake m axim um us e of the CPU, because idle
tim e can be kept to a m inim um .
New : A new thread begins its life cycle in the new s tate. It rem ains in this s tate until the program s tarts the
thread. It is als o referred to as a born thread.
Runnable : After a newl y born thread is s tarted, the thread becom es runnable. A thread in this s tate
is cons idered to be executing its tas k.
W aiting: Som etim es a thread trans itions to the waiting s tate while the thread waits for another thread
to perform a tas k.A thread transitions back to the runnable s tate only when another thread s ignals the
waiting
thread to continue executing .
Timed w aiting: A runnable thread can enter the tim ed waiting s tate for a s pecified interval of tim e. A thread
in this s tate trans itions back to the runnable s tate when that tim e interval e xpires or when the even t i t
is
waiting for occurs .
Terminated: A runnable thread enters the term inated s tate when it com pletes its tas k or otherwise
term inates .
Thread Priorities:
Ever y Ja va thread has a priority that helps the operating s ys tem determ ine the order in which threads
are s cheduled.
Java priorities are in the range between MIN_PRIORIT Y (a cons tant of 1) and MAX_PRIORIT Y (a cons tant of
10). By default, e ver y thread is given priority NOR M_PRIOR IT Y (a cons tant of 5).
Threads with higher priority are m ore im portant to a program and s hould be allocated process or tim e
before lower-priority threads . However, thread priorities cannot guarantee the order in which threads execute
and very m uch platform dependent.
Creating a Thread:
Java defines two ways in which this can be accomplis hed:
Example:
Here is an exam ple that creates a new thread and s tarts it running:
// Create a new thread.
class NewThread implements Runnable {
Thread t;
NewThread() {
// Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for the second thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
// Let the thread sleep for a while.
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
public class ThreadDemo {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
This would produce following result:
Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.
Example:
Here is the preceding program rewritten to extend Thread:
// Create a second thread by extending Thread
class NewThread extends Thread {
NewThread() {
// Create a new, second thread super("Demo
Thread"); System.out.println("Child thread:
" + this); start(); // Start the thread
}
// This is the entry point for the second thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
// Let the thread sleep for a while.
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
public class ExtendThread {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
This would produce following result:
Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.
Thread Methods:
Following is the lis t of important m edthods available in the Thread class .
SN Methods w ith Description
1
until the second thread term inates or the specified number of millis econds pass es .
7
The previous m ethods are invoked on a particular Thread object. The following m ethods in the Thread c lass are
s tatic. Invoking one o f the s tatic m ethods performs the operation on the currently running thread
SN Methods w ith Description
1
Example:
The following ThreadClass Demo program dem ons trates some of these methods of the Thread class :
// File Name : DisplayMessage.java
// Create a thread to implement Runnable
public class DisplayMessage implements Runnable
{
private String message;
public DisplayMessage(String message)
{
this.message = message;
}
public void run()
{
while(true)
{
System.out.println(message);
}
}
}
// File Name : GuessANumber.java
// Create a thread to extentd Thread
public class GuessANumber extends Thread
{
private int number;
public GuessANumber(int number)
{
this.number = number;
}
Hello
Hello
Hello
Hello
Hello
Hello
Thread-2 guesses 27
Hello
** Correct! Thread-2 in 102 guesses.**
Hello
Starting thread4...
Hello
Hello
..........remaining result produced.
Thread Synchronization
When two or m ore threads need access to a s hared res ource, they need s ome way to ensure that the resource
will be used by only one thread a t a tim e.
The process by which this s ynchroni zation is achieved is called thread synchronization.
The s ynchronized ke yword in Ja va creates a block of code referred to as a critical section. Every Ja va 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 corres ponding object's lock.
This is the general form of the s ynchroni zed s tatement:
synchronized(object) {
// statements to be synchronized
}
Here, object is a reference to the object b eing s ynchroni zed. A s ynchroni zed block ens ures that a call to a m ethod
that is a mem ber of object occurs onl y after the current thread has s uccess fully entered object's m onitor.
Here is an exam ple, us ing a s ynchroni zed block within the run( ) method:
// File Name : Callme.java
// This program uses a synchronized block.
class Callme {
void call(String msg) {
System.out.print("[" + msg);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Interrupted");
}
System.out.println("]");
}
}
// File Name : Caller.java
class Caller implements Runnable {
String msg;
Callme target;
Thread t;
public Caller(Callme targ, String s) {
target = targ;
msg = s;
t = new Thread(this);
t.start();
}
// synchronize calls to call()
public void run() {
synchronized(target) { // synchronized block
target.call(msg);
}
}
}
// File Name : Synch.java
public class Synch {
public static void main(String args[]) {
Callme target = new Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");
// wait for threads to end
try {
ob1.t.join();
ob2.t.join();
ob3.t.join();
} catch(InterruptedException e) {
System.out.println("Interrupted");
}
}
}
This would produce following result:
[Hello]
[World]
[Synchronized]
Interthread Communication
Cons ider the classic queuing problem , where one thread is producing s ome data and another is cons uming it. To
m ake the problem m ore interes ting, s uppose that the producer has to wait until the cons umer is finis hed before it
generates m ore data.
In a polling s ys tem , the cons um er would was te m any CPU cycles while it waited for the producer to produc
e. Once the producer was finis hed, it would s tart polling, was ting m ore CPU cycles waiting for the
cons um er to finis h, and s o on. Clearl y, this s ituation is undes irable.
To avoid polling , Ja va includes an elegant interprocess comm unication mechanism via th e following m ethods :
w ait( ): This m ethod tells the calling thread to give up the m onitor and go to s leep until s om e other thread
enters the s ame monitor and calls notify( ).
notify( ) : This m ethod wakes up the firs t thread that called wait( ) on the s am e object.
notifyAll( ) : This m ethod wakes up all the threads that called wait( ) on the s am e object.c The highes t priority
thread will run firs t.
These m ethods are im plem ented as final methods in Object, so all classes have them . All three methods can be
called only from within a synchronize d conte xt.
These m ethods are declared within Object. Various forms of wait( ) exis t that allow you to s pecify a period of tim e
to wait.
Example:
The following s am ple program cons is ts of four class es : Q, the queue that you're trying to s ynchroni ze ; Producer,
the threaded object that is producing queue entries ; Consum er, the threaded object that is consum ing
queue entries ; and PC, the tin y clas s that creates the s ingle Q, Producer, and Cons umer.
The proper way to write this program in Java is to use wait( ) and notify( ) to s ignal in both directions , as shown
here:
class Q {
int n;
boolean valueSet = false;
synchronized int get() {
if(!valueSet)
try {
wait();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Got: " + n);
valueSet = false;
notify();
return n;
}
synchronized void put(int n) {
if(valueSet)
try {
wait();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
this.n = n; valueSet = true;
System.out.println("Put: " + n);
notify();
}
}
class Producer implements Runnable {
Q q;
Producer(Q q) {
this.q = q;
new Thread(this, "Producer").start();
}
public void run() {
int i = 0;
while(true) {
q.put(i++);
}
}
}
class Consumer implements Runnable {
Q q;
Consumer(Q q) {
this.q = q;
new Thread(this, "Consumer").start();
}
public void run() {
while(true) {
q.get();
}
}
}
public class PCFixed {
public static void main(String args[]) {
Q q = new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to stop.");
}
}
Ins ide get( ), wait( ) is called. This caus es its execution to s us pend until the Producer notifies you that s om e data
is ready.
When this happens , execution ins ide get( ) resum es . After the data has been obtained, get( ) calls notify( ). This
tells Producer that it is okay to p ut m ore data in the queue.
Ins ide put( ), wait( ) s us pends execution until the Cons um er has removed the item from the queue.
When execution res um es , the next item of data is put in the queue, and notify( ) is called. This tells the
Cons umer that it s hould now remove it.
Here is some output from this program , which s hows the clean s ynchronous behavior:
Put:
Got:
Put:
Got:
Put:
Got:
Put:
Got:
Put:
Got:
1
1
2
2
3
3
4
4
5
5
Thread Deadlock
A s pecial type o f error tha t you need to a void that relates s pecifically to m ultitas king is deadlock, which occurs
when two threads have a circular dependency on a pair of s ynchroni zed objects .
For exam ple, s uppos e one thread enters the m onitor on object X and another thread enters the m onitor on object
Y. If the thread in X tries to call any s ynchroni zed m ethod on Y, i t will block as expected. Howe ver, if the thread in
Y, in turn , tries to call any s ynchroni zed m ethod on X, the thread waits fore ver, becaus e to access X, it would
have to release its own lock on Y s o that the firs t thread could com plete.
Example:
To unders tand deadlock fully, i t is us eful to s ee it in action. The ne xt e xam ple creates two class es , A and B, with
m ethods foo( ) and bar( ), res pectivel y, which paus e briefly before trying to call a m ethod in the other class .
The main class , nam ed Deadlock, creates an A and a B ins tance, and then s tarts a s econd thread to s et up the
deadlock condition. The foo( ) and bar( ) m ethods use sleep( ) as a way to force the deadlock condition to occur.
class A {
synchronized void foo(B b) {
String name = Thread.currentThread().getName();
System.out.println(name + " entered A.foo");
try {
Thread.sleep(1000);
} catch(Exception e) {
System.out.println("A Interrupted");
}
System.out.println(name + " trying to call B.last()");
b.last();
}
synchronized void last() {
System.out.println("Inside A.last");
}
}
class B {
synchronized void bar(A a) {
String name = Thread.currentThread().getName();
System.out.println(name + " entered B.bar");
try {
Thread.sleep(1000);
} catch(Exception e) {
System.out.println("B Interrupted");
}
System.out.println(name + " trying to call A.last()");
a.last();
}
synchronized void last() {
System.out.println("Inside A.last");
}
}
public class Deadlock implements Runnable {
A a = new A();
B b = new B();
Deadlock() {
Thread.currentThread().setName("MainThread");
Thread t = new Thread(this, "RacingThread");
t.start();
a.foo(b); // get lock on a in this thread.
System.out.println("Back in main thread");
}
public void run() {
b.bar(a); // get lock on b in other thread.
System.out.println("Back in other thread");
}
public static void main(String args[]) {
new Deadlock();
}
}
Here is some output from this program :
MainThread entered A.foo
RacingThread entered B.bar
MainThread trying to call B.last()
RacingThread trying to call A.last()
Becaus e 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 press ing CTRL-BREAK on a PC .
You will s ee that RacingThread owns the m onitor on b, while it is waiting for the monitor on a. At the s am e tim e,
MainThread owns a and is waiting to get b. This program will never com plete.
As this e xam ple illus trates , if yo ur m ultithreaded program locks up occas ionally, deadlock is one o f the
firs t conditions that you s hould check for.
Ordering Locks:
Acom m on threading trick to avoid the deadlock is to order the locks . By ordering the locks , i t g i ves threads
a s pecific order to obtain multiple locks .
Deadlock Example:
Following is the depiction of a dead lock:
// File Name ThreadSafeBankAccount.java
public class ThreadSafeBankAccount
{
private double balance;
private int number;
public ThreadSafeBankAccount(int num, double initialBalance)
{
balance = initialBalance;
number = num;
}
public int getNumber()
{
return number;
}
public double getBalance()
{
return balance;
}
public void deposit(double amount)
{
synchronized(this)
{
double prevBalance = balance;
try
{
Thread.sleep(4000);
}catch(InterruptedException e)
{}
balance = prevBalance + amount;
}
}
public void withdraw(double amount)
{
synchronized(this)
{
double prevBalance = balance;
try
{
Thread.sleep(4000);
}catch(InterruptedException e)
{}
balance = prevBalance - amount;
}
}
}
The problem with the LazyTeller class is that it does not cons ider the poss ibility of a race condition , a common
occurrence in multithreaded programming.
After the two threads are s tarted, teller1 grabs the checking lock and teller2 grabs the s avings lock. When teller1
tries to obtain the s avings lock, it is no t a vailable. Therefore, teller1 blocks until the savings lock
becomes available. When the tel ler1 thread blocks , teller1 s till has the checking lock and does not let it go.
Sim ilarly, teller2 is waiting for the checking lock, so teller2 blocks but does not let go o f the s avings lock. This
leads to one result: deadlock!
}
}
This would remove deadlock problem and would produce following res ult:
Creating two bank accounts...
Creating two teller threads...
Starting both threads...
Transferring from 101 to 102
Transferring from 102 to 101
Withdrawing from 101
Depositing into 102
Withdrawing from 102
Depositing into 101
Example:
// Suspending and resuming a thread for Java 2
class NewThread implements Runnable {
String name; // name of thread
Thread t;
boolean suspendFlag;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
suspendFlag = false;
t.start(); // Start the thread
}
// This is the entry point for thread.
public void run() {
try {
for(int i = 15; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(200);
synchronized(this) {
while(suspendFlag) {
wait();
}
}
}
} catch (InterruptedException e) {
System.out.println(name + " interrupted.");
}
System.out.println(name + " exiting.");
}
void mysuspend() {
suspendFlag = true;
}
synchronized void myresume() {
suspendFlag = false;
notify();
}
}
public class SuspendResume {
public static void main(String args[]) {
NewThread ob1 = new NewThread("One") ;
NewThread ob2 = new NewThread("Two") ;
try {
Thread.sleep(1000); ob1.mysuspend();
System.out.println("Suspending thread One");
Thread.sleep(1000);
ob1.myresume(); System.out.println("Resuming
thread One"); ob2.mysuspend();
System.out.println("Suspending thread Two");
Thread.sleep(1000);
ob2.myresume();
System.out.println("Resuming thread Two");
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
// wait for threads to finish
try {
System.out.println("Waiting for threads to finish.");
ob1.t.join();
ob2.t.join();
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}
Here is the output produced by the ab o ve program :
New thread: Thread[One,5,main]
One: 15
New thread: Thread[Two,5,main]
Two: 15
One: 14
Two: 14
One: 13
Two: 13
One: 12
Two: 12
One: 11
Two: 11
Using Multithreading:
The key to utili zing m ultithreading s upport effecti vel y is to think concurrently rather than serially. For e xam ple,
when you ha ve two s ubs ys tems within a program that can execute concurrentl y, m ake them individual threads .
With the careful us e of m ultithreading, you can create very efficient programs . A word of caution is in
order, however: If you create too m any threads , you can actuall y degrade the performance of your program
rather than enhance it.
Rem em ber, som e overhead is associated with context s witching. If you create too m any threads , m ore CPU tim e
will be s pent changing contexts than e xecuting your program !
CHAPTER
34
Java Applet Basics
n applet is a Ja va program tha t runs in a Web brows er. An applet can be a full y functional Ja va
application because it has the entire Java API at its dispos al.
There are s om e im portant differences between an applet and a s tandalone Java applicatio n, including
the following:
A m ain() m ethod is not invoked on an applet, and an applet class will not define m ain().
When a us er views an HTML page that contains an applet, the code for the applet is downloaded to the
us er's m achine.
A J VM is required to view an applet. The JVM can be either a plug -in of the Web brows er or a separate
runtim e environm ent.
The JVM on the us er's machine creates an ins tance of the applet class and invokes various m ethods during
the applet's lifetim e.
Applets have s trict s ecurity rules that are enforced by the Web browser. The s ecurity of an applet is often
referred to as s andbox s ecurity, com paring the applet to a child pla ying in a s andbox with various rules that
m us t be followed.
Other class es that the applet nee ds can be downloaded in a s ingle Java Archi ve (J AR) file .
init: This method is i ntended for wha tever i ni tiali zati on is needed for your a ppl et. I t i s ca ll ed a fter the
pa ra m ta gs i nsi de the a ppl et ta g ha ve been proces sed.
start: This method is a utomati call y call ed after the brows er calls the i ni t method. I t is al s o call ed
when ever the us er returns to the pa ge c onta i ni ng the a ppl et a fter ha vi ng gone off to oth er pa ges .
stop: This method is a utomati cal l y call ed when the us er mov es off th e pa ge on whi ch th e a ppl et s its . It
c a n, therefor e, b e c a lled repeate dl y i n the s a me a pplet.
dest roy: This method is onl y c all ed when the brows er s huts down norma ll y. Bec a us e a ppl ets a re mea nt to
li ve on a n HTML pa ge, you s houl d not normal l y l eave resourc es behi nd a fter a us er l ea ves the pa ge that
c onta i ns the a pplet.
paint: I nvoked immedia tel y a fter the sta rt() metho d, a nd als o a ny ti me the a ppl et needs to repai nt its elf i
n the brows er. Th e pai nt() method is actuall y i nheri ted fr om the j a va .awt.
java.applet.Applet.
java.awt.Graphics .
Without thos e import s tatem ents , the Ja va compiler would not recogni ze the class es Applet and Graphics , which
the applet class refers to.
Get the network location o f the H TML file that contains the applet
Fetch an image
Additionall y, the Apple t class provides an interface by which the viewe r or brows er obtains information about the
applet and controls the applet's execution. The viewer may:
reques t inform ation about the auth or, vers ion and copyright of the applet
The Apple t class provides default implementations of each of thes e methods . Thos e im plementations m ay
be overridden as necess ary.
The "Hello, World" apple t is com plete as it s tands . The only m ethod overridden is the paint method.
Invoking an Applet:
An apple t m ay be in voked b y em bedding directi ves in an HTML file and viewing the file through an apple t viewer
or Java-enabled browser.
The <applet> tag is the bas is for em bedding an applet in an HTML file. Below is an exam ple that in vokes the
"Hello, World" applet:
<html>
<title>The Hello, World Applet</title>
<hr>
<applet code="HelloWorldApplet.class" width= "3 20" he ight= "120">
If your browser was Java-enabled, a "Hello, World"
message would appear here.
</applet>
<hr>
</html>
Bas ed on the above exam ples , here is the live applet e xample:
Note : You can refer to
Applet Examp le .
HTML Applet Tag to unders tand m ore about calling applet from
HTML .
The code attribute of the <applet> tag is required. It s pecifies the Applet class to ru n. Width and height are als o
required to s pecify the initial s ize of the panel in which an applet runs . The applet directi ve m us t be clos ed with a
</applet> tag.
If an apple t takes parameters , values m ay be passed for the param eters by adding <param > tags between
<applet> and </applet>. The brows er ignores text and other tags between the applet tags .
Non-Java-enabled brows ers do not process <applet> and </applet>. Therefore, an ything tha t appears between
the tags , not related to the applet, is vis ible in non-Ja va-enabled brows ers .
The viewer or brows er looks for the com piled Java code at the location of the document. To s pecify otherwis e,
use the codebas e attribute of the <applet> tag as shown:
<applet codebase="http://amrood.com/applets"
code="HelloWorldApplet.class" width="320" height="120">
If an apple t resides in a package other than the default, the holding package mus t be s pecified in the
code attribute us ing the period character (.) to s eparate package/class components . For exam ple:
The applet calls pars eSquareSize() to pars e the s quareSize parameter. pars eSquareSize() calls the
library m ethod Integer.parseInt(), which pars es a s tring and returns an integer. Integer.parseInt() throws an
exception whene ver its argum ent is invalid.
Therefore, pars eSquareSize() catches e xceptions , rather than allowing the applet to fail on bad input.
The applet calls pars eColor() to pars e the color parameter into a Color value. pars eColor() does a s eries of s tring
comparis ons to m atch the param eter value to the nam e of a predefined color. You need to im plem ent
these methods to make this applet works .
Make an HTML page with the appropriate tag to load the applet code.
Suppl y a s ubclass of the JAppl et clas s . Make this class public. Otherwis e, the applet canno t be loaded .
Eliminate the m ain m ethod in the application. Do not cons truct a fram e window for the application. Your
application will be dis played ins ide the brows er.
Mo ve an y initiali zation code from the fram e window cons tructor to the init method of the applet. You don't
need to explicitl y cons truct the applet object.the brows er ins tantiates it for you and calls the init m ethod.
Rem ove the call to s etSize ; for applets , s izing is done with the width and height parameters in the HTML
file.
Rem ove the call to s etDefaultClos eOperation. An applet cannot be closed; it term inates when the browser
exits .
If the application calls s etTitle, elim inate the call to the m ethod. Applets cannot ha ve title bars . (You can , o f
cours e, title the web page itself, using the HTML title tag.)
Event Handling:
Applets inherit a group of e vent-handling m ethods from the Container class . The Container class defines s everal
m ethods , s uch as process KeyEvent and process Mous eEvent, for handling particula r types of e vents , and then
one catch-all method called process Event.
Inorder to react an e vent, an apple t mus t o verride the appropriate e vent-s pecific m ethod.
import
import
import
import
java.awt.event.MouseListener;
java.awt.event.MouseEvent;
java.applet.Applet;
java.awt.Graphics;
}
public void mouseClicked(MouseEvent event) {
addItem("mouse clicked! ");
}
}
Now let us call this applet as follows :
<html>
<title>Event Handling</title>
<hr>
<applet code="ExampleEventHandling.class"
width="300" height="300">
</applet>
<hr>
</html>
Initially the apple t will dis play "ini tiali zing the applet. Starting the applet." Then once you click ins ide the rectangle
"m ouse clicked" will be dis played as well.
Bas ed on the above exam ples , here is the live applet e xample:
Applet Examp le .
Displaying Images:
An apple t can display im ages of the form at GIF, JPEG, B MP, and others . To dis play an im age within the applet,
you us e the drawIm age() m ethod found in the java.awt.Graphics class .
Following is the example s howing all the s teps to s how im ages :
import java.applet.*;
import java.awt.*;
import java.net.*;
public class ImageDemo extends Applet
{
private Image image;
private AppletContext context;
public void init()
{
context = this.getAppletContext();
String imageURL = this.getParameter("image");
if(imageURL == null)
{
imageURL = "java.jpg";
}
try
{
URL url = new URL(this.getDocumentBase(), imageURL);
image = context.getImage(url);
}catch(MalformedURLException e)
{
e.printStackTrace();
// Display in browser status bar
context.showStatus("Could not load image!");
}
}
public void paint(Graphics g)
{
context.showStatus("Displaying image");
Applet Examp le .
Playing Audio:
An apple t can pla y an audio file repres ented by the AudioClip interface in the ja va.applet package . The AudioClip
interface has three m ethods , including:
public void pla y() : Pla ys the audio clip one time, from the beginning.
public void loop() : Causes the audio clip to replay continuall y.
public void stop() : Stops playing the audio clip.
To obtain an Audi oClip object, you m us t invoke the getAudioClip() m ethod of the Apple t clas s . The getAudioClip()
m ethod returns imm ediately, whether or not the URL res olves to an actual audio file . The audio file is
not downloaded until an attempt is m ade to play the audio clip.
Following is the example s howing all the s teps to play an audio:
import java.applet.*;
import java.awt.*;
import java.net.*;
public class AudioDemo extends Applet
{
private AudioClip clip;
private AppletContext context;
public void init()
{
context = this.getAppletContext();
String audioURL = this.getParameter("audio");
if(audioURL == null)
{
audioURL = "default.au";
}
try
{
URL url = new URL(this.getDocumentBase(), audioURL);
clip = context.getAudioClip(url);
}catch(MalformedURLException e)
{
e.printStackTrace();
context.showStatus("Could not load audio file!");
}
}
public void start()
{
if(clip != null)
{
clip.loop();
}
}
public void stop()
{
if(clip != null)
{
clip.stop();
}
}
}
Now let us call this applet as follows :
<html>
<title>The ImageDemo applet</title>
<hr>
<applet code="ImageDemo.class" width="0" height="0">
<param name="audio" value="test.wav" >
</applet>
<hr>
</html>
You can us e your tes t.wav a t your PC to tes t the abo ve e xam ple.
CHAPTER
Java Documentation
35
ava s upports three types o f comm ents . The firs t two are the // and the /* */. The third t ype is called a
docum entation comm ent. It begins with the character s equence /** and it ends with */.
Docum entation comm ents allow you to em bed inform ation about your program into the program itself. You can
then use the javadoc utility program to e xtract the inform ation and put it into an HTML file.
Docum entation comm ents make it convenie nt to document your programs .
Documentation Comment:
After the beginning /** , the firs t li ne or lines become the main des cription of your class , variable , or m ethod.
After that, you can include one or m ore of the various @ tags . Each @ tag mus t s tart at the beginning o f a new
line or follow an as teris k (*) that is at the s tart of a line.
Multiple tags of the sam e type should be grouped together. For e xam ple, if you ha ve three @s ee tags , put them
one after the other.
Here is an exam ple of a docum entation comment for a class :
/**
* This class draws a bar chart.
* @author Zara Ali
* @version 1.2
*/
Example:
Following is a s am ple program that us es documentation comm ents . Notice the way each comment im mediately
precedes the item that it des cribes .
After being process ed by j a vadoc, the docum entation about the SquareNum class will be found in
SquareNum .html.
import java.io.*;
/**
* This class demonstrates documentation comments.
* @author Ayan Amhed
* @version 1.2
*/
public class SquareNum {
/**
* This method returns the square of num.
* This is a multiline description. You can use
* as many lines as you like.
* @param num The value to be squared.
* @return num squared.
*/
public double square(double num) {
return num * num;
}
/**
* This method inputs a number from the user.
* @return The value input as a double.
* @exception IOException On input error.
* @see IOException
*/
public double getNumber() throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader inData = new BufferedReader(isr);
String str;
str = inData.readLine();
return (new Double(str)).doubleValue();
}
/**
* This method demonstrates square().
* @param args Unused.
* @return Nothing.
* @exception IOException On input error.
* @see IOException
*/
public static void main(String args[]) throws IOException
{
SquareNum ob = new SquareNum();
double val;
System.out.println("Enter value to be squared: ");
val = ob.getNumber(); val = ob.square(val);
System.out.println("Squared value is " + val);
}
}
Now process above SquareNum .java file using javadoc utility as follows :
$ javadoc SquareNum.java
Loading source file SquareNum.java...
Constructing Javadoc information...
Standard Doclet version 1.5.0_13
Building tree for all the packages and classes...
Generating SquareNum.html...
SquareNum.java:39: warning - @return tag cannot be used\
in method with void return type.
Generating package-frame.html...
Generating package-summary.html...
Generating package-tree.html...
Generating constant-values.html...
Building index for all the packages and classes...
Generating overview-tree.html...
Generating index-all.html...
Generating deprecated-list.html...
Building index for all classes...
Generating allclasses-frame.html...
Generating
Generating
Generating
Generating
1 warning
$
allclasses-noframe.html...
index.html...
help-doc.html...
stylesheet.css...
You can check all the generated docum entation here: SquareNum .
CHAPTER
36
Java Library Classes
his tutorial would cover package ja va.lang which pro vides class es that are fundam ental to the des ign of
the Java programm ing language. The m os t important class es are Object, which is the root of the clas s hierarchy,
and Class , ins tances of which repres ent classes at run time.
Here is the lis t of class es of ackage java.lang. Thes e class es are very im portant to know for a Ja va programmer.
Click a class link to know m ore detail about that class . For a further drill, you can refer s tandard Java
docum entation.
SN
Boolean
Boolean
Byte
The Byte clas s wraps a value of prim itive type b yte in an object.
Character
The Character class wraps a value of the prim itive type char in an object.
Class
Ins tances of the class Class repres ent classes and interfaces in a running Java application.
Class Loader
A class loader is an object that is res pons ible for loading class es .
Com piler
The Com piler class is provided to s upport Ja va-to-nati ve-code com pilers and related s ervices .
Double
The Double class wraps a value of the prim itive type double in an object.
Float
The Float class wraps a value of prim itive type float in an object.
Integer
The Integer class wraps a value of the primitive t ype int in an object.
10
Long
The Long class wraps a value of the prim itive type long in an object.
11
Math
The class Math contains m ethods for perform ing basic num eric operations s uch as the elem entary
exponential, logarithm , s quare root, and trigonom etric functions .
12
Num ber
The abs tract class Num ber is the s uperclass of classes BigDecim al, BigInteger, Byte , Double , Fl oat,
Integer, Long , and Short.
13
Object
Class Object is the root of the class hierarchy.
14
Package
Package objects contain vers ion inform ation about the implementation and specification of a Java package .
Process
15
The Runtim e.exec m ethods create a native process and return an ins tance of a s ubclass of Process that
can be us ed to control the process and obtain inform ation about it.
16
Runtim e
Ever y Ja va application has a s ingle ins tance of class Runtim e that allows the application to interface with
the environment in which the application is running.
17
18
SecurityManager
The s ecurity m anager is a class that allows applications to im plement a security policy.
19
Short
The Short class wraps a value of prim itive type s hort in an object.
20
StackTraceElem ent
An elem ent in a s tack trace, as returned b y Throwable.getStackTrace().
21
StrictMath
The class StrictMath contains m ethods for performing bas ic numeric operations such as the elementary
exponential, logarithm , s quare root, and trigonom etric functions .
22
String
The String class represents character s trings .
23
StringBuffer
A s tring buffer im plem ents a m utable s equence of characters .
24
Sys tem
The Sys tem class contains s everal us eful class fields and m ethods .
25
Thread
A thread is a thread of e xecution in a program .
26
ThreadGroup
A thread group represents a s et of thre ads .
27
ThreadLocal
This class provides thread-local variables .
28
Throwable
The Throwable class is the s uperclass of all errors and exceptions in the Java language .
29
Void
The Void class is an unins tantiable placeholder class to hold a reference to the Class object repres enting
the Java ke yword void .