You are on page 1of 233

Java Programming Tutorial

JAVA PROGRAMMING TUTORIAL

Lets Learn in New Look

Shaik Bilal Ahmed

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.

Copyright & Disclaimer Notice


A ll

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

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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 Environment Setup ........................................................ 15


Setting up the path fo r wi ndows 2000/XP:................................................15
Setting up the path fo r wi ndows 95/98/ME: ..............................................15
Setting up the path fo r Linux, UNIX , So laris, FreeBSD: ...........................15
Popular Java Editors: ...............................................................................16
Wha t is Next ? ..........................................................................................16

Java Basic Syntax.................................................................. 17


First Java Program : ..................................................................................17
Basic Syntax: ...........................................................................................18
Java Ide ntifiers: ........................................................................................18
Java Modifiers: .........................................................................................19
Java Variables:.........................................................................................19
Java Arrays : .............................................................................................19
Java E nums : ............................................................................................19
Example : ..................................................................................................19
Java Ke ywords: ........................................................................................20
Comments in Ja va ...................................................................................20
Using B lank Lines: ...................................................................................20
Inhe ritance : ..............................................................................................20
Interfaces: ................................................................................................21
Wha t is Next ? ..........................................................................................21

Java Object & Classes ........................................................... 22


Objects in Ja va:........................................................................................22
Classes in Ja va : .......................................................................................23
Constr uctors: ............................................................................................23
Creating a n Object: ..................................................................................24
Accessing Insta nce Variables a nd Me thods: ............................................24
Example : ..................................................................................................24
Source file dec laratio n r ules: ....................................................................25
JAVA PROGRAMMING TUTORIAL
BILAL AHMED SHAIK

Java Package :..........................................................................................26


Import sta teme nts : ...................................................................................26
A Simple Case Stud y: ..............................................................................26
Wha t is Next ? ..........................................................................................27

Java Basic Datatypes............................................................. 28


Primitive Data Types: ...............................................................................28
byte : .........................................................................................................28
short: ........................................................................................................28
int: ............................................................................................................29
long : .........................................................................................................29
float: .........................................................................................................29
double : .....................................................................................................30
boolean: ...................................................................................................30
char : .........................................................................................................30
Refere nce Data Types : ............................................................................30
Java Literals: ............................................................................................31
Wha t is Next ? ..........................................................................................32

Java Variable Types .............................................................. 33


Local variables : .......................................................................................33
Example : ..................................................................................................34
Example : ..................................................................................................34
Insta nce variables : ..................................................................................34
Example : ..................................................................................................35
Class/static va riables :..............................................................................36
Example : ..................................................................................................36
Wha t is Next ? ..........................................................................................37

Java Modifier Types ............................................................... 38


1. Ja va Access Modifiers..........................................................................38
Default Access Modifier - No ke yword:.....................................................38
Example : ..................................................................................................38
Private Access Modifier - private: .............................................................39
Example : ..................................................................................................39
Public Access Modifier - p ub lic:................................................................39
Example : ..................................................................................................39
Protected Access Modifier - p rotected : ....................................................40
Example : ..................................................................................................40
Access Contro l a nd Inherita nce: ..............................................................40
2. No n Access Modifiers...........................................................................40
Access Contro l Modifiers:.........................................................................41
JAVA PROGRAMMING TUTORIAL
BILAL AHMED SHAIK

Non Access Modifiers:..............................................................................41


Access Contro l Modifiers:.........................................................................41
Non Access Modifiers:..............................................................................41
Wha t is Next ? ..........................................................................................42

Java Basic Operators ............................................................. 43


The Arithmetic Opera tors: ........................................................................43
The Relational Operators: ........................................................................44
Example ...................................................................................................45
The Bitwise Operators:.............................................................................45
Example ...................................................................................................46
The Logical Operators:.............................................................................47
Example ...................................................................................................47
The Assignme nt Operato rs: .....................................................................47
Example : ..................................................................................................48
Misc Operators.........................................................................................49
Conditional Operator ( ? : ): ......................................................................49
insta nceOf Operator : ................................................................................50
Precedence of Ja va Operators:................................................................50
Wha t is Next ? ..........................................................................................51

Java Loop Control.................................................................. 52


The while Loop: ........................................................................................52
Synta x: .....................................................................................................52
Example : ..................................................................................................52
The do...while Loop: .................................................................................53
Synta x: .....................................................................................................53
Example : ..................................................................................................53
The for Loop: ............................................................................................54
Synta x: .....................................................................................................54
Example : ..................................................................................................54
Enhanced for loop in Ja va :.......................................................................55
Synta x: .....................................................................................................55
Example : ..................................................................................................55
The break Keyword: .................................................................................55
Synta x: .....................................................................................................56
Example : ..................................................................................................56
The co nti nue Ke yword :.............................................................................56
Synta x: .....................................................................................................56
Example : ..................................................................................................56
Wha t is Next ? ..........................................................................................57
JAVA PROGRAMMING TUTORIAL
BILAL AHMED SHAIK

Java Decision Making ............................................................ 58


The if Stateme nt: ......................................................................................58
Synta x: .....................................................................................................58
Example : ..................................................................................................58
The if...else Stateme nt: ............................................................................59
Synta x: .....................................................................................................59
Example : ..................................................................................................59
The if...else if...else S tateme nt: ................................................................59
Synta x: .....................................................................................................59
Example : ..................................................................................................60
Nested if...else S tateme nt: .......................................................................60
Synta x: .....................................................................................................60
Example : ..................................................................................................60
The s witc h Stateme nt: ..............................................................................61
Synta x: .....................................................................................................61
Example : ..................................................................................................61
Wha t is Next? ...........................................................................................62

Java Numbers ........................................................................ 63


Example : ..................................................................................................63
Number Methods:.....................................................................................64
Wha t is Next ? ..........................................................................................65

Java Characters ..................................................................... 66


Example : ..................................................................................................66
Example : ..................................................................................................66
Escape Sequences : .................................................................................66
Example : ..................................................................................................67
Character Methods: ..................................................................................67
Wha t is Next? ...........................................................................................68

Java Strings ........................................................................... 69


Creating Strings: ......................................................................................69
String Le ngth: ...........................................................................................69
Concate nating Stri ngs: .............................................................................70
Creating Format Strings: ..........................................................................70
String Methods: ........................................................................................71

Java Arrays ............................................................................ 74


Declaring Arra y Variables:........................................................................74
Example : ..................................................................................................74
Creating Arra ys : .......................................................................................74
Example : ..................................................................................................75
JAVA PROGRAMMING TUTORIAL
BILAL AHMED SHAIK

Processing Arra ys: ...................................................................................75


Example : ..................................................................................................75
The foreac h Loops: ..................................................................................76
Example : ..................................................................................................76
Passing Arra ys to Me thods: .....................................................................76
Retur ni ng a n Arra y from a Me thod : ..........................................................77
The Arrays Class:.....................................................................................77

Java Date & Time .................................................................. 78


Getti ng C urre nt Date & Time ....................................................................79
Date Comparison: ....................................................................................79
Date Formatting usi ng SimpleDateFormat: ..............................................79
Simple DateFormat forma t codes: ............................................................80
Date Formatting usi ng pri ntf: ....................................................................81
Date and Time Conversion Characters: ...................................................82
Parsing Stri ngs i nto Dates:.......................................................................83
Sleeping for a W hile : ................................................................................83
Measuring E lapsed Time :.........................................................................84
GregorianCale ndar Class: ........................................................................84
Examp le: ..................................................................................................86

Java Regular Expressions ..................................................... 88


Capturi ng Gro ups: ....................................................................................88
Example : ..................................................................................................89
Regular Expressio n S ynta x: .....................................................................89
Methods of the Matc her Class:.................................................................90
Inde x Methods:.........................................................................................90
Stud y Methods: ........................................................................................91
Replaceme nt Methods : ............................................................................91
The start a nd e nd Methods: .....................................................................91
The m atches and lookingAt Methods: ......................................................92
The replaceFirst and replaceAll Methods: ................................................93
The appendReplacem ent and appendTail Methods:................................93
PatternSyntaxE xceptio n Class Methods: .................................................94

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

Passing Parameters b y Values: ...............................................................98


Example : ..................................................................................................98
Overloading Me thods : ..............................................................................99
The Scope of Variables: ...........................................................................99
Using Command-Line Arg ume nts: .........................................................100
Example : ................................................................................................100
The Co nstr uctors:...................................................................................101
Example : ................................................................................................101
Example : ................................................................................................101
Variable Argume nts( var-a rgs): ...............................................................102
Example : ................................................................................................102
The fina lize( ) Method:............................................................................102

Java Files & I/O.................................................................... 104


Reading Co nsole Inp ut: ..........................................................................104
Reading C haracters from Co nsole: ........................................................104
Reading Strings from Conso le: ..............................................................105
Writing Co nsole Outp ut: .........................................................................106
Example : ................................................................................................106
Reading a nd Writing Files: .....................................................................106
FileInp utS tream:.....................................................................................107
ByteArra yInp utStream ............................................................................108
Example : ................................................................................................108
DataInp utS tream ....................................................................................109
Example : ................................................................................................110
FileOutputStream : ..................................................................................110
ByteArra yOutp utS tream .........................................................................111
Example : ................................................................................................112
DataOutputStrea m .................................................................................113
Example : ................................................................................................113
Example : ................................................................................................114
File Na vigation and I/O: ..........................................................................114
File Class ...............................................................................................114
Example : ................................................................................................117
FileReader Class....................................................................................118
Example : ................................................................................................118
FileWriter Class......................................................................................119
Example : ................................................................................................120
Directories in Ja va:.................................................................................120
Creating Directories:...............................................................................120
JAVA PROGRAMMING TUTORIAL
BILAL AHMED SHAIK

Reading Directories:...............................................................................121

Java Exceptions ................................................................... 122


Exception Hierarc hy: ..............................................................................122
Exceptions Methods : ..............................................................................124
Catching Excep tions:..............................................................................124
Example : ................................................................................................125
Multiple catc h B locks:.............................................................................125
Example : ................................................................................................126
The throws/thro w Ke ywords: ..................................................................126
The fina lly Ke ywo rd ................................................................................126
Example : ................................................................................................127
Declaring yo u o wn E xceptio n: ................................................................128
Example : ................................................................................................128
Common E xceptio ns: .............................................................................130

Java Inheritance................................................................... 131


IS-A Re lations hip: ..................................................................................131
Example : ................................................................................................132
Example : ................................................................................................132
The i nsta nceof Keyword: ........................................................................132
HAS-A relations hip: ................................................................................133

Java Overriding .................................................................... 134


Example : ................................................................................................134
Rules for method ove rriding: ..................................................................135
Using the s uper ke yword:.......................................................................136

Java Polymorphism.............................................................. 137


Example : ................................................................................................137
Virtual Methods : .....................................................................................138

Java Abstraction .................................................................. 141


Abstract Class : .......................................................................................141
Exte nding Abstract Class: ......................................................................142
Abstract Methods: ..................................................................................144

Java Encapsulation.............................................................. 145


Example : ................................................................................................145
Benefits o f E ncaps ula tion: ......................................................................146

Java Interfaces..................................................................... 147


Declaring Interfaces: ..............................................................................148
Example : ................................................................................................148
Example : ................................................................................................148
Impleme nting Inte rfaces: ........................................................................148
JAVA PROGRAMMING TUTORIAL
BILAL AHMED SHAIK

Exte nding Inte rfaces : .............................................................................149


Exte nding M ultiple Interfaces: ................................................................150
Tagging Interfaces: ................................................................................150

Java Packages..................................................................... 151


Creating a package: ...............................................................................151
Example : ................................................................................................151
The impor t Ke yword : ..............................................................................152
Example : ................................................................................................152
The Director y Str ucture of Packages: ....................................................153
Set CLASSPATH S ystem Variable: .......................................................154

Java Data Structures............................................................ 156


The E numeration:...................................................................................156
Example : ................................................................................................157
The BitSet ..............................................................................................157
Example : ................................................................................................159
The Vecto r..............................................................................................160
Example : ................................................................................................163
The Stack ...............................................................................................164
Example : ................................................................................................165
The Dictionar y ........................................................................................165
Map Interface .........................................................................................166
Example : ................................................................................................167
The Has htable ........................................................................................168
Example : ................................................................................................169
The Properties........................................................................................170
Example : ................................................................................................171

Java Collections ................................................................... 173


The Collection Interfaces:.......................................................................173
The Collection Classes:..........................................................................174
The Collection Algorithms: .....................................................................175
How to use a n Iterator? ..........................................................................176
How to use a n Comparato r? ..................................................................176
Summa ry: ...............................................................................................176

Java Generics ...................................................................... 177


Gene ric Methods: ...................................................................................177
Example : ................................................................................................177
Bounded Type Paramete rs: ...................................................................178
Example : ................................................................................................178
Gene ric Classes: ....................................................................................179
JAVA PROGRAMMING TUTORIAL
BILAL AHMED SHAIK

Example : ................................................................................................179

Java Serialization................................................................. 181


Serializing a n Ob ject: .............................................................................182
Deserializing a n Ob ject: .........................................................................182

Java Networking .................................................................. 184


Url Processing ........................................................................................184
URL C lass Me thods: ..............................................................................185
Example : ................................................................................................185
URLConnections Class Methods: ..........................................................186
Example : ................................................................................................187
Socket Programmi ng:.............................................................................188
ServerSocket Class Methods: ................................................................189
Socket Class Methods:...........................................................................190
Ine tAddress Class Methods: ..................................................................191
Socket Client Exa mple: ..........................................................................191
Socket Serve r E xample:.........................................................................192

Java Sending Email ............................................................. 194


Send a Simple Email: .............................................................................194
Send a n HTML Email: ............................................................................195
Send Attac hment i n Email: .....................................................................197
User Authentication Part: .......................................................................198

Java Multithreading .............................................................. 199


Life Cycle of a Thread: ...........................................................................199
Thread Priorities: ....................................................................................200
Creating a Thread: .................................................................................200
Create Thread b y Impleme nting Runnable:............................................201
Example : ................................................................................................201
Create Thread b y E xte ndi ng Thread: .....................................................202
Example : ................................................................................................202
Thread Methods: ....................................................................................203
Example : ................................................................................................204
Major Thread Concepts:.........................................................................206
Example : ................................................................................................208
Example : ................................................................................................209
Ordering Locks: ......................................................................................211
Deadlock Examp le: ................................................................................211
Deadlock Solution Examp le: ..................................................................213
Example : ................................................................................................215
Using M ultithreading:..............................................................................217
JAVA PROGRAMMING TUTORIAL
BILAL AHMED SHAIK

Java Applet Basics ............................................................... 218


Life Cycle of an Applet: ..........................................................................218
A "Hello, World" Applet:..........................................................................219
The Apple t CLASS: ................................................................................219
Invoki ng a n Apple t:.................................................................................220
Getti ng Apple t Parameters: ....................................................................221
Specifying Apple t Parame ters: ...............................................................222
Application Conversio n to Applets:.........................................................222
Event Ha ndli ng: ......................................................................................223
Displaying Images: .................................................................................224
Playing Audio: ........................................................................................225

Java Documentation ............................................................ 227


The ja vadoc Tags:..................................................................................227
Docume ntatio n Comme nt:......................................................................228
Wha t ja vadoc Outp uts? ..........................................................................228
Example : ................................................................................................228

Java Library Classes ............................................................ 231

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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 .

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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.

Tools you will need:


For perform ing the exam ples dis cuss ed in this tutorial, you will need a Pentium 200 -MH z com puter with
a m inim um of 64 MB o f R AM (128 MB o f R AM recom mended).
You als o will need the following softwares :

Linux 7.1 or Windows 95/98/2000/XP operating s ys tem .

Java JDK 5

Micros oft Notepad or an y other te xt editor

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 .

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

CHAPTER

Java Environment Setup

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 :

Setting up the path for windows 2000/XP:


As s uming you have ins talled Java in c:\Program Files\java\jdk directory:

Right-click on 'My Com puter' and s elect 'Properties '.

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'.

Setting up the path for windows 95/98/ME:


As s uming you have ins talled Java in c:\Program Files\java\jdk directory:

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:

Setting up the path for Linux, UNIX, Solaris, FreeBSD:


Environm ent variable PATH s hould be set to point to where the ja va binaries have been ins talled. Refer to your
s hell docum entation if you ha ve trouble doing this .
Exam ple, i f you use b ash as your s hell, then you would add the following line to the end o f your '.bashrc: e xport
PATH=/path/to/ja va:$P ATH '

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

Popular Java Editors:


To write your ja va programs you will need a te xt editor. There are e ven m ore sophis ticated IDE available in the
m arket. But for now , you can consider one of the following:

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 .

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

CHAPTER

Java Basic Syntax

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 .

First Java Program:


Let us look at a simple code that would print the words Hello World.
public class MyFirstJavaProgram {
/* This is my first java program.
* This will print 'Hello World' as the output
*/
public static void main(String []args) {
System.out.println("Hello World"); // prints Hello World
}
}
Lets look at how to save the file, com pile and run the program . Pleas e follow the s teps given below:

Open notepad and add the code as above.

Save the file as : MyFirs tJavaPro gram .java.

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).

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

Now type ' ja va MyFirs tJavaProgram ' to run your program .

You will be able to s ee ' Hello Wo rld ' printed on the window.

C : > javac MyFirstJavaProgram.java


C : > java MyFirstJavaProgram
Hello World

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.

Exam ple class MyFirstJavaClass


Method Names - All m ethod names s hould s tart with a Lower Cas e letter.
If s everal words are us ed to form the nam e of the method, then each inner word's fi rs t letter should be in
Upper Case.

Exam ple pub lic void m yMethodName()


Program File Name - Name of the program file s hould exactl y m atch the class nam e.
When s aving the file you s hould s ave it us ing the class nam e (Remem ber java is cas e s ens itive) and a ppend
'.java' to the end o f the nam e. (i f the file nam e and the class nam e do not m atch your program will not
compile).
Exam ple : As s ume 'MyFirs tJavaProgram ' is the class nam e. Then the file s hould be s aved
as 'MyFirstJavaProgram .java'

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 (_).

After the firs t character identifiers can ha ve an y com bination of characters .

A ke y word canno t be used as an identifier.

Mos t im portantly identifiers are case s ens itive.

Exam ples of legal identifiers :age, $s alary, _ value,

Exam ples of illegal identifiers : 123abc, -s alary

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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 .

Access Modifiers : default, public , protected, pri vate


Non-access Modifiers : final , abs tract, s trictfp

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 )

Ins tance Variables (Non s tatic 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 PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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.
*/

public static void main(String []args){


// This is an example of single line comment
/* This is also an example of single line comment. */
System.out.println("Hello World");
}

Using Blank Lines:


A line containing onl y whites pace, possibly with a comm ent, is known as a blank line, and Java totall y i gnores it.

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.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

CHAPTER

Java Object & Classes

ava is an Object Oriented Lan guage. As a language that has the Object Oriented feature Ja va s upports the

following fundam ental concepts :

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 .

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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 .

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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 :

Declaration . A variable declarati on with a variable nam e with an object type.


Instantiation . The 'new ' ke y word is used to create the object.
Initia lization . The 'new ' ke yword is followed by a call to a cons tructor. This call initializes the new object.

Exam ple of creating an object is given below:


public class Puppy{
public Puppy(String name){
// This constructor has one parameter, name.
System.out.println("Passed Name is :" + name );
}
public static void main(String []args){
// Following statement would create an object myPuppy
Puppy myPuppy = new Puppy( "tommy" );
}
}
If we com pile and run the above program then it would produce following res ult:
Passed Name is :tommy

Accessing Instance Variables and Methods:


Ins tance variables and m ethods are accessed via created objects . To access an ins tance variable the
fully qualified path should be as follows :
/* First create an object */
ObjectReference = new Constructor();
/* Now call a variable as follows */
ObjectReference.variableName;
/* Now you can call a class method as follows */
ObjectReference.MethodName();

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( ){

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

System.out.println("Puppy's age is :" + puppyAge );


return puppyAge;
}
public static void main(String []args){
/* Object creation */
Puppy myPuppy = new Puppy( "tommy" );
/* Call class method to set puppy's age */
myPuppy.setAge( 2 );
/* Call another class method to get puppy's age */
myPuppy.getAge( );
/* You can access instance variable as follows as well */
System.out.println("Variable Value :" + myPuppy.puppyAge );
}
}
If we com pile and run the above program then it would produce following res ult:
Passed Name is :tommy
Puppy's age is :2
Variable Value :2

Source file declaration rules:


As the las t part o f this s ection lets us now look into the s ource file declaration rules . Thes e rules are ess ential
when declaring classes , im port s tatem ents and pack age s tatem ents in a s ource file.

There can be only one public class per s ource file.

A s ource file can have multiple non public class es .

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 PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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.*;

A Simple Case Study:


For our case s tudy we will be creating two class es . They are Em ployee and Em ployeeTes t.
Firs t open notepad and add the following code. Rem ember this is the Employee class and the class is a public
class . Now s ave this s ource file with the nam e Em ployee.java.
The Em ployee class has four class variables nam e, age, des ignation and salary. The class has one
explicitl y defined cons tructor which takes a param eter.
import java.io.*;
public class Employee{
String name;
int age;
String designation;
double salary;
// This is the constructor of the class Employee
public Employee(String name){
this.name = name;
}
// Assign the age of the Employee to the variable age.
public void empAge(int empAge){
age = empAge;
}
/* Assign the designation to the variable designation.*/
public void empDesignation(String empDesig){
designation = empDesig;
}
/* Assign the salary to the variable
salary.*/
public void empSalary(double empSalary){
salary = empSalary;
}
/* Print the Employee details */
public void printEmployee(){
System.out.println("Name:"+ name );
System.out.println("Age:" + age );
System.out.println("Designation:" + designation );
System.out.println("Salary:" + salary);
}
}

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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 .

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

CHAPTER

Java Basic Datatypes

ariables are nothing but res erved m em ory locations to s tore values . This m eans that when you create a

variable you res erve som e s pace in m em ory.


Bas ed on the data type of a variable , the operating s ys tem allocates mem ory and decides what can be s tored in
the res erved m em ory. Therefore, b y ass igning different data types to variables , you can s tore integers , decimals ,
or characters in thes e variables .
There are two data types available in Ja va:

Prim itive Data Types

Reference/Object Data Types

Primitive Data Types:


There are eight prim itive data types s upported by Ja va. Prim itive data types are predefined by the language and
named by a key word . Le t us now look into detail about the eight primitive data t ypes .

byte:

Byte data t ype is a 8-bit s igned two's com plem ent integer.

Minim um value is -128 (-2^7)

Ma xim um value is 127 (inclusive)(2^7 -1)

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.

Exam ple : b yte a = 100 , b yte b = -50

short:

Short data type is a 16-bit signed two's com plem ent integer.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

Minim um value is -32,768 (-2^15)

Ma xim um value is 32,767(inclus ive) (2^15 -1)

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.

Exam ple : short s = 10000 , short r = -20000

int:

int data type is a 32-bit signed two's com plem ent integer.

Minim um value is - 2,147,483,648.(-2^31)

Ma xim um value is 2,147,483,647(inclus ive).(2^31 -1)

Int is generally us ed as the default data type for integral values unless there is a concern about m em ory.

The default value is 0.

Exam ple : in t a = 100000 , in t b = -200000

long:

Long data type is a 64-bit signed two's com plem ent integer.

Minim um value is -9,223,372,036,854,775,808.(-2^63)

Ma xim um value is 9,223,372,036,854,775,807 (inclusive). (2 ^63 -1)

This type is us ed when a wider range than int is needed.

Default value is 0L.

Exam ple : in t a = 100000L , i nt b = -200000L

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 .

Default value is 0.0f.

Float data type is never us ed for precis e values s uch as currency.

Exam ple : floa t f1 = 234.5 f

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

double:

double data type is a double-precision 64-bit IEEE 754 floating point.

This data type is generally used as the default data type for 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.

Default value is 0.0d.

Exam ple : double d1 = 123.4

boolean:

boolean data type repres ents one bit of inform ation.

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 .

Default value is fals e.

Exam ple : boolean one = true

char:

char data type is a single 16-bit Unicode character.

Minim um value is '\u0000' (or 0).

Ma xim um value is '\uffff' (or 65,535 inclusive).

Char data type is us ed to s tore any character.

Exam ple . char letterA =' A'

Reference Data Types:

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 .

Default value o f an y reference va riable is null.

A reference variable can be us ed to refer to an y object of the declared type or an y com patible type .

Exam ple : Anim al anim al = new Animal("giraffe");

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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

Carriage return (0 x0d)

\f

Form feed (0x0c)

\b

Backs pace (0x08)

\s

Space (0 x20)

\t

tab

\"

Double quote

\'

Single quote

\\

backslas h

\ddd

Octal character (ddd)

\uxxxx

He xadecim al UNICODE character (xxxx)

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

CHAPTER

Java Variable Types

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

Ins tance variables

Class /s tatic variables

Local variables :

Local variables are declared in m ethods , cons tructors , or blocks .

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..

Acces s m odifiers cannot be us ed for local variables .

Local variables are vis ible only within the declared m ethod, cons tructor or block.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

Local variables are im plem ented at s tack level internall y.

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);
}

public static void main(String args[]){


Test test = new Test();
test.pupAge();
}

This would produce following result:


Puppy age is: 7

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.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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 .

Ins tance variables can be declared in class level before or after us e.

Acces s m odifiers can be given for ins tance variables .

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

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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

an outs ide class

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

the cons tant s hould be acces sed as

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.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

CHAPTER

Java Modifier Types

odifiers are keywords that you add to thos e definitions to change their meanings . The Java language

has a wide variety o f m odifiers , including the following:

1. Java Access Modifiers


Java pro vides a num ber o f access m odifiers to s et acces s levels for classes , vari ables , m ethods and
cons tructors . The four access levels are:

Vis ible to the package. the default. No m odifiers are needed.

Vis ible to the class only (private).

Vis ible to the world (public).

Vis ible to the package and all s ubclasses (protected).

Default Access Modifier - No keyword:


Default access m odifier m eans we do not e xplicitl y declare an access m odifier for a class , field, m ethod etc.
A variable or m ethod declared without an y access control m odifier is available to an y other class in the s ame
package. The defaul t modifier cannot be used for methods , fields in an interface.

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;
}

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

Private Access Modifier - private:


Methods , Variables and Cons tructors that are declared pri vate can onl y be accessed within the declared class
its elf.
Private access modifier is the mos t res trictive access level. Class and interfaces cannot be private .
Variables that are declared pri vate can be access ed outs ide the class if public getter m ethods are pres ent in the
class .
Using the private modifier is the main way that an object encaps ulates itself and hide data from the outs ide world.

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.

Public Access Modifier - public:


A class , m ethod, cons tructor, interface etc declared public can be access ed from an y other class .
Therefore fields , methods , blocks declared inside a public class can be accessed from any class belonging
to the Java Uni vers e.
However if the public class we are trying to access is in a different package, then the public class s till need to be
im ported.
Becaus e of class inheritance, all public m ethods and variables of a class are inherited by its s ubclasses .

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 .

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

Protected Access Modifier - protected:


Variables , methods and cons tructors which are declared protected in a superclass can be access ed only by the
s ubclasses in other package or any class within the package of the protected mem bers ' class .
The protected access modifier cannot be applied to class and interfaces . Methods , fields can be
declared protected, howe ver m ethods and fields in a interface cannot be declared protected .
Protected access gives the s ubclass a chance to us e the helper m ethod or variable, while pre venting a
nonrelated class from trying to us e it.

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.

Access Control and Inheritance:


The following rules for inherited methods are enforced:

Methods declared public in a s uperclass also m us t be public in all s ubclass es .

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 .

2. Non Access Modifiers


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 exam ples (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
}

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

Access Control Modifiers:


Java pro vides a num ber o f access m odifiers to s et access levels for class es , vari ables , m ethods and
cons tructors . The four access levels are:

Vis ible to the package. the default. No m odifiers are needed.

Vis ible to the class only (private).

Vis ible to the world (public).

Vis ible to the package and all s ubclasses (protected).

Non Access Modifiers:


Java pro vides a num ber of non-access m odifiers to achieve m any other functionality.

The static m odifier for creating class m ethods and variables


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 m ethods .
The synchronized and volatile m odifiers , which are us ed for threads .

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
}

Access Control Modifiers:


Java pro vides a num ber o f access m odifiers to s et access levels for class es , vari ables , m ethods and
cons tructors . The four access levels are:

Vis ible to the package. the default. No m odifiers are needed.

Vis ible to the class only (private).

Vis ible to the world (public).

Vis ible to the package and all s ubclasses (protected).

Non Access Modifiers:


Java pro vides a num ber of non-access m odifiers to achieve m any other functionality.

The static m odifier for creating class m ethods and variables

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

CHAPTER

Java Basic Operators

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 :

Arithm etic Operators

Relational Operators

Bitwis e Operators

Logical Operators

As s ignm ent Operators

Mis c Operators

The Arithmetic Operators:


Arithm etic operators are used in m athematical express ions in the sam e way that the y are us ed in algebra. The
following table lis ts the arithmetic operators :
As s ume integer variable A holds 10 and variable B holds 20 then:
Operator

Description

Example

Addition - Adds values on either s ide of the operator

A + B will gi ve 30

Subtraction - Subtracts right hand operand from left hand operand

A - B will gi ve -10

Multiplication - Multiplies values on either s ide of the operator

A * B will gi ve 200

Divis ion - Divides left hand operand b y right hand operand

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

++

Increm ent - Increase the value of op erand b y 1

B++ gives 21

--

Decrem ent - Decreas e the value of op erand b y 1

B-- gives 19

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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

The Relational Operators:


There are following relational operators s upported by Ja va language
As s ume variable A holds 10 and varia ble B holds 20 then:
Operator Description

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.

(A > B) is not 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 .

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

<=

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

The Bitwise Operators:


Java defines s everal bitwis e operators which can be applied to the integer types , long , int, short, ch ar, and b yte.
Bitwis e operator works on bits and perform bit by bit operation. Ass um e if a = 60; and b = 13; Now in
binary
form at they will be as follows :
a = 0011 1100
b = 0000 1101
----------------a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
The following table lis ts the bitwise operators :
As s ume integer variable A holds 60 and variable B holds 13 then:

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

Operator Description

Example

&

Binary AND Operator copies a bit to the res ult if it


exis ts in both operands .

(A & B) will gi ve 12 which is 0000 1100

Binary OR Operator copies a bit i f i t e xis ts in


eather operand.

(A | B) will gi ve 61 which is 0011 1101

Binary XOR Operator copies the bit i f it is s et in


one operand but no t both .

Binary Ones Com plem ent Operator is unary and


has the efect of 'flipping ' bits .

<<

Binary Left Shift Operator. The left operan ds value


A << 2 will gi ve 240 which is 1111 0000
is m oved left b y the num ber of bits specified by
the right operand .

>>

Binary Right Shift Operator. The left operan ds


value is m oved right b y the num ber of bits
s pecified by the right operand .

A >> 2 will gi ve 15 which is 1111

>>>

Shift right zero fill operator. The left op erands


value is m oved right b y the num ber of bits s
pecified by the righ t operand and shifted values
are filled up with zeros .

A >>>2 will gi ve 15 which is 0000 1111

(A ^ B) will gi ve 49 which is 0011 0001


(~A ) will gi ve -60 which is 1100 0011

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

static void main(String args[]) {


a = 60; /* 60 = 0011 1100 */
b = 13; /* 13 = 0000 1101 */
c = 0;

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 );
}
}

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

This would produce following result:


a & b = 12
a | b = 61
a ^ b = 49
~a = -61
a << 2 = 240
a >> 15
a >>> 15

The Logical Operators:


The following table lis ts the logical operators :
As s ume boolean variables A holds true and variable B holds fals e then:
Operator Description

Example

&&

Called Logical AND operator. If both the operands are non zero then
then condition becom es true.

(A && B) is fals e.

||

Called Logical OR Operator. If an y of the two operands are non zero


then then condition becom es true.

(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

The Assignment Operators:


There are following ass ignm ent operators s upported by Java language:
Operator Description

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

Example

Sim ple ass ignm ent operator, As signs values


from right s ide operands to left s ide operand

C = A + B will assigne value of A + B into C

+=

Add AND ass ignm ent operator, It adds right


operand to the left operand and ass ign the
res ult to left operand

C += A is equivalen t to C = C + A

-=

Subtract AND as signment operator, It


s ubtracts right operand from the left operand
and ass ign the res ult to left operand

C -= A is equivalen t to C = C - A

*=

Multipl y AND as signment operator, It m ultiplies


right operand with the left operand and ass ign C *= A is equivalen t to C = C * A
the res ult to left operand

/=

Divide AND ass ignm ent operator, It d i vides left


operand with the right operand and assign the C /= A is equivalen t to C = C / A
res ult to left operand

%=

Modulus AND ass ignm ent operator, It takes


m odulus using two operands and as sign the
res ult to left operand

C %= A is equivalen t to C = C % A

<<=

Left s hift AND ass ignm ent operator

C <<= 2 is sam e as C = C << 2

>>=

Right s hift AND ass ignm ent operator

C >>= 2 is sam e as C = C >> 2

&=

Bitwis e AND ass ignm ent operator

C &= 2 is s am e as C = C & 2

^=

bitwis e exclus ive OR and ass ignm ent operator

C ^= 2 is s am e as C = C ^ 2

|=

bitwis e inclus ive OR and ass ignm ent operator

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

static void main(String args[]) {


a = 10;
b = 20;
c = 0;

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 );

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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;

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " +

b );

b = (a == 10) ? 20: 30;


System.out.println( "Value of b is : " + b );
}
}
This would produce following result:
Value of b is : 30
Value of b is : 20

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

Precedence of Java Operators:


Operator precedence determines the grouping of terms in an express ion. This affects how an express ion is
evaluated . Certain operators have higher precedence than others ; for exam ple, the m ultiplication operator has
higher precedence than the addition operator:
For exam ple x = 7 + 3 * 2; Here x is ass igned 13, not 20 becaus e operator * has higher precedenace than + so it
firs t get m ultiplied with 3*2 and then adds into 7.
Here operators with the highes t precedence appear at the top of the table, thos e with the lowes t appear at the
bottom . Within an expression, higher precedenace operators will be evaluated firs t.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

CHAPTER

Java Loop Control

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 .

The while Loop:


A while loop is a control s tructure that allows you to repeat a tas k a certain num ber of tim es .

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 );

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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

The do...while Loop:


A do...while loop is s im ilar to a while loop, e xcept that a do...while loop is guaranteed to execute at leas t one
tim e.

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

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

value
value
value
value
value
value

of
of
of
of
of
of

x
x
x
x
x
x

: 14
: 15
: 16
: 17
: 18
: 19

The for Loop:


A for loop is a repetition control s tructure that allows you to efficientl y write a loop that needs to execute a s pecific
number of times .
A for loop is us eful when you know how m any tim es a tas k is to be repeated.

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

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

value
value
value
value
value
value

of
of
of
of
of
of

x
x
x
x
x
x

: 14
: 15
: 16
: 17
: 18
: 19

Enhanced for loop in Java:


As of ja va 5 the enhanced for loop w as introduced. This is mainly used for Arrays .

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:


The b reak keyword is us ed to s top the entire loop. The break ke yword m us t be used ins ide any loop or a s witch
s tatem ent.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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

The continue Keyword:


The continue keyword can be us ed in an y of the loop control s tructures . It caus es the loop to imm ediately jump to
the next iteration o f the loop .

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");

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

}
}
}
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.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

CHAPTER

10
Java Decision Making

here are two types of decis ion m aking s tatements in Java. The y are:

if s tatements

s witch s tatem ents

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

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

The if...else Statement:


An if s tatem ent can be followed by an optional else s tatement, which executes when the Boolean express ion is
false.

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

The if...else if...else Statement:


An if s tatem ent can be followed b y an optional else if...else s tatem ent, which is very us efull to tes t
various conditions us ing single if...else if s tatem ent.
When using if, els e if , els e s tatem ents there are few points to keep in mind.

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 {

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

//Executes when the none of the above condition is true.


}

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

Nested if...else Statement:


It is always legal to nes t if-els e s tatem ents , which m eans you can use one if or else if s tatem ent ins ide another if
or els e if s tatem ent.

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");
}
}
}

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

This would produce following result:


X = 30 and Y = 10

The switch Statement:


A swi tch s tatement allows a variable to be tes ted for equality agains t a lis t of values . Each value is called a case,
and the variable being switched on is checked for each cas e.

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!");

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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 .

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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);
}
}

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

This would produce following result:


15
When x is ass igned integer values , the compiler boxes the integer becaus e x is integer obj ects . Later, x
is unboxed so that they can be add ed as integers .

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:

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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

Ins ert a tab in the te xt at this point.

\b

Ins ert a backspace in the text at this point.

\n

Ins ert a newline in the te xt at this point.

\r

Ins ert a carriage return in the te xt at this point.

\f

Ins ert a form feed in the text at this point.

\'

Ins ert a single quote character in the text a t this point.

\"

Ins ert a double quote character in the te xt a t this point.

\\

Ins ert a backslas h character in the text a t this point.

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:

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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 .

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

CHAPTER

13
Java Strings

trings which are widely us ed in Ja va programming, are a s equence of characters . In the Ja va

programm ing language, s trings are objects .


The Java platform provides the String class to create and manipulate s trings .

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.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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

Creating Format Strings:


You ha ve printf() and form at() m ethods to print output with form atted numbers . The String class has an equivalent
class m ethod, format(), that returns a String object rather than a PrintStream object.
Using String's s tatic form at() m ethod allows you to create a form atted s tring that you can reus e, as oppos ed to a
one-tim e print s tatem ent. For exam ple, ins tead of:
System.out.printf("The value of the float variable is " +
"%f, while the value of the integer " +

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

"variable is %d, and the string " +


"is %s", floatVar, intVar, stringVar);
you can write :
String fs;
fs = String.format("The value of the float variable is " +
"%f, while the value of the integer " +
"variable is %d, and the string " +
"is %s", floatVar, intVar, stringVar);
System.out.println(fs);

String Methods:
Here is the lis t m ethods s upported by String class :

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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 .

Declaring Array Variables:


To use an array in a program , you m us t declare a variable to reference the arra y, and you m us t s pecify the type
of arra y the variable can reference . H ere is the s yntax for declaring an arra y variable :
dataType[] arrayRefVar;

// preferred way.

or
dataType arrayRefVar[];

//

works but not preferred way.

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[];

//

works but not preferred way.

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 :

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

It creates an array us ing new dataType[arra ySi ze];

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++) {

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

System.out.println(myList[i] + " ");


}
// Summing all elements
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);
// Finding the largest element
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}
This would produce following result:
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5

The foreach Loops:


JDK 1.5 introduced a new for loop, known as foreach loop or enhanced for loop, which enables you to tra vers e
the complete array s equentially without using an index variable.

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

Passing Arrays to Methods:


Jus t as you can pass prim itive type val ues to m ethods , you can also pass arrays to methods . For exam ple, the
following m ethod dis plays the elements in an int arra y:

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

public static void printArray(int[] array) {


for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
You can in voke i t b y pas s ing an array. For e xam ple, the following s tatem ent invokes the printArra y m ethod to
display 3, 1 , 2 , 6 , 4 , and 2 :
printArray(new int[]{3, 1, 2, 6, 4, 2});

Returning an Array from a Method:


A m ethod may als o return an array. For e xam ple, the m ethod s hown below returns an array that is the re vers al of
another array:
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
for (int i = 0, j = result.length - 1; i < list.length; i++, j--) {
result[j] = list[i];
}
return result;
}

The Arrays Class:


The java.util.Arra ys class contains various s tatic m ethods for s orting and s earching arrays , com paring arrays , and
filling array elements . These m ethods are overloaded for all primitive types .
SN Methods w ith Description

public static int binarySearch(Object[] a , Object ke y)


Searches the s pecified array of Object ( Byte, Int , double etc) for the s pecified value us ing the
binary s earch algorithm . The arra y m us t be sorted prior to m aking this call. This returns index of
the s earch key, i f i t is contained in the lis t; otherwis e, (-(ins ertion point + 1).

public static boolean equals(long[] a , long[] a2)


Returns true if the two s pecified arrays of longs are equal to one another. Two arra ys are
cons idered equal if both arrays contain the s ame num ber of elem ents , and all corresponding pairs
of elements in the two arrays are equal. This returns true if the two arra ys are equal. Sam e
m ethod could be us ed by all other prem itive data types ( Byte, s hort, Int etc .)

public static void fill(int[] a , int val)


As s igns the specified int value to each elem ent of the s pecified array of ints . Same m ethod could
be used by all other premitive data types ( Byte, s hort, Int etc.)

public static void sort(Object[] a)


Sorts the specified array of objects into as cending order, according to the natural ordering of its
elem ents . Sam e m ethod could be us ed by all other prem itive data types ( Byte, s hort, Int etc.)

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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

boolean after(Date date)


Returns true if the invoking Date object contains a date that is later than the one specified by date,
otherwis e, it returns fals e.

boolean before(Date date)


Returns true if the invoking Date object contains a date that is earlier than the one specified by
date, otherwis e, i t returns fals e.

Object clone( )
Duplicates the invoking Date object.

int compareTo( Date date)


Com pares the value of the in voki ng object with that of date. Returns 0 if the values are equal.
Returns a negative value i f the in voking object is earlier than date. Returns a pos itive value i f the
invoking object is later than date.

int compareTo(Object obj)


Operates identically to com pareTo(Date) if obj is of class Date. Otherwise, it throws a
Class Cas tException.

boolean e quals(Object date)


Returns true if the invoking Date object contains the sam e tim e and date as the one s pecified by
date, otherwis e, i t returns fals e.

long getTime( )

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

Returns the num ber of m illis econds that have elapsed s ince January 1, 1970 .
8

int hash Code( )


Returns a has h code for the invoking object.

void setTime(long t ime)


Sets the time and date as specified by tim e, which repres ents an elapsed tim e in m illis econds from
m idnight, January 1 , 1970

10

String t oString( )
Converts the invoking Date object into a s tring and returns the res ult.

Getting Current Date & Time


This is very eas y to ge t curren t d ate and tim e in Java. You can us e a s im ple Date object with toString()m ethod to
print curren t date and time as follows :
import java.util.Date;
public class DateDemo {
public static void main(String args[]) {
// Instantiate a Date object
Date date = new Date();
// display time and date using toString()
System.out.println(date.toString());
}
}
This would produce following result:
Mon May 04 09:51:52 CDT 2009

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.

Date Formatting using SimpleDateFormat:


Sim pleDateForm at is a concrete class for formatting and pars ing dates in a locale-s ensitive
m anner. Sim pleDateFormat allows you to s tart b y choosing any us er -defined patterns for date-tim e
form atting. For exam ple:
import java.util.*;
import java.text.*;
public class DateDemo {
public static void main(String args[]) {

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

Date dNow = new Date( );


SimpleDateFormat ft =
new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
System.out.println("Current Date: " + ft.format(dNow));
}
}
This would produce following result:
Current Date: Sun 2004.07.18 at 04:14:09 PM PDT

Simple DateFormat format codes:


To s pecify the tim e format us e a time pattern s tring. In this pattern, all ASCII letters are res erved as
pattern letters , which are defined as the following:
Character

Description

Example

Era des ignator

AD

Year in four digits

2001

Month in year

July or 07

Day in m onth

10

Hour in A.M./P .M. (1~12)

12

Hour in day (0~23)

22

Minute in hour

30

Second in minute

55

Millisecond

234

Day in week

Tues day

Day in year

360

Day of week in m onth

2 (s econd Wed. in July)

Week in year

40

Week in m onth

A. M./P. M. m arker

PM

Hour in day (1~24)

24

Hour in A.M./P .M. (0~11)

10

Tim e zone

Eas tern Standard Tim e

'

Es cape for text

Delimiter

"

Single quote

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

Date Formatting using printf:


Date and tim e formatting can be done very eas ily using printf m ethod. You us e a two-letter form at,
s tarting with t and ending in one of the letters of the table gi ven below. For e xam ple:
import java.util.Date;
public class DateDemo {
public static void main(String args[]) {
// Instantiate a Date object
Date date = new Date();
// display time and date using toString()
String str = String.format("Current Date/Time : %tc", date );
System.out.printf(str);
}
}
This would produce following result:
Current Date/Time : Sat Dec 15 16:37:57 MST 2012
It would be a bi t s illy i f you had to s upply the date m ultiple tim es to format each part. For tha t reas on, a form at
s tring can indicate the index of the argum ent to be form atted.
The index m us t imm ediately follow the %, and it m us t be terminated by a $. For e xam ple:
import java.util.Date;
public class DateDemo {
public static void main(String args[]) {
// Instantiate a Date object
Date date = new Date();
// display time and date using toString()
System.out.printf("%1$s %2$tB %2$td, %2$tY",
"Due date:", date);
}
}
This would produce following result:
Due date: February 09, 2004
Alternati vel y, you can us e the < flag. It indicates that the sam e argument as in the preceding form at s pecification
s hould be us ed again. For exam ple:
import java.util.Date;
public class DateDemo {
public static void main(String args[]) {
// Instantiate a Date object
Date date = new Date();
// display formatted date
System.out.printf("%s %tB %<te, %<tY",

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

"Due date:", date);


}
}
This would produce following result:
Due date: February 09, 2004

Date and Time Conversion Characters:


Character

Description

Example

Com plete date and tim e

Mon Ma y 04 09:51:52 CDT


2009

F
D

ISO 8601 date


U.S. form atted date (month/day/year)

24-hour tim e

18:05:19

12-hour tim e

06:05:19 pm

24-hour tim e, no s econds

18:05

Four-digit year (with leading zeroes )

2004

Las t two digits of the year (with l eading zeroes )

04

Firs t two digits of the year (with lead ing zeroes )

20

Full m onth nam e

February

Abbre viated m onth nam e

Feb

Two-digit m onth (with leading zeroes )

02

Two-digit da y (with leading zeroes )

03

Two-digit da y (withou t leading zeroes )

Full weekday nam e

Monda y

Abbre viated weekda y nam e

Mon

Three-digit da y o f year (with leading zeroes )

069

Two-digit hour (with leading zeroes ), between 00 and 23

18

Two-digit hour (withou t leading zeroes ), betw een 0 and


23

18

2004-02-09
02/09/2004

Two-digit hour (with leading zeroes ), between 01 and 12


I
l
M
S

06
Two-digit hour (withou t leading zeroes ), betw een 1 and
12
Two-digit m inutes (with leading zeroes )

Two-digit s econds (with leading zeroes )

05
19

Three-digit m illiseconds (with leading zeroes )

047

Nine-digit nanos econds (with leading zeroes )

047000000

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

Uppercase morning or afternoon m arker

PM

Lowercase morning or afternoon m arker

pm

RFC 822 num eric offs et from GMT

-0800

Tim e zone

PST

Seconds s ince 1970-01-01 00:00:00 GMT

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.

Parsing Strings into Dates:


The Sim pleDateForm at class has s om e additional m ethods , notably pars e( ) , which tries to pars e a
s tring according to the format s tored in the given SimpleDateForm at object. For e xam ple:
import java.util.*;
import java.text.*;
public class DateDemo {
public static void main(String args[]) {
SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd");
String input = args.length == 0 ? "1818-11-11" : args[0];
System.out.print(input + " Parses as ");
Date t;
try {
t = ft.parse(input);
System.out.println(t);
} catch (ParseException e) {
System.out.println("Unparseable using " + ft);
}
}
}
A s am ple run of the above program would produce following result:
$ java DateDemo
1818-11-11 Parses as Wed Nov 11 00:00:00 GMT 1818
$ java DateDemo 2007-12-01
2007-12-01 Parses as Sat Dec 01 00:00:00 GMT 2007

Sleeping for a While:


You can s leep for any period of tim e from one m illis econd up to the lifetime of your com puter. For
exam ple, following program would s leep for 10 s econds :
import java.util.*;
public class SleepDemo {
public static void main(String args[]) {
try {

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

System.out.println(new Date( ) + "\n");


Thread.sleep(5*60*10);
System.out.println(new Date( ) + "\n");
} catch (Exception e) {
System.out.println("Got an exception!");
}
}
}
This would produce following result:
Sun May 03 18:04:41 GMT 2009
Sun May 03 18:04:51 GMT 2009

Measuring Elapsed Time:


Som etime you m ay need to meas ure point in tim e in millis econds . So let's re -write above exam ple once again:
import java.util.*;
public class DiffDemo {
public static void main(String args[]) {
try {
long start = System.currentTimeMillis( );
System.out.println(new Date( ) + "\n");
Thread.sleep(5*60*10);
System.out.println(new Date( ) + "\n");
long end = System.currentTimeMillis( );
long diff = end - start;
System.out.println("Difference is : " + diff);
} catch (Exception e) {
System.out.println("Got an exception!");
}
}
}
This would produce following result:
Sun May 03 18:16:51 GMT 2009
Sun May 03 18:16:57 GMT 2009
Difference is : 5993

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 :

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

SN Constructor w ith Description


1

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, int date)


Cons tructs a GregorianCalendar with the given date s et in the default time zone with the defaul t
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.

Gregorian Calendar(TimeZone zone)


Cons tructs a GregorianCalendar based on the current tim e in the given time zone with the defaul t
locale.

Gregorian Calendar(TimeZone zone , Loc ale aLocale)


Cons tructs a GregorianCalendar based on the current tim e in the given 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

voi d add( int field , int amount)


Adds the s pecified (signed) am ount of tim e to the given time field, bas ed on the calendar's rules .

protecte d void compute Fields()


Converts UTC as millis econds to time field values .

protected void computeTime()


Overrides Calendar Converts tim e field values to UTC as milliseconds .

boolea n e quals(Object obj)


Com pares this GregorianCalendar to an object reference.

int get( int f ield)


Gets the value for a given tim e field.

int get ActualMaximum(int field)


Return the maxim um value that this field could have, gi ven the current date.

int get ActualMinimum(int field)


Return the minim um value that this field could ha ve, gi ven the current date.

int get GreatestMinimum(int field)


Returns highes t minim um value for the gi ven field if varies .

Date get Gregorian Change()


Gets the Gregorian Calendar change date.

10

int getLeastMaximum(int field)


Returns lowes t m axim um value for the gi ven field if varies .

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

11

int getMaximum(int field)


Returns maxim um value for the gi ven field.

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

int getMinimum(int field)


Returns minim um value for the gi ven field.

16

int hashCode()
Override has hCode.

17

boolea n isLeap Year(int ye ar)


Determines if the given year is a leap year.

18

void roll(int field, boolea n up)


Adds or subtracts (up/down) a s ingle unit of tim e on the given tim e field without changing larger
fields .

19

voi d set(int field , int value)


Sets the time field with the given value .

20

void set(int year , int mont h, int date)


Sets the values for the fields year, m onth, and date.

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

void set Gregorian Change( Date date)


Sets the GregorianCalendar change date.

24

void setTime(Date date)


Sets this Calendar's current time with the given Date.

25

voi d setTimeInM illis(lon g millis)


Sets this Calendar's current time from the given long value.

26

void setTimeZone(TimeZone value)


Sets the time zone with the given time zone value.

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"};

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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

Regular Expression Syntax:


Here is the table lis ting down all the regular expression m etacharacter s yntax a vailable in Ja va :
Subexpression Matches
^

Matches beginning of line.

Match es end of line.

Matches any s ingle character e xcept newline. Using m option allows it to m atch
newline as well.

[...]

Match es any s ingle character in brackets .

[^...]

Matches any s ingle character not in brackets

\A

Begi nning of entire s tring

\z

End of entire s tring

\Z

End of entire s tring except allowable final line term inator.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

re*

Matches 0 or m ore occurrences of preceding e xpress ion.

re+

Matches 1 or m ore of the previo us thing

re?

Matches 0 or 1 occurrence of preceding e xpress ion.

re{ n}

Matches exactl y n num ber of occurrences of preceding e xpress ion.

re{ n,}

Matches n or m ore occurrences of preceding e xpress ion.

re{ n, m }

Matches at leas t n and a t mos t m occurrences of preceding expression.

a| b

Matches either a or b.

(re)

Groups regular expressions and rem em bers matched text.

(?: re)

Groups regular expressions without rem embering matched text.

(?> re)

Matches independent pattern without backtracking.

\w

Matches word characters .

\W

Matches nonword characters .

\s

Matches whitespace. Equivalent to [\t\n\r\f].

\S

Matches nonwhitespace.

\d

Matches digits . Equivalen t to [0-9].

\D

Matches nondigits .

\A

Matches beginning of s tring.

\Z

Matches end of s tring. If a new line e xis ts , it m atches jus t before newline.

\z

Matches end of s tring.

\G

Matches point where las t match finis hed.

\n

Back-reference to capture group num ber "n"

\b

Matches word boundaries when outs ide brackets . Matches backs pace (0x08) when
inside brackets .

\B

Matches nonword boundaries .

\n, \t, etc.

Matches newlines , carriage returns , tabs , etc.

\Q

Es cape (quote) all characters up to \E

\E

Ends quoting begun with \Q

Methods of the Matcher Class:


Here is the lis ts of us eful ins tance m ethods :

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

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

2
3

public int start()


Returns the s tart index o f the pre vious match.
public int start(int group)
Returns the s tart index o f the s ubs equence captured by the gi ven group during the pre vious match
operation.
public int end()
Returns the offs et after the las t character m atched.
public int end(int group)

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

public boolean looking At()


Attem pts to m atch the input sequence, s tarting at the beginning of the region, agains t the pattern .

public boolea n f ind()


Attem pts to find the next s ubs equence of the input s equence that matches the pattern.

public boolean f ind( int star t


Res ets this m atcher and then attempts to find the next s ubsequence of the input s equence that
m atches the pattern, s tarting at the s pecified index.

public boolea n matches()


Attem pts to m atch the entire region agains t the pattern.

Replacement Methods:
Replacem ent m ethods are us eful methods for replacing text in an input s tring:
SN Methods w ith Description
1

public Matcher appendReplacement(StringBuffer sb, String replacement)


Im plem ents a non-terminal append-and-replace s tep.

public String Buffer appe ndTail(String Buffer sb)


Im plem ents a terminal append-and-replace s tep.

public String replace All(String replacem ent)


Replaces every s ubsequence of the input s equence that matches the pattern with the given
replacem ent s tring.
public String replace First(String replace ment)

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 .

The start and end Methods:


Following is the example that counts the number of times the word "cats " appears in the input s tring:

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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.

The matches and lookingAt Methods:


The matches and lookingAt m ethods both attem pt to match an input sequence agains t a pattern. The difference,
however, is that matches requires the entire input s equence to be m atched, while lookingAt does not.
Both m ethods always s tart at the beginning of the input s tring. Here is the exam ple explaining the functionality:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexMatches
{
private static final String REGEX = "foo";
private static final String INPUT = "fooooooooooooooooo";
private static Pattern pattern;

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

private static Matcher matcher;


public static void main( String args[] ){
pattern = Pattern.compile(REGEX);
matcher = pattern.matcher(INPUT);
System.out.println("Current REGEX is: "+REGEX);
System.out.println("Current INPUT is: "+INPUT);
System.out.println("lookingAt(): "+matcher.lookingAt());
System.out.println("matches(): "+matcher.matches());
}
}
This would produce following result:
Current REGEX is: foo
Current INPUT is: fooooooooooooooooo
lookingAt(): true
matches(): false

The replaceFirst and replaceAll Methods:


The replaceFirs t and replaceAll m ethods replace text that m atches a given regular express ion. As their nam es
indicate, replaceFirs t replaces the firs t occurrence, and replace All replaces all occurences .
Here is the exam ple explaining the functionality:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexMatches
{
private static String REGEX = "dog";
private static String INPUT = "The dog says meow. " +
"All dogs say meow.";
private static String REPLACE = "cat";
public static void main(String[] args) {
Pattern p = Pattern.compile(REGEX);
// get a matcher object
Matcher m = p.matcher(INPUT);
INPUT = m.replaceAll(REPLACE);
System.out.println(INPUT);
}
}
This would produce following result:
The cat says meow. All cats say meow.

The appendReplacement and appendTail Methods:


The Matcher class als o provides appendReplacement and appendTail m ethods for text replacem ent.
Here is the exam ple explaining the functionality:
import java.util.regex.Matcher;
import java.util.regex.Pattern;

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

public class RegexMatches


{
private static String REGEX = "a*b";
private static String INPUT = "aabfooaabfooabfoob";
private static String REPLACE = "-";
public static void main(String[] args) {
Pattern p = Pattern.compile(REGEX);
// get a matcher object Matcher m =
p.matcher(INPUT); StringBuffer sb =
new StringBuffer(); while(m.find()){
m.appendReplacement(sb,REPLACE);
} m.appendTail(sb);
System.out.println(sb.toString());
}
}
This would produce following result:
-foo-foo-foo-

PatternSyntaxException Class Methods:


A PatternS ynta xE xception is an unchecked e xception that indicates a s yntax error in a regular e xpression pattern.
The PatternSynta xException class provides the following m ethods to help you determ ine what went wrong:
SN Methods w ith Description
1

public String get Description()


Retrieves the des cription of the error.

public int getIndex()


Retrieves the error index.

public String getPattern()


Retrieves the erroneous regular express ion pattern.

public String getMessage()


Returns a multi-line s tring containing the des cription of the s ynta x error and its index, the
erroneous regular express ion pattern, and a vis ual indication of the error inde x within the pattern .

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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 .

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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;

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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 .

The void Keyword:


This s ection s hows how to declare and invoke a voi d m ethod. Following e xam ple gives a program that declares a
m ethod nam ed printGrade and invokes it to print the grade for a gi ven s core.

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');
}
}

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

}
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.

Passing Parameters by Values:


When calling a method, you ne ed to pro vide argum ents , which m us t be given in the s ame order as
their res pective param eters in the method s pecification. This is known as param eter order ass ociation.
For exam ple, the following method prints a mess age n tim es :
public static void nPrintln(String message, int n) {
for (int i = 0; i < n; i++)
System.out.println(message);
}
Here, you can us e nPrintln("Hello", 3) to print "Hello " three tim es . The nPrintln("Hello", 3) s tatem ent pass es the
actual s tring param eter, "Hello", to the param eter, m essage; pass es 3 to n; and prints "Hello" three
tim es . However, the s tatement nPrintln(3, "Hello") would be wrong.
When you in voke a method with a param eter, the value of the argum ent is passed to the parameter. This
is referred to as pas s -by-value. If the argument is a variable rather than a literal value, the value of the variable
is pass ed to the param eter. The variable is not affected, regardless of the changes m ade to the parameter
ins ide the m ethod.
For s im plicity, Ja va programmers often s ay pass ing an argum ent x to a param eter y, which actuall y
m eans pass ing the value of x to y.

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);

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

// 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.

The Scope of Variables:


The s cope of a variable is the part of the program where the variable can be referenced . A variable defined ins ide
a m ethod is referred to as a local variable.
The s cope of a local variable s tarts from its declaration and continues to the end of the block that contains the
variable. A local variable m us t be declared before it can be us ed.
A param eter is actually a local variable. The s cope of a method param eter covers the entire m ethod.
A variable declared in the initial action part o f a for loop header has its s cope in the entire loop. But a variable
declared inside a for loop body has its s cope lim ited in the loop body from its declaration to the end of the block
that contains the variable as s hown below:

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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 .

Using Command-Line Arguments:


Som etimes you will want to pass inform ation into a program when you run it. This is accomplis hed by pass ing
comm and-line argum ents to m ain( ).
A com m and-line argum ent is the inform ation that directly follows the program 's nam e on the comm and line when
it is executed. To access the comm and-line argum ents ins ide a Java program is quite eas y.they are s tored as
s trings in the String array pass ed to main( ).

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

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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 {

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

public static void main(String args[]) {


MyClass t1 = new MyClass( 10 );
MyClass t2 = new MyClass( 20 );
System.out.println(t1.x + " " + t2.x);
}
}
This would produce following result:
10 20

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

The finalize( ) Method:


It is possible to define a m ethod that will be called jus t before an object's final d es truction by the
garbage collector. This m ethod is called finalize( ), and it can be us ed to ensure that an object term inates cleanly.
For exam ple, you m ight use finali ze( ) to m ake s ure that an open file owned b y that object is closed.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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:

Reading Console Input:


Java inpu t cons ole is accom plis hed by reading from System.in. To obtain a character-bas ed s tream that
is attached to the console, you wrap System.in in a BufferedReader object, to create a character s tream . Here
is m os t comm on s yntax to obtain BufferedReader:
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
Once BufferedReader is obtained, we can use read( ) m ethod to reach a character or readLine( ) m ethod to read
a s tring from the console.

Reading Characters from Console:


To read a character from a BufferedReader, we would read( ) m ethod whos e s ytax is as follows :
int read( ) throws IOException
Each tim e that read( ) is called, it reads a character from the input s tream and returns it as an integer value. It
returns .1 when the end of the s tream is encountered. As you can s ee, it can throw an IOException .
The following program dem ons trates read( ) by reading characters from the cons ole until the us er types a "q":
// Use a BufferedReader to read characters from the console.
import java.io.*;
public class BRRead {
public static void main(String args[]) throws IOException
{

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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

Reading Strings from Console:


To read a s tring from the keyboard, us e the vers ion of readLine( ) that is a m ember of the BufferedReader class .
Its general form is s hown here:
String readLine( ) throws IOException
The following program dem ons trates BufferedReader and the readLine( ) m ethod. The program reads
and displays lines of text until you enter the word "end":
// Read a string from console using a BufferedReader.
import java.io.*;
public class BRReadLines {
public static void main(String args[]) throws IOException
{
// Create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str;
System.out.println("Enter lines of text.");
System.out.println("Enter 'end' to quit.");
do {
str = br.readLine();
System.out.println(str);
} while(!str.equals("end"));
}
}
Here is a s ample run:
Enter lines of text.
Enter 'end' to quit.
This is line one
This is line one
This is line two

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

This is line two


end
end

Writing Console Output:


Cons ole output is mos t eas ily accomplis hed with print( ) and println( ), des cribed earlier. Thes e m ethods
are defined by the class PrintStream which is the type of the object referenced b yS ystem.out . Even
though Sys tem .out is a byte s tream , using it for s imple program output is s till acceptable.
Becaus e PrintStream is an output s tream derived from OutputStream , it als o im plem ents the low -level m ethod
write( ). Thus , write( ) can be us ed to write to the cons ole. The s im ples t form of write( ) defined by PrintStream is
s hown here:
void write(int byteval)
This m ethod writes to the s tream the byte s pecified by b yte val. Although b yte val is declared as an integer, only
the low-order eight bits are written.

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.

Reading and Writing Files:


As des cribed earlier, 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 used for writing data to a des tination.
Here is a hierarchy of class es to deal with Input and Output s treams .

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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

public void close() throw s IOException{}


This m ethod closes the file output s tream . Releas es any s ys tem res ources ass ociated with the file.
Throws an IOException.

protected void f inalize()throw s IOExceptio n {}


This m ethod cleans up the connection to the file. Ens ures that the close method of this file output
s tream is called when there are no m ore references to this s tream . Throws an IOException.

public int read(int r)throw s IOException{}


This m ethod reads the s pecified byte of data from the InputStream . Returns an int. Returns the
next b yte of data and -1 will be returned if it's end of file.

public int read(byte[] r) throw s IOException{}


This m ethod reads r.length bytes from the input s tream into an array. Returns the total number of
bytes read. If end o f file -1 will be returned .

public int a vailable() throw s IO Exception{}


Gives the number of bytes that can be read from this file input s tream . Returns an i nt.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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

public int read()


This m ethod reads the next b yte of data from the InputStream . Returns an int as the next b yte o f
data. If it is end of file then i t retu rns -1.

public int read(byte[] r , int off, int len)


This m ethod reads upto len num ber of b ytes s tarting from off from the input s tream into an array.
Returns the total num ber of bytes read. If end of file -1 will be returned.

public int available()


Gives the number of bytes that can be read from this file input s tream . Returns an int that gi ves
the number of bytes to be read.

public void mark(int read)


This s ets the current m arked pos ition in the s tream . The parameter gives the m axim um lim it of
bytes that can be read before the m arked position becom es invalid.

public long skip(lon g n)


Skips n num ber of bytes from the s tream . This returns the actual number of bytes s kipped.

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();

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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;
ByteArrayInputStream bInput = new ByteArrayInputStream(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
Y

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.

Public final int read(b yte [] b)t hrow s IOException


Reads s ome bytes from the inputs tream an s tores in to the byte array. Returns the total num ber of
bytes read into the buffer otherwis e -1 if it is end of file.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

(a) public final Boolea n readBooolean()throw s IOException,


(b) public f inal byte read Byte()throw s IOExc eption,
(c) public fina l short readShort()throw s IO Exception
(d) public f inal Int readInt()throw s IOException
These m ethods will read the bytes from the contained InputStream . Returns the next two b ytes of
the InputStream as the s pecific primitive type.

public String readLine() throw s IOException


Reads the next line o f te xt from the input s tream . It reads s uccessive bytes , con verting each b yte
s eparately into a character, until i t encou nters a line term inator or end of file; the characters read
are then returned as a String.

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")

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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

public void close() throw s IOException{}


This m ethod closes the file output s tream . Releas es any s ys tem res ources associated with the file.
Throws an IOException.

protected void f inalize()throw s IOExceptio n {}


This m ethod cleans up the connection to the file. Ens ures that the close method of this file output
s tream is called when there are no m ore references to this s tream . Throws an IOException.

public void w rite(int w )throw s IOException{}


This m ethods writes the s pecified byte to the output s tream .

public voi d w rite(byte[] w )


Writes w.length bytes from the m entioned byte arra y to the OutputS tream .

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

public void reset()


This m ethod res ets the num ber of valid b ytes of the b yte arra y output s tream to zero, s o all the
accumulated output in the s tream will be dis carded.
public byte[] to Byte Arra y()

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.

public voi d w rite(int w )


Writes the specified array to the output s tream .

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

public void w rite(byte []b, int of , int len)


Writes len num ber of bytes s tarting from offset off to the s tream .

public void w riteTo(Out putStream outSt)


Writes the entire content of this Stream to the specified s tream argument.

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

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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

public fina l voi d w rite(byte[] w , int off , int le n)throw s IOException


Writes len bytes from the s pecified byte arra y s tarting at point off , to the underl ying s tream .
Public final int w rite(byte [] b)t hrow s IOException

Writes the current number of bytes written to this data output s tream . Returns the total num ber of
bytes write into the buffer.

(a) public final voi d w riteBooolean()throw s IOExc eption,


(b) public f inal void w riteByte()throw s IOException,
(c) public fina l voi d w riteShort()throw s IOException
(d) public final voi d w riteInt()throw s IOException
These m ethods will write the s pecific prim itive type data into the output s tream as bytes .

Public void flush()t hrow s IOExc eption


Flushes the data output s tream .

public fina l voi d w riteBytes(String s) throw s IO Exception


Writes out the s tring to the underlying output s tream as a s equence of bytes . Each character in the
s tring is written out, in sequence, b y dis carding its high eight bits .

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();

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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

,
,
,
,
,

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 Navigation and I/O:


There are several other class es that we would be going through to get to know the bas ics of File Navi gation and
I/O.

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:

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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

public String get Name()


Returns the nam e of the file or directory denoted b y this abs tract pathnam e.

public String getParent()


Returns the pathnam e s tring of this abs tract pathnam e's parent, or null if this pathnam e does not
name a parent directory.

public File getParent File()


Returns the abs tract pathnam e of this abs tract pathname's parent, or null if this pathnam e does
not name a parent directory.

public String getPath()


Converts this abs tract pathnam e into a pathnam e s tring.

public boolean is Absolute()


Tes ts whether this abs tract pathname is abs olute. Returns true if this abs tract pathnam e is
absolute, fals e otherwis e

public String getAbsolutePath()


Returns the abs olute pathnam e s tring of this abs tract pathnam e.
public boolean can Read()

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

public boolean is Director y()


10 Tes ts whether the file denoted by this abs tract pathnam e is a directory. Returns true if and onl y i f
the file denoted by this abs tract pathname exis ts and is a directory; fals e otherwise.
public boolean is File()
11 Tes ts whether the file denoted by this abs tract pathnam e is a normal file. A file is normal if it is not
a directory and , in addition , s atis fies other s ys tem -dependent criteria. An y non-directory file

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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 .

public long lengt h()


13 Returns the length of the file denoted b y this abs tract pathnam e. The return value is uns pecified if
this pathnam e denotes a directory.
public boolean create New File() t hrow s IOException
14

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.

public void deleteOn Exit()


16 Reques ts that the file or directory denoted b y this abs tract pathnam e be deleted when the virtual
m achine term inates .
public String[] list()
17 Returns an array o f s trings nam ing the files and directories in the directory denoted by this
abs tract pathnam e.
public String[] list( Filename Filter filter )
18 Returns an array o f s trings nam ing the files and directories in the directory denoted by this
abs tract pathnam e that s atis fy the s pecified filter.
public File[] list Files()
20 Returns an array o f abs tract pathnam es denoting the files in the directory denoted by this abs tract
pathname.
public File[] list Files( File Filter filter )
21 Returns an array o f abs tract pathnames denoting the files and directories in the directory denoted
by this abs tract pathnam e that satis fy the s pecified filter.
public boolean mkdir()
22 Creates the directory nam ed b y this abs tract pathnam e. Returns true if and only i f the directory
was created; fals e otherwis e

23

public boolean mkdirs()


Creates the directory nam ed by this abs tract pathnam e, including any necess ary but none xis tent
paren t directories . Returns true if and onl y if the directory was created, along with all necessary
parent directories ; false otherwis e.

public boolean renameTo( File dest)


24 Renames the file denoted by this abs tract pathnam e. Returns true if and only if the renaming
s ucceeded; false otherwis e
public boolean setLastModif ied(long t im e)
25 Sets the las t-m odified time of the file or directory named by this abs tract pathnam e. Returns true if
and only i f the operation succeeded; fals e otherwis e .
26

public boolean setReadOnl y()


Marks the file or directory nam ed b y this abs tract pathnam e s o that onl y read operations are
allowed. Returns true if and onl y if the operation s ucceeded; false otherwis e.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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

public static File createTempFile(String prefix, String suffix) t hrow s IOException


Creates an empty file in the default tem porary-file directory, us ing the given prefi x and s uffix to
generate its name. Invoking this m ethod is equivalent to in voking createTem pFile(prefix, s uffix,
null). Returns abs tract pathname denoting a newly-created em pty file.

public int compareTo( File pathnam e)


Com pares two abs tract pathnam es lexicographically. Returns zero if the argum ent is equal to this
29 abs tract pathnam e, a value less than zero if this abs tract pathnam e is lexicographically less than
the argum ent, or a value greater th an zero if this abs tract pathnam e is lexicographically greater
than the argum ent.
public int compareTo(Object o)
Com pares this abs tract pathnam e to another object. Returns returns zero if the argum ent is equal
30 to this abs tract pathnam e, a value less than zero if this abs tract pathnam e is lexicographically less
than the argum ent, or a val ue greater than zero if this abs tract pathnam e is lexicographically
greater than the argum ent.

31

public boolean equals(Object obj)


Tes ts this abs tract pathname for equality with the gi ven object. Returns true if and onl y i f the
argum ent is not null and is an abs tract pathname that denotes the sam e file or directory as this
abs tract pathnam e.

public String toString()


32 Returns the pathnam e s tring of this abs tract pathnam e. This is jus t the s tring returned by the
getPath() method.

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

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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

Methods w ith Description

public int read() throw s IO Exception


Reads a s ingle character. Returns an int, which repres ents the character read.

public int read(char [] c, int offset, int len)


Reads characters into an array. Returns the num ber of characters read.

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

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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 result:
This
is
an
example

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

Methods w ith Description

public void w rite(int c) throw s IOException


Writes a s ingle character.

public voi d w rite(char [] c, int offset, int len)


Writes a portion of an array o f characters s tarting from offset and with a length of len.

public voi d w rite(String s , int offset, int len)


Write a portion of a String s tarting from offs et and with a length of len.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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();
}

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

}
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

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

CHAPTER

19
Java Exceptions

n exception is a problem that aris es during the execution of a program . An e xception can occur for

m any different reas ons , including the following:

A us er has entered invalid data.

A file tha t needs to be opened cannot be found.

A network connection has been los t in the m iddle of comm unications , or the JVM has run out of mem ory.

Some of thes e exceptions

are caus ed by us er error, others b y programmer error, a nd

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 .

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

Here is a lis t of m os t comm on checked and unchecked Java's Built-in Exceptions.

Javas Built-in Excepti ons


Java defines s everal exception class es inside the s tandard package java.lang.
The mos t general of these exceptions are subclass es of the s tandard type Runtim eException . Since ja va.lang is
im plicitly im ported into all Ja va programs , m os t exceptions deri ved from
Runtim eException are
autom atically available .
Java defines s everal other types of e xceptions that relate to its various class libraries . Following is the lis t of Ja va
Unchecked Runtim eException.
Exceptio n

Description

Arithm eticException

Arithm etic error, s uch as divide-by-zero .

Arra yInde xOutOfBounds Exce ption

Arra y inde x is out-of-bounds .

Arra yStoreException

As s ignm ent to an array elem ent of an incom patible type .

Class Cas tException

In valid cas t.

IllegalArgumentException

Illegal argum ent used to invoke a m ethod.

IllegalMonitorStateException

Illegal m onitor operation, s uch as waiting on an unlocked thread.

IllegalStateException

En vironm ent or application is in incorrect s tate.

IllegalThreadStateException

Reques ted operation not compatible with current thread s tate.

IndexOutOfBounds Exception

Some type of inde x is out-of-bounds .

Negative Arra ySi zeException

Arra y created with a negati ve s ize.

NullPointerException

In valid us e of a null reference.

Num berForm atException

In valid con vers ion of a s tring to a numeric form at.

SecurityException

Attem pt to violate s ecurity.

StringIndexOutOfBounds

Attem pt to inde x outs ide the bounds of a s tring.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

Uns upportedOperationException

An uns upported operation was encountered.

Following is the lis t of Ja va Checked Exceptions Defined in java.lang.


Exceptio n

Description

Class NotFoundException

Class not found.

CloneNotSupportedExcepti on

Attem pt to clone an object tha t does not im plem ent the Cloneable
interface.

IllegalAccess Exception

Acces s to a class is denied.

Ins tantiationException

Attem pt to create an object o f an abs tract class or interface.

InterruptedException

One thread has been interrupted by another thread.

NoSuchFieldException

A reques ted field does not exis t.

NoSuchMethodException

A reques ted m ethod does not exis t.

Exceptions Methods:
Following is the lis t of important m ethods available in the Throwable class .
SN Methods w ith Description
1

public String getMessage()


Returns a detailed m essage about the e xception that has occurred. This m essage is initialized in
the Throwable cons tructor.

public Throw able getCause()


Returns the caus e of the excepti on as repres ented by a Throwable object.

public String toString()


Returns the nam e of the class concatenated with the res ult of getMess age()

public voi d printStackTrace()


Prints the res ult of toString() along with the s tack trace to Sys tem .err, the error output s tream .
public StackTraceElement [] getStackTrac e()

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

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

}
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

Multiple catch Blocks:


A tr y block can be followed b y m ultiple catch blocks . The s ynta x for m ultiple catch blocks looks like the following:
try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}
The previous s tatem ents dem ons trate three catch blocks , but you can ha ve an y number of them after a s ingle try.
If an exception occurs in the protected code, the exception is thrown to the firs t catch block in the lis t. If the data
type o f the e xception thrown matches ExceptionType1 , it gets caught there. If not, the e xce ption passes down to
the s econd catch s tatem ent. This continues until the exception either is caught or falls through all catches ,
in which cas e the current m ethod s tops execution and the e xception is thrown down to the pre vious method on
the call s tack.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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;
}

The throws/throw Keywords:


If a m ethod does not handle a checked e xception, the m ethod m us t declare it us ing the throw skeyword.
The throws keyword appears at the end of a m ethod's signature.
You can throw an e xception , either a newl y ins tantiated one or an exception tha t you jus t caught, b y
using the throw keyword. Try to und ers tand the different in throws and throw keywords .
The following m ethod declares that it throws a Rem oteException:
import java.io.*;
public class className
{
public void deposit(double amount) throws RemoteException
{
// Method implementation
throw new RemoteException();
}
//Remainder of class definition
}
A m ethod can declare that it throws m ore than one exception, in which cas e the exceptions are declared in a lis t
s eparated by comm as . For exam ple, the following m ethod declares that it throws a Rem oteException and
an Ins ufficientFunds Exception:
import java.io.*;
public class className
{
public void withdraw(double amount) throws RemoteException,
InsufficientFundsException
{
// Method implementation
}
//Remainder of class definition
}

The finally Keyword


The finally ke yword is us ed to create a block of code that follows a tr y block. A finall y block o f code
always executes , whether or not an e xception has occurred.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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:

A catch claus e cannot e xis t witho ut a try s tatem ent.

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 .

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

Declaring you own Exception:


You can create your own e xceptions in Ja va. Keep the following points in mind when writing your own exception
class es :

All e xceptions mus t be a child of Throwable.

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 .

We can define our own Exception class as below:


class MyException extends Exception{
}
You jus t need to e xtend the Exception class to create your own Exception class . Thes e are considered to be
checked exceptions . The following InsufficientFunds Exception class is a us er -defined exception that e xtends the
Exception class , m aking it a checked exceptio n. An e xception clas s is like any other class , containing useful fields
and methods .

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;
}

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

public void withdraw(double amount) throws


InsufficientFundsException
{
if(amount <= balance)
{
balance -= amount;
}
else
{
double needs = amount - balance;
throw new InsufficientFundsException(needs);
}
}
public double getBalance()
{
return balance;
}
public int getNumber()
{
return number;
}
}
The following BankDem o pro gram dem ons trates invoking the depos it() and withdraw() m ethods of
CheckingAccount.
// File Name BankDemo.java
public class BankDemo
{
public static void main(String [] args)
{
CheckingAccount c = new CheckingAccount(101);
System.out.println("Depositing $500...");
c.deposit(500.00);
try
{
System. out. print ln( " \nW ith draw ing $100...");
c.withdraw(100.00);
System.out.println("\nWithdrawing $600...");
c.withdraw(600.00);
}catch(InsufficientFundsException e)
{
System.out.println("Sorry, but you are short $"
+ e.getAmount());
e.printStackTrace();
}
}
}
Com pile all the above three files and run BankDemo, this would produce following res ult:
Depositing $500...
Withdrawing $100...
Withdrawing $600...
Sorry, but you are short $200.0
InsufficientFundsException
at CheckingAccount.withdraw(CheckingAccount.java:25)
at BankDemo.main(BankDemo.java:13)

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

CHAPTER

20
Java Inheritance

nheritance can be defined as the process where one object acquires the properties of another. With the us e

of inheritance the inform ation is made m anageable in a hierarchical order.


When we talk about inheritance the mos t commonly us ed keyword would be extends and implements. These
words would determine whether one object IS- A t ype of another. B y us ing these keywords we can make
one object acquire the properties of another object.

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:

Anim al is the s uperclass of Mamm al class .

Anim al is the s uperclass of Reptile class .

Mam mal and Reptile are s ub class es of Anim al class .

Dog is the subclass of both Mamm al and Anim al class es .

Now if we cons ider the IS-A relationship we can s ay:

Mam mal IS-A Anim al

Reptile IS-A Anim al

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

Dog IS-A Mam m al

Hence : Dog IS-A Anim al as well

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{
}

The instanceof Keyword:


Let us us e the instanceof operator to check determ ine whether Mam mal is actually an Anim al, and dog
is actually an Anim al
interface Animal{}
class Mammal implements Animal{}
public class Dog extends Mammal{
public static void main(String args[]){

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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

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

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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
}

This would produce following result:

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

Animals can move


Dogs can walk and run
In the above e xam ple you can s ee that the even though b is a type of Animal it runs the move method in the Dog
class . The reason for this is : In com pile time the check is m ade on the reference type. Howe ver in the ru ntim e
JVM figures out the object type and wou ld run the m ethod that belongs to that particular object.
Therefore in the above e xam ple, the program will com pile properly since Animal class has the m ethod
m ove. Then at the runtime it runs the m ethod s pecific for that object.
Cons ider the following exam 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 void bark(){
System.out.println("Dogs can bark");
}
}
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
b.bark();
}
}
This would produce following result:
TestDog.java:30: cannot find symbol
symbol : method bark()
location: class Animal
b.bark();
^
This program will throw a com pile tim e error s ince b's reference type Anim al does n't have a m ethod b y the nam e
of bark.

Rules for method overriding:


The argum ent lis t s hould be exactly the s am e as that of the o verridden m ethod.
The return type s hould be the s am e or a s ubtype of the return t ype declared in the original o verridden m ethod
in the super class .

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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.

Cons tructors cannot be overridden .

Using the super keyword:


When invoking a s uperclass version of an o verridden m ethod the super keyword is us ed.
class Animal{
public void move(){
System.out.println("Animals can move");
}
}
class Dog extends Animal{
public void move(){
super.move(); // invokes the super class method
System.out.println("Dogs can walk and run");
}
}
public class TestDog{
public static void main(String args[]){
Animal b = new Dog(); // Animal reference but Dog object
b.move(); //Runs the method in Dog class
}
}
This would produce following result:
Animals can move
Dogs can walk and run

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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:

A Deer IS- A Animal

A Deer IS- A Vegetarian

A Deer IS- A Deer

A Deer IS- A Object

When we apply the reference variable facts to a Deer object reference, the following declarations are legal:
Deer d = new Deer();
Animal a = d;
Vegetarian v = d;

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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;
}

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

public String getName()


{
return name;
}
public String getAddress()
{
return address;
}
public void setAddress(String newAddress)
{
address = newAddress;
}
public int getNumber()
{
return number;
}
}
Notice that nothing is different in this Em ployee class . The class is now abs tract, but i t s till has three fields , s even
m ethods , and one cons tructor.
Now if you would try as follows :
/* File name : AbstractDemo.java */
public class AbstractDemo
{
public static void main(String [] args)
{
/* Following is not allowed and would raise error */
Employee e = new Employee("George W.", "Houston, TX", 43);
System.out.println("\n Call mailCheck using
Employee reference--");
e.mailCheck();
}
}
When you would com pile above class then you would get following error:
Employee.java:46: Employee is abstract; cannot be instantiated
Employee e = new Employee("George W.", "Houston, TX", 43);
^
1 error

Extending Abstract Class:


We can extend Em ployee class in norm al way 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()
{

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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;
}
}
Here we cannot ins tantiate a new Em ployee, but if we ins tantiate a new Salary object, the Salary object will inheri t
the three fields and seven m ethods from Em ployee.
/* File name : AbstractDemo.java */
public class AbstractDemo
{
public static void main(String [] args)
{
Salary s = new Salary("Mohd Mohtashim", "Ambehta,
3, 3600.00);
Salary e = new Salary("John Adams", "Boston, MA",
2, 2400.00);

UP",

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.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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
}

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

CHAPTER

24
Java Encapsulation

ncapsulation is one of the four fundam ental OOP concepts . The other three are inheritance,

polym orphism , and abs traction.


Encaps ulation is the technique of m aking the fields in a class private and providing access to the fields via public
m ethods . If a field is declared private, it cannot be accessed by anyone outs ide the class , thereby hiding the fields
within the class . For this reason, encapsulation is also referred to as data hiding.
Encaps ulation can be des cribed as a protective barrier that pre vents the code and data being random ly accessed
by other code defined outside the class . Access to the data and code is tightly controlled by an interface .
The m ain benefit of encaps ulation is the ability to m odify our im plem ented code without breaking the code
of others who us e our code. With this feature Encapsulation gives m aintainability, flexibility and extens ibility to
our code.

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;
}

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

public void setName(String newName){


name = newName;
}
public void setIdNum( String newId){
idNum = newId;
}
}
The public m ethods are the access points to this class 's fields from the outs ide java world. Norm ally
these m ethods are referred as getters and s etters . Therefore any class that wants to access the variables
s hould access them through thes e getters and s etters .
The variables of the EncapTes t class can be access as below:
/* File name : RunEncap.java */
public class RunEncap{
public static void main(String args[]){
EncapTest encap = new EncapTest();
encap.setName("James");
encap.setAge(20);
encap.setIdNum("12343ms");
System.out.print("Name : " + encap.getName()+
" Age : "+ encap.getAge());
}
}
This would produce following result:
Name : James Age : 20

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.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

CHAPTER

25
Java Interfaces

n interface is a collection of abs tract methods . A clas s im plem ents an interface, thereby inheriting the

abs tract m ethods of the interface.


An interface is not a class . Writing an interface is s im ilar to writing a class , but they are two different concepts . A
class des cribes the attributes and behaviors of an object. An i nterface contains behaviors that a class
im plem ents .
Unless the class that im plem ents the interface is abs tract, all the m ethods of the interface need to be defined in
the class .
An interface is s im ilar to a class in the following ways :

An interface can contain an y num ber of m ethods .


An interface is written in a file with a .java e xtens ion, with the nam e of the interface m atching the nam e of the
file.

The b ytecode o f an interface appears in a .class file.


Interfaces appear in packages , and their corres ponding bytecode file m us t be in a directory s tructure
that m atches the package nam e.
However, an interface is different from a class in s everal ways , including:

You cannot ins tantiate an interface.


An interface does not contain an y co ns tructors .
All of the m ethods in an interface are abs tract.
An interface canno t contain ins tance fields . The onl y fields that can appear in an interface m us t be declared
both s tatic and final.

An interface is not e xtended b y a class ; it is im plem ented by a class .


An interface can e xtend m ultiple interfaces .

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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;
}

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

public static void main(String args[]){


MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}
This would produce following result:
Mammal eats
Mammal travels
When overriding m ethods defined in interfaces there are several rules to be followed:

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 :

A class can im plem ent m ore than one interface at a tim e.


A class can extend only one class , but im plem ent m any interface.
An interface can e xtend another interface, s im ilarly to the way that a clas s can extend another class .

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();

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

public void endOfPeriod(int period);


public void overtimePeriod(int ot);
}
The Hockey interface has four methods , but it inherits two from Sports ; thus , a class that im plem ents Ho
ckey needs to implement all s ix m ethods . Sim ilarly, a class that im plem ents Football needs to define the three
m ethods from Football and the two m ethods from Sports .

Extending Multiple Interfaces:


A Ja va class can only e xtend one paren t class . Multiple inheritance is not allowed. Interfaces are not class es ,
however, and an interface can e xtend m ore than one parent interface.
The extends keyword is us ed once, and the parent interfaces are declared in a comma -separated lis t.
For exam ple, i f the Hocke y interface e xtended both Sports and Event, it would be declared as :
public interface Hockey extends Sports, Event

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 .

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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:

java .lang - bundles the fundamental classes


java .io - clas ses for input , outpu t functions are bundled in this package
Programm ers can define their own packages to bundle group of class es /interfaces etc. It is a good practice to
group related classes im plem ented by you s o that a programmers can eas ily determ ine that the class es ,
interfaces , enum erations , annotations are related.
Since the package creates a new names pace there won't be an y name conflicts with nam es in other packages .
Using packages , it is eas ier to provide access control and it is als o easier to locate the related classed.

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();

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

}
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

The import Keyword:


If a class wants to us e another class in the s ame package, the package name does not need to be used. Class es
in the same package find each other without an y s pecial s yntax.

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:

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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 Directory Structure of Packages:


Two m ajor res ults occur when a class is placed in a package:

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 .

Here is sim ple way of m anaging your files in java:


Put the s ource code for a class , interface, enumeration, or annotation type in a te xt file whos e name is the sim ple
name of the type and whose extens ion is .java. For e xam ple:
// File Name :

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:

Class name -> vehicle.Car

Path name -> vehicle\Car.java (in windows )

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

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

For exam ple:


// File Name: Dell.java
package com.apple.computers;
public class Dell{
}
class Ups{
}
Now compile this file as follows us ing -d option:
$javac -d . Dell.java
This would put compiled files as follows :
.\com\apple\computers\Dell.class
.\com\apple\computers\Ups.class
You can im port all the class es or interfaces defined in \com \apple\com puters\ as follows :
import com.apple.computers.*;
Like the .java s ource files , the com piled .class files s hould be in a series of directories that reflect the package
name. However, the path to the .class files does not have to be the sam e as the path to the .java s ource files .
You can arrange your s ource and class directories s eparately, as :
<path-one>\sources\com\apple\computers\Dell.java
<path-two>\classes\com\apple\computers\Dell.class
By doing this , it is possible to give the class es directory to other programm ers without revealing your s ources . You
also need to manage s ource and class files in this manner s o that the com piler and the Java Virtual Machine
(JVM) can find all the t ypes your program us es .
The full path to the classes directory, <path-two>\class es , is called the class path, and is s et with the
CLASSPATH s ys tem variable. Both the com piler and the JVM cons truct the path to your .class files by adding the
package nam e to the class path.
Say <path-two>\class es is the class path, and the package nam e is com .apple.com puters , then the com piler and
JVM will look for .class files in <path-two>\classes \com \apple\com ptuers .
A class path m ay include s everal paths . Multiple paths should be separated by a s em icolon (Windows ) or colon
(Unix). By default, the compiler and the JVM s earch the current directory and the JAR file containing the Ja va
platform class es s o that thes e directories are autom atically in the class path.

Set CLASSPATH System Variable:


To dis play the current CL ASSPATH variable, us e the following comm ands in Windows and Unix (Bourne s hell):

In Windows -> C:\> s et CLASSP ATH

In Uni x -> % echo $CL ASSPATH

To delete the current contents of the CL ASSPATH variable, use :

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

In Windows -> C:\> s et CLASSP ATH =

In Uni x -> % uns et CL ASSPATH ; e xport CL ASSP ATH

To s et the CLASSPATH variable :

In Windows -> s et CLASSPATH=C:\us ers \jack\java\classes

In Uni x -> % CL ASSP ATH=/hom e/jack/ja va/class es ; export CL ASSP ATH

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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:

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

SN Methods w ith Description


1

boolean hasMore Elements( )


When implem ented, it mus t return true while there are s till more elem ents to extract, and fals e
when all the elements have been enum erated.

Object next Element( )


This returns the next object in the enum eration as a generic Object reference.

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:

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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

void and( Bit Set bitSet)


ANDs the contents of the invoking BitSet object with those specified by bitSet. The res ult is placed
into the invoking object.

void and Not( Bit Set bitSet)


For each 1 bit in bitSet, the corres ponding bit in the in voking BitSet is cleared.

int cardinality( )
Returns the num ber of s et bits in the invoking object.

void clear( )
Zeros all bits .

void clear(int index)


Zeros the bit s pecified by index.

voi d clear(int startIndex , int en dIndex)


Zeros the bits from s tartIndex to endInde x.1.

Object clone( )
Duplicates the invoking BitSet object.

boolean e quals(Object bitSet)


Returns true if the invoking bi t set is equivalent to the one pass ed in bitSet. Otherwise, the m ethod
returns false.

void flip(int index)


Revers es the bit s pecified by index. (

10

voi d flip( int startIndex , int endIndex)


Revers es the bits from s tartIndex to endInde x.1.

11

boolea n get(int index)


Returns the current s tate of the bit at the s pecified index.

BitSet get( int startIndex , int endIndex)


12 Returns a BitSet tha t consis ts of the bits from s tartIndex to endIndex.1. The in voking object is not
changed.
13

int hashCode( )
Returns the has h code for the invoking object.

14

boolean intersects(BitSet bitSet)


Returns true if at leas t one pair o f corresponding bits within the invoking object and bitSe t are 1 .

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.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

int next Clear Bit(int startIndex)


17 Returns the index o f the ne xt cleared bit, (that is , the ne xt zero bit), s tarting from the index
s pecified by s tartIndex
int nextSetBit(int startIndex)
18 Returns the index o f the ne xt s et bit (that is , the ne xt 1 bit), s tarting from the index s pecified by
s tartIndex. If no bi t is s et, .1 is returned.
void or( BitSet bitSet)
19 ORs the contents of the invo king BitSet object with that s pecified by bitSet. The res ult is placed
into the invoking object.
20

void set(int index)


Sets the bit specified by index.

21

voi d set(int index , boolea n v)


Sets the bit specified by index to the value passed in v. true s ets the bit, fals e clears the bit.

22

voi d set(int startIndex , int endI ndex)


Sets the bits from s tartIndex to endInde x.1.

void set(int startIndex , int endIndex , boolean v)


23 Sets the bits from s tartIndex to endInde x.1, to the value pass ed in v. true s ets the bits , false clears
the bits .
24

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);

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

// 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:

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

Vector(int size, int incr)


The fourth form creates a vector that contains the elements of collection c:
Vector(Collection c)
Apart from the methods inherited from its parent class es , Vector defines following m ethods :
SN Methods w ith Description
1

void add( int index , Object element)


Ins erts the s pecified elem ent at the specified pos ition in this Vector.

boolea n a dd(Object o)
Appends the s pecified element to the end of this Vector.

boolean add All( Collection c)


Appends all of the elements in the specified Collection to the end of this Vector, in the order tha t
they are returned b y the s pecified Collection's Iterator.

boolea n a ddAll( int index , Colle ction c)


Ins erts all of the elem ents in in the s pecified Collection into this Vector at the s pecified pos ition.

void add Element(Object obj)


Adds the s pecified com ponent to the end of this vector, increasing its s ize by one.

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.

boolea n c ontains(Object elem)


Tes ts if the s pecified object is a com ponent in this vector.

10

boolean contains All( Collection c)


Returns true if this Vector contains all of the elem ents in the s pecified Collection.

11

void copyInto(Object[] an Arra y)


Copies the components of this vector into the s pecified array.

12

Object elementAt(int index)


Returns the com ponent at the s pecified index.

13

Enumeration elements()
Returns an enum eration of the components of this vector.

void ensure Capacity(int m inCapacit y)


14 Increas es the capacity of this vector, if necessary, to ens ure that it can hold at leas t the num ber of
components specified by the m inim um capacity argum ent.
15

boolean equals(Object o)
Com pares the s pecified Object with this Vector for equality.

16

Object first Element()


Returns the firs t com ponent (the item at inde x 0) of this vector.

17

Object get(int index)


Returns the element at the s pecified pos ition in this Vector.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

18

int hashCode()
Returns the has h code value for this Vector.

int indexOf(Object elem)


19 Searches for the firs t occurence of the gi ven argum ent, tes ting for equality us ing the equals
m ethod.
int indexOf(Object elem, int index)
20 Searches for the firs t occurence of the gi ven argum ent, beginning the s earch at inde x, and tes ting
for equality us ing the equals m ethod.
21

void insertElementAt( Object o bj, int index)


Ins erts the s pecified object as a component in this vector at the s pecified index.

22

boolean is Empty()
Tes ts if this vector has no com ponents .

23

Object last Element()


Returns the las t com ponent of the vector.

24

int lastIndexOf(Object elem)


Returns the index of the las t occurrence of the specified object in this vector.

int lastIndexOf(Object elem, int index)


25 Searches backwards for the s pecified object, s tarting from the specified index, and returns an
index to it.
26

Object remove(int index)


Rem oves the elem ent at the specified pos ition in this Vector.

boolean remo ve(Object o)


27 Rem oves the firs t occurrence of the specified element in this Vector If the Vector does not contain
the elem ent, it is unchanged.
28

boolean remove All(Collectio n c)


Rem oves from this Vector all of its elem ents that are contained in the s pecified Collection.

29

void remove All Elements()


Rem oves all com ponents from this vector and s ets its s ize to zero.

30

boolea n remove Element(Obje ct obj)


Rem oves the firs t (lowes t-indexed) occurrence of the argument from this vector.

31

voi d remove ElementAt( int index)


rem oveElementAt(int inde x)

protected void remove Range(int fromIndex , int toIndex)


32 Rem oves from this Lis t all of the elem ents whos e index is between from Index, inclus ive and
toIndex, e xclus ive .
33

boolean retainAll(Collectio n c)
Retains only the elements in this Vector that are contained in the s pecified Collection.

34

Object set(int index , Object ele ment)


Replaces the element at the s pecified pos ition in this Vector with the s pecified element.

35

void set ElementAt(Object obj, int inde x)


Sets the com ponent at the specified inde x of this vector to be the s pecified object.

36

voi d setSize(int new Size)


Sets the size of this vector.

37

int size()

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

Returns the num ber of components in this vector.


38

List subList(int fromIndex , int t oIndex)


Returns a view of the portion o f this Lis t between from Index, inclus ive, and toInde x, e xclus ive .

39

Object[] to Arra y()


Returns an array containing all of the elements in this Vector in the correct order.

Object[] toArra y(Object[] a)


40 Returns an array containing all of the elements in this Vector in the correct order; the runtim e type
of the returned arra y is that o f the s pecified array.
String t oString()
41 Returns a s tring repres entation of this Vector, containing the String repres entation of each
elem ent.
42

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();

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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

boolean empt y()


Tes ts if this s tack is em pty. Returns true if the s tack is em pty, and returns fals e if the s tack
contains elem ents .

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 .

Object push(Object element)


Pus hes element onto the s tack. elem ent is also returned.

int search(Object element)


Searches for element in the s tack. If found, its offs et from the top of the s tack is returned.
Otherwis e, .1 is returned.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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 .

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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.

Object get(Object key)


Returns the object that contains the value as sociated with key. If ke y is not in the dictionary, a null
object is returned.

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 put(Object key, Object value)


Ins erts a key and its value into the dictionary. Returns null if ke y is not alread y in the dictionary;
returns the previous value ass ociated with key if ke y is already 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.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

SN Methods w ith Description


1

voi d clear( )
Rem oves all key/value pairs from the invoking map.

boolea n contains Ke y(Object k)


Returns true if the invoking m ap contains k as a key. Otherwis e, returns fals e.

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.

boolean e quals(Object obj)


Returns true if obj is a Map and contains the sam e entries . Otherwis e, returns fals e.

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");

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

voi d clear( )
Res ets and em pties the has h table.

Object clone( )
Returns a duplicate of the invoki ng object.

boolean c ontains(Object value)


Returns true if s ome value equal to value e xis ts within the has h table. Returns fals e if the value
is n't found.
boolean c ontains Ke y(Object ke y)

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.

boolean c ontainsValue(Object value)


Returns true if s ome value equal to value e xis ts within the hash table. Returns fals e if the value
is n't found.

Enumeration elements( )
Returns an enum eration of the valu es contained in the hash table.

Object get(Object key)


Returns the object that contains the value ass ociated with key. If ke y is not in the has h table, a null
object is returned.

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

Object put(Object key, Object value)


Ins erts a key and a value into the has h table. Returns null if ke y is n't alread y in the has h table;
returns the previous value ass ociated with key if ke y is already in the hash table.

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;

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

balance.put("Zara", new Double(3434.34));


balance.put("Mahnaz", new Double(123.22));
balance.put("Ayan", new Double(1378.00));
balance.put("Daisy", new Double(99.22));
balance.put("Qadir", new Double(-19.08));
// Show all balances in hash table.
names = balance.keys();
while(names.hasMoreElements()) {
str = (String) names.nextElement();
System.out.println(str + ": " +
balance.get(str));
}
System.out.println();
// Deposit 1,000 into Zara's account
bal = ((Double)balance.get("Zara")).doubleValue();
balance.put("Zara", new Double(bal+1000));
System.out.println("Zara's new balance: " +
balance.get("Zara"));
}
}
This would produce following result:
Qadir: -19.08
Zara: 3434.34
Mahnaz: 123.22
Daisy: 99.22
Ayan: 1378.0
Zara's new balance: 4434.34

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:

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

Properties(Properties propDefault)
Apart from the methods defined by Has htable, Properties defines following m ethods :
SN Methods w ith Description
1

String getPropert y(String ke y)


Returns the value ass ociated with key. A null object is returned if ke y is neither in the lis t nor in the
default property lis t.

String getPropert y(String ke y, String defaultProperty)


Returns the value ass ociated with key. defaultProperty is returned if ke y is neither in the lis t nor in
the default property lis t.

voi d list(PrintStream streamOut)


Sends the property lis t to the output s tream linked to s tream Out.

void list(PrintW riter streamOut)


Sends the property lis t to the output s tream linked to s tream Out.

voi d load(InputStream str eamIn) throw s IOException


Inputs a property lis t from the input s tream linked to s tream In.
Enumeration propertyNames( )

Returns an enum eration of the ke ys . This includes thos e keys found in the default property lis t,
too.

Object setProperty(String ke y, Strin g value)


As s ociates value with key. Returns the pre vious value associated with key, or returns null if no
s uch association exis ts .

void store(Out putStream streamOut, String description)


After writing the s tring specified by des cription, the property lis t is written to the output s tream
linked to s tream Out.

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) + ".");
}

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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

Missouri is Jefferson City.


Illinois is Springfield.
Indiana is Indianapolis.
California is Sacramento.
Washington is Olympia.

The capital of Florida is Not Found.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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.

Extending and/or adapting a collection had to be eas y.

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 .

The Collection Interfaces:


The collections framework defines s everal interfaces . This s ection provides an overview o f each interface :
SN Interfaces w ith Description
1

The Collection Interface

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

This enables you to work with groups of objects ; it is at the top of the collections hierarchy.
2

The Lis t Interface


This extends Collection and an i ns tance of Lis t s tores an ordered collection of elem ents .

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 Sorted Map


This extends Map s o that the keys are maintained in as cending order.

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.

The Collection Classes:


Java pro vides a set of s tandard collection classes that im plement Collection interfaces . Som e of the
class es provide full im plem entations that can be us ed as -is and others are abs tract class , providing
s keletal im plementations that are used as s tarting points for creating concrete collections .
The s tandard collection class es are summ arized in the following table:
SN Classes w ith Description
1

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.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

The Ab stractCollection, Ab stractSet, Ab stractList, Ab stractSequentialList and Ab stractMap class es


provide s keletal implementations of the core collection interfaces , to m inimize the effort required to implement
them .
The following legacy classes defined by ja va.util has been dis cuss ed in previous tutorial:
SN Classes w ith Description
1

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.

The Collection Algorithms:


The collections framework defines s everal algorithms that can be applied to collections and m aps . These
algorithms are defined as s tatic methods within the Collections class .
Several o f the m ethods can throw a Class CastException, which occurs when an attem pt is m ade to compare
incom patible types , or an UnsupportedOperation Exception, which occurs when an attem pt is m ade to m odify
an unm odifiable collection.
Collections defines three s tatic variables : EMPTY_SET, E MPT Y_LIST, and EMPT Y_ MAP . All are im mutable.
SN

Algorithms w ith Description

The Collection Algorithms


Here is a lis t of all the algorithm im plem entation.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

How to use an Iterator?


Often, you will wan t to cycle through the elem ents in a collection. For e xam ple, you m ight wan t to dis play each
elem ent.
The easies t way to do this is to em ploy an iterator, which is an object that im plem ents either the Iterator or the
Lis tIterator interface.
Iterator enables you to cycle through a collection, obtaining or rem oving elem ents . Lis tIterator extends Iterator to
allow bidirectional travers al of a lis t, a nd the m odification of elements .
SN

Iterator Methods w ith Description

Using Java Iterator


Here is a lis t of all the methods with exam ples provided by Iterator and Lis tIterator interfaces .

How to use an Comparator?


Both TreeSet and Tree Map s tore elements in s orted order. Howe ver, it is the comparator that defines precis ely
what sorted order m eans .
This interface lets us s ort a given coll ection an y num ber of different wa ys . Also this interface can be us ed to s ort
any ins tances of any class .(even clas ses we cannot modify).
SN

Iterator Methods w ith Des cription

Using Java Com parator


Here is a lis t of all the methods with exam ples provided by Comparator Interface.

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.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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

String array or an arra y o f an y t ype that s upports ordering.


Java Generic m ethods and generic classes enable programm ers to s pecify, with a s ingle m ethod declaration, a
s et of related m ethods or, with a s ingle class declaration, a s et of related types , res pectivel y.
Generics als o provide com pile-tim e type s afety that allows programmers to catch invalid types at compile time.
Using Java Generic concept we m ight write a generic m ethod for s orting an array of objects , then in voke
the generic m ethod with Integer arrays , Double arra ys , String arra ys and s o on, to sort the array elements .

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 )
{

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

// Display array elements


for ( E element : inputArray ){
System.out.printf( "%s ", element );
}
System.out.println();
}
public static void main( String args[] )
{
// Create arrays of Integer, Double and Character
Integer[] intArray = { 1, 2, 3, 4, 5 }; Double[]
doubleArray = { 1.1, 2.2, 3.3, 4.4 }; Character[]
charArray = { 'H', 'E', 'L', 'L', 'O' };
System.out.println( "Array integerArray contains:" );
printArray( intArray ); // pass an Integer array
System.out.println( "\nArray doubleArray contains:" );
printArray( doubleArray ); // pass a Double array
System.out.println( "\nArray characterArray contains:" );
printArray( charArray ); // pass a Character array
}
}
This would produce following result:
Array integerArray contains:
1 2 3 4 5 6
Array doubleArray contains:
1.1 2.2 3.3 4.4
Array characterArray contains:
H E L L O

Bounded Type Parameters:


There m ay be times when you'll wan t to res trict the kinds of types that are allowed to be pass ed to a
type parameter. For exam ple, a m ethod that operates on num bers m ight only want to accept ins tances of
Num ber or its s ubclass es . This is what bounded type parameters are for.
To declare a bounded type param eter, lis t the type parameter's nam e, followed by the e xtends keyword , followed
by its upper bound.

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

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

}
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"));

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

System.out.printf("Integer Value :%d\n\n", integerBox.get());


System.out.printf("String Value :%s\n", stringBox.get());
}
}
This would produce following result:
Integer Value :10
String Value :Hello World

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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);
}

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

}
Notice that for a class to be s erialized s uccess fully, two conditions m us t be m et:

The class m us t im plement the java.io.Seriali zable interface.

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)

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

{
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.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

URL Class Methods:


The java.net. URL clas s repres ents a URL and has com plete set of m ethods to m anipulate URL in Java.
The URL class has s everal cons tructors for creating URLs , including the following:
SN Methods w ith Description

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.

public URL(String url) t hrow s MalformedURL Exception


Creates a URL from the given String

public URL(URL context, String url) throw s MalformedURL Exception


Creates a URL by pars ing the together the URL and String argum ents

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

Methods w ith Description

public String getPath()


Returns the path of the URL.

public String getQuer y()


Returns the query part o f the URL.

public String getAuthority()


Returns the authority of the URL .

public int getPort()


Returns the port of the URL .

public int get DefaultPort()


Returns the default port for the protocol of the URL.

public String getProtocol()


Returns the protocol of the URL.

public String get Host()


Returns the hos t of the URL .

public String get Host()


Returns the hos t of the URL .

public String get File()


Returns the filenam e of the URL.

10

public String get Ref()


Returns the reference part of the URL.

11

public URLConnectio n openConne ction() throw s IOException


Opens a connection to the URL, allowing a client to comm unicate with the res ource.

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.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

// File Name : URLDemo.java


import java.net.*;
import java.io.*;
public class URLDemo
{
public static void main(String [] args)
{
try
{
URL url = new URL(args[0]);
System.out.println("URL is " + url.toString());
System.out.println("protocol is "
+ url.getProtocol());
System.out.println("authority is "
+ url.getAuthority());
System.out.println("file name is " + url.getFile());
System.out.println("host is " + url.getHost());
System.out.println("path is " + url.getPath());
System.out.println("port is " + url.getPort());
System.out.println("default port is "
+ url.getDefaultPort());
System.out.println("query is " + url.getQuery());
System.out.println("ref is " + url.getRef());
}catch(IOException e)
{
e.printStackTrace();
}
}
}
A s am ple run of the thid program would produce following res ult:
$ java URLDemo http://www.amrood.com/index.htm?language=en#j2se
URL is http://www.amrood.com/index.htm?language=en#j2se
protocol is http
authority is www.amrood.com
file name is /index.htm?language=en
host is www.amrood.com
path is /index.htm
port is -1
default port is 80
query is language=en
ref is j2se

URLConnections Class Methods:


The openConnection() m ethod returns a ja va.net. URLConnection, an abs tract class whos e
s ubclasses repres ent the various types of URL connections .
For exam ple:

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...

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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

Object get Content()


Retrieves the contents of this URL connection.

Object get Content( Class[] classes)


Retrieves the contents of this URL connection.

String get ContentEncoding()


Returns the value of the content-encoding header field.

int get ContentLengt h()


Returns the value of the content-l ength header field.

String get ContentType()


Returns the value of the content-type header field.

int getLastModified()
Returns the value of the las t-m odified header field.

long get Expiration()


Returns the value of the e xpires header field.

long getIfM odifie dSince()


Returns the value of this object's ifModifiedSince field.
public void setDoInput(boolea n input)

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.

public void setDoOutput(boolea n output)


10 Pas ses in true to denote that the connection will be us ed for output. The defaul t value is fals e
becaus e many types of URLs do not s upport being written to.
11

public InputStream getInputStream() throw s IOException


Returns the input s tream of the URL connection for reading from the res ource.

12

public OutputStream getOutputStream() throw s IOException


Returns the output s tream of the URL connection for writing to the res ource

13

public URL get URL()


Returns the URL that this URLConnection object is connected to

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

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

{
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.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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 .

ServerSocket Class Methods:


The java.net.Ser verSocket class is us ed by s erver applications to obtain a port and lis ten for client reques ts
The ServerSocke t class has four cons tructors :
SN Methods w ith Description
1

public ServerSocket(int port) t hrow s IOEx ception


Attem pts to create a s erver socket bound to the specified port. An e xception occurs if the port is
already bound b y another application.

public ServerSocket(int port, int backlog) t hrow s IO Exception


Sim ilar to the previous cons tructor, the backlog parameter specifies how m any incoming clients to
s tore in a wait queue.

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

public ServerSocket() throw s IOExc eption


Creates an unbound s erver s ocket. When us ing this cons tructor, us e the bind() m ethod when you
are ready to bind the server s ocket

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

public int getLocalP ort()


Returns the port that the s erver s ocket is lis tening on. This m ethod is useful if you pass ed in 0 as
the port number in a cons tructor and let the s erver find a port for you.
public Socket accept() throw s IOException

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

public voi d setSoTimeout( int t imeout)


Sets the time-out value for how long the s erver s ocket waits for a client during the accept().

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.

public void bind(S ocketAddress host, int backlog)

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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.

Socket Class Methods:


The java.net.S oc ket class repres ents the s ocket that both the client and s erver us e to comm unicate with each
other. The client obtains a Socket object by ins tantiating one, whereas the s erver obtains a Socket object from the
return value o f the accept() m ethod.
The Socket class has five cons tructors that a client uses to connect to a s erver:
SN Methods w ith Description

public Socket(String host, int port) throw s Unknow nHostException, IO Exception.


This m ethod attempts to connect to the s pecified s erver at the s pecified port. If this cons tructor
does not throw an exception , the connection is success ful and the client is connected to the
s erver.

public Socket(InetAddress host, int port) throw s IOException


This m ethod is identical to the previous cons tructor, except that the hos t is denoted by an
InetAddress object.

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.

public Inet Address getInet Address()


This m ethod returns the address of the other com puter that this s ocket is connected to.

public int getPort()


Returns the port the socket is bound to on the rem ote machine.

public int getLocalP ort()


Returns the port the s ocket is bound to on the local m achine.

public SocketAddress getRemote SocketAddress()


Returns the address of the rem ote socket.

public InputStream getInputStream() thr ow s IOException


Returns the input s tream of the socket. The input s tream is connected to the output s tream of the

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

rem ote s ocket.


7

public OutputStream getOutputStream() throw s IOException


Returns the output s tream of the socket. The output s tream is connected to the input s tream of the
rem ote s ocket

public void close() throw s IOException


Clos es the s ocket, which makes this Socket object no longer capable of connecting again to an y
s erver

InetAddress Class Methods:


This class repres ents an Internet Protocol (IP) address . Here are following us efull methods which you would need
while doing socket programm ing:
SN

Methods w ith Description

static InetAddress getByAddress(byte[] addr)


Returns an InetAddress object given the raw IP address .

static InetAddress getByAddress(String host, byte[] addr)


Create an InetAddress bas ed on the provided hos t name and IP addres s .

static InetAddress getByName(String host)


Determines the IP address of a hos t, gi ven the hos t's nam e.

String get HostAddress()


Returns the IP address s tring in textual pres entation.

String get Host Name()


Gets the hos t nam e for this IP address .

static InetAddress InetAddress getLocalHost()


Returns the local hos t.

String toString()
Converts this IP address to a String.

Socket Client Example:


The following GreetingClient is a client program that connects to a s erver by us ing a s ocket and s ends a greeting,
and then waits for a res pons e.
// File Name GreetingClient.java
import java.net.*;
import java.io.*;
public class GreetingClient
{
public static void main(String [] args)
{
String serverName = args[0];
int port = Integer.parseInt(args[1]);
try
{
System.out.println("Connecting to " + serverName
+ " on port " + port);
Socket client = new Socket(serverName, port);
System. out. println( " Just con necte d to "

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

+ 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();
}
}
}

Socket Server Example:


The following GreetingServer program is an example of a s erver application that us es the Socket class to lis ten
for clients on a port num ber specified by a comm and-line argum ent:
// File Name GreetingServer.java
import java.net.*;
import java.io.*;
public class GreetingServer extends Thread
{
private ServerSocket serverSocket;
public GreetingServer(int port) throws IOException
{
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(10000);
}
public void run()
{
while(true)
{
try
{
System.out.println("Waiting for client on port " +
serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
System.out.println("Just connected to "
+ server.getRemoteSocketAddress());
DataInputStream in =
new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out =
new DataOutputStream(server.getOutputStream());
out.writeUTF("Thank you for connecting to "
+ server.getLocalSocketAddress() + "\nGoodbye!");
server.close();
}catch(SocketTimeoutException s)

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

{
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!

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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 .

Send a Simple Email:


Here is an example to s end a s im ple em ail from your m achine. Here it is assumed that your
localhostis connected to the internet and capable enough to s end an em ail.
// File Name SendEmail.java
import
import
import
import

java.util.*;
javax.mail.*;
javax.mail.internet.*;
javax.activation.*;

public class SendEmail


{
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.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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!");
// Now set the actual message
message.setText("This is actual message");
// 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 a s im ple em ail:
$ java SendEmail
Sent message successfully....
If you wan t to s end an em ail to m ultiple recipients then following m ethods would be used to s pecify m ultiple email
IDs :
void addRecipients(Message.RecipientType type,
Address[] addresses)
throws MessagingException
Here is the des cription of the parameters :

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

Send an HTML Email:


Here is an exam ple to s end an HTML em ail from your m achine. Here it is assum ed that your
localhostis connected to the internet and capable enough to s end an em ail.
This example is very s imilar to previous one, e xcept here we are us ing s etContent() method to s et content whose
s econd argum ent is "text/htm l" to s pecify that the HT ML content is included in the mess age.
Using this exam ple, you can send as big as HTML content you like.
// File Name SendHTMLEmail.java
import java.util.*;

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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 PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

Send Attachment in Email:


Here is an exam ple to s end an em ail with attachment from your m achine. Here it is ass um ed
that yourlocalhost is connected to the internet and capable enough to s end an em ail.
// File Name SendFileEmail.java
import
import
import
import

java.util.*;
javax.mail.*;
javax.mail.internet.*;
javax.activation.*;

public class SendFileEmail


{
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!");
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Fill the message
messageBodyPart.setText("This is message body");
// Create a multipar message
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

// Part two is attachment


messageBodyPart = new MimeBodyPart();
String filename = "file.txt";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
// Send the complete message parts
message.setContent(multipart );
// 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 SendFileEmail
Sent message successfully....

User Authentication Part:


If it is required to provide us er ID and Password to the email s erver for authentication purpos e then you can s et
these properties as follows :
props.setProperty("mail.user", "myuser");
props.setProperty("mail.password", "mypwd");
Res t of the em ail sending m echanism would remain as explained above.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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 .

Life Cycle of a Thread:


A thread goes through various s tages in its life cycle. For exam ple, a thread is born, s tarted, runs , and then dies .
Following diagram s hows com plete life cycle of a thread.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

Abo ve m entioned s tages are explained here:

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:

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

You can im plem ent the Runnable interface.

You can e xtend the Thread class , its elf.

Create Thread by Implementing Runnable:


The easies t way to create a thread is to create a class that im plements the Runnable interface.
To im plem ent Runnable, a class need only im plem ent a s ingle m ethod called run( ), which is declared like this :
public void run( )
You will define the code tha t cons titutes the new thread inside run() m ethod. It is im portant to unders tand that
run() can call other methods , us e other class es , and declare variables , jus t like the m ain thread can.
After you create a class that im plem ents Runnable, you will ins tantiate an object of type Thread from within that
class . Thread defines several cons tructors . The one that we will us e is s hown here:
Thread(Runnable threadOb, String threadName);
Here threadOb is an ins tance of a class that im plem ents the Runnable interface and the nam e of the new thread
is s pecified by threadNam e.
After the new thread is created, it will not s tart running until you call its start( ) m ethod, which is declared within
Thread. The s tart( ) m ethod is s hown here:
void start( );

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

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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.

Create Thread by Extending Thread:


The second way to create a thread is to create a new class that extends Thread, and then to create an ins tance
of that class .
The extending class mus t override the run( ) m ethod, which is the entry point for the new thread . It m us t als o
call start( ) to begin execution o f the new thread.

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.");

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

}
}
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

public void start()


Starts the thread in a s eparate path of e xecution, then in vokes the run() m ethod on this Thread
object.

public void run()


If this Thread object was ins tantiated us ing a separate Runnable target, the run() m ethod is
invoked on tha t Runnable object.

public fina l voi d setName(String name)


Changes the nam e of the Thread object. There is also a getName() method for retrieving the
name.

public fina l voi d setPriority( int priority)


Sets the priority of this Thread object. The poss ible values are between 1 and 10.

public fina l voi d setDaemon(boolea n on)


A param eter of true denotes this Thread as a daem on thread.

public fina l voi d join( lon g millisec)


The current thread in vokes this m ethod on a s econd thread, caus ing the current thread to block

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

until the second thread term inates or the specified number of millis econds pass es .
7

public voi d interrupt()


Interrupts this thread, caus ing it to continue e xecution if it was blocked for any reason.

public fina l boolea n is Alive()


Returns true if the thread is alive, which is any tim e after the thread has been s tarted but before it
runs to completion.

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

public static void yield()


Caus es the currently running thread to yield to an y other threads of the sam e priority that are
waiting to be s cheduled

public static void sleep(long m illisec)


Caus es the currently running thread to block for at leas t the s pecified num ber of m illis econds

public static boolean holdsLock(Object x)


Returns true if the current thread holds the lock on the given Object.

public static Threa d currentThr ead()


Returns a reference to the currently running thread, which is the thread that in vokes this method.

public static void dumpStack()


Prints the s tack trace for the currently running thread, which is us eful when debugging a
m ultithreaded application.

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;
}

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

public void run()


{
int counter = 0;
int guess = 0;
do
{
guess = (int) (Math.random() * 100 + 1);
System.out.println(this.getName()
+ " guesses " + guess);
counter++;
}while(guess != number);
System.out.println("** Correct! " + this.getName()
+ " in " + counter + " guesses.**");
}
}
// File Name : ThreadClassDemo.java
public class ThreadClassDemo
{
public static void main(String [] args)
{
Runnable hello = new DisplayMessage("Hello");
Thread thread1 = new Thread(hello);
thread1.setDaemon(true);
thread1.setName("hello");
System.out.println("Starting hello thread...");
thread1.start();
Runnable bye = new DisplayMessage("Goodbye");
Thread thread2 = new Thread(hello);
thread2.setPriority(Thread.MIN_PRIORITY);
thread2.setDaemon(true);
System.out.println("Starting goodbye thread...");
thread2.start();
System.out.println("Starting thread3...");
Thread thread3 = new GuessANumber(27);
thread3.start();
try
{
thread3.join();
}catch(InterruptedException e)
{
System.out.println("Thread interrupted.");
}
System.out.println("Starting thread4...");
Thread thread4 = new GuessANumber(75);
thread4.start();
System.out.println("main() is ending...");
}
}
This would produce following res ult. You can try this exam ple again and again and you would ge t differen t res ult
every tim e.
Starting hello thread...
Starting goodbye thread...
Hello
Hello
Hello

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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.

Major Thread Concepts:


While doing Multithreading programm ing, you would need to ha ve following concepts very hand y:

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) {

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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;

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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 .

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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;
}
}
}

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

// File Name LazyTeller.java


public class LazyTeller extends Thread
{
private ThreadSafeBankAccount source, dest;
public LazyTeller(ThreadSafeBankAccount a,
ThreadSafeBankAccount b)
{
source = a;
dest = b;
}
public void run()
{
transfer(250.00);
}
public void transfer(double amount)
{
System.out.println("Transferring from "
+ source.getNumber() + " to " + dest.getNumber());
synchronized(source)
{
Thread.yield();
synchronized(dest)
{
System.out.println("Withdrawing from "
+ source.getNumber());
source.withdraw(amount);
System.out.println("Depositing into "
+ dest.getNumber());
dest.deposit(amount);
}
}
}
}
public class DeadlockDemo
{
public static void main(String [] args)
{
System.out.println("Creating two bank accounts...");
ThreadSafeBankAccount checking =
new ThreadSafeBankAccount(101, 1000.00);
ThreadSafeBankAccount savings =
new ThreadSafeBankAccount(102, 5000.00);
System.out.println("Creating two teller threads...");
Thread teller1 = new LazyTeller(checking, savings);
Thread teller2 = new LazyTeller(savings, checking);
System.out.println("Starting both threads...");
teller1.start();
teller2.start();
}
}
This would produce following result:
Creating two bank accounts...
Creating two teller threads...
Starting both threads...
Transferring from 101 to 102
Transferring from 102 to 101

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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!

Deadlock Solution Example:


Here trans fer() method, in a class named OrderedTeller, in s tead of arbitraril y s ynchroni zing on locks ,
this trans fer() m ethod obtains locks in a s pecified order based on the number of the bank account.
// 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;
}
}
}
// File Name OrderedTeller.java

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

public class OrderedTeller extends Thread


{
private ThreadSafeBankAccount source, dest;
public OrderedTeller(ThreadSafeBankAccount a,
ThreadSafeBankAccount b)
{
source = a;
dest = b;
}
public void run()
{
transfer(250.00);
}
public void transfer(double amount)
{
System.out.println("Transferring from " + source.getNumber()
+ " to " + dest.getNumber());
ThreadSafeBankAccount first, second;
if(source.getNumber() < dest.getNumber())
{
first = source;
second = dest;
}
else
{
first = dest;
second = source;
}
synchronized(first)
{
Thread.yield();
synchronized(second)
{
System.out.println("Withdrawing from "
+ source.getNumber());
source.withdraw(amount);
System.out.println("Depositing into "
+ dest.getNumber());
dest.deposit(amount);
}
}
}
}
// File Name DeadlockDemo.java
public class DeadlockDemo
{
public static void main(String [] args)
{
System.out.println("Creating two bank accounts...");
ThreadSafeBankAccount checking =
new ThreadSafeBankAccount(101, 1000.00);
ThreadSafeBankAccount savings =
new ThreadSafeBankAccount(102, 5000.00);
System.out.println("Creating two teller threads...");
Thread teller1 = new OrderedTeller(checking, savings);
Thread teller2 = new OrderedTeller(savings, checking);
System.out.println("Starting both threads...");
teller1.start();
teller2.start();

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

}
}
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

Thread Control: Suspend, Stop and Resume


While the s us pend( ), res um e( ), and s top( ) methods defined by Thread class s eem to be a perfectly reasonable
and convenient approach to m anaging the execution of threads , they mus t not be us ed for new Java programs
and obs olete in newer versions of Ja va.
The following exam ple illus trates how the wait( ) and notify( ) m ethods that are inherited from Object can be us ed
to control the execution o f a thread .
This exam ple is s im ilar to the program in the previous section. However, the deprecated method calls have been
rem oved. Le t us cons ider the operation of this program .
The NewThread class contains a boolean ins tance variable named s us pendFlag, which is used to control
the execution o f the thread . It is initiali zed to false by the cons tructor.
The run( ) m ethod contains a s ynchronized s tatem ent block that checks s us pendFlag. If that variable is true, the
wait( ) m ethod is invoked to s us pend the execution of the thread. The m ysus pend( ) method sets s us pendFlag to
true. The m yres um e( ) m ethod s ets s us pendFlag to false and invokes notify( ) to wake up the thread. Finall y, the
m ain( ) m ethod has been m odified to invoke the m ys us pend( ) and m yres um e( ) m ethods .

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();

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

}
}
}
} 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

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

Suspending thread One


Two: 10
Two: 9
Two: 8
Two: 7
Two: 6
Resuming thread One
Suspending thread Two
One: 10
One: 9
One: 8
One: 7
One: 6
Resuming thread Two
Waiting for threads to finish .
Two: 5
One: 5
Two: 4
One: 4
Two: 3
One: 3
Two: 2
One: 2
Two: 1
One: 1
Two exiting.
One exiting.
Main thread exiting.

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 !

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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:

An applet is a Java class that extends the ja va.applet.Applet class .

A m ain() m ethod is not invoked on an applet, and an applet class will not define m ain().

Applets are designed to be em bedded within an HTML page.

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 .

Life Cycle of an Applet:


Four m ethods in the Applet class give you the fram ework on which you build an y s erious applet:

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 .

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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.

A "Hello, World" Applet:


The following is a s im ple applet named HelloWorldApplet.ja va:
import java.applet.*;
import java.awt.*;
public class HelloWorldApplet extends Applet
{
public void paint (Graphics g)
{
g.drawString ("Hello World", 25, 50);
}
}
These import s tatements bring the class es into the s cope of our applet class :

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.

The Applet CLASS:


Ever y apple t is an e xtens ion of the java.applet.Applet class. The bas e Applet class provides methods that
a derived Apple t class m ay call to obtain inform ation and s ervices from the browser context.
These include m ethods that do the following:

Get apple t param eters

Get the network location o f the H TML file that contains the applet

Get the network location o f the ap plet class directory

Print a s tatus mess age in the brows er

Fetch an image

Fetch an audio clip

Play an audio clip

Res ize the applet

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:

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

reques t inform ation about the auth or, vers ion and copyright of the applet

reques t a des cription of the parameters the applet recogni zes

initiali ze the apple t

des troy the apple t

s tart the applet's execution

s top the applet's execution

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:

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

<applet code= "mypackage.subpackage.TestApplet.class"


width="320" height="120">

Getting Applet Parameters:


The following exam ple dem ons trates how to make an applet res pond to s etup param eters s pecified in
the docum ent. This applet dis plays a checkerboard pattern of black and a second color.
The s econd color and the s ize of each s quare may be s pecified as param eters to the applet within the document.
CheckerApplet gets its param eters in the init() m ethod. It m ay als o get its param eters in the paint()
m ethod.
However, getting the values and saving the s ettings once at the s tart of the applet, ins tead of a t e ver y refres h, is
convenien t and efficient.
The applet viewer or brows er calls the init() m ethod of each applet it runs . The viewer calls init() once,
immediately after loading the applet. (Applet.init() is im plem ented to do nothing.) Override the
default im plem entation to ins ert cus tom initialization code.
The Applet.getParam eter() method fetches a parameter given the param eter's name (the value of a paramete r is
always a s tring). If the value is num eric or other non-character data, the s tring m us t be parsed.
The following is a s keleton of CheckerApplet.ja va:
import java.applet.*;
import java.awt.*;
public class CheckerApplet extends Applet
{
int squareSize = 50;// initialized to default size
public void init () {}
private void parseSquareSize (String param) {}
private Color parseColor (String param) {}
public void paint (Graphics g) {}
}
Here are CheckerApplet's init() and pri vate pars eSquareSize() m ethods :
public void init ()
{
String squareSizeParam = getParameter ("squareSize");
parseSquareSize (squareSizeParam);
String colorParam = getParameter ("color");
Color fg = parseColor (colorParam);
setBackground (Color.black);
setForeground (fg);
}
private void parseSquareSize (String param)
{
if (param == null) return;
try {
squareSize = Integer.parseInt (param);
}
catch (Exception e) {
// Let default value remain
}
}

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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 .

Specifying Applet Parameters:


The following is an exam ple of an HTML file with a CheckerApplet em bedded in it. The HTML file s pecifies both
param eters to the applet by m eans of the <param > tag.
<html>
<title>Checkerboard Applet</title>
<hr>
<applet code="CheckerApplet.class" width="480" height="320">
<param name="color" value="blue">
<param name="squaresize" value="30">
</applet>
<hr>
</html>
Note : Param eter nam es are not cas e sens itive.

Application Conversion to Applets:


It is eas y to conver t a graphical Ja va a pplication (that is , an application that us es the AWT and tha t you can s tart
with the java program launcher) into an applet that you can em bed in a web page.
Here are the specific s teps for converting an application to an applet.

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.)

Don't call s etVis ible(true). The apple t is displayed autom atically.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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 class ExampleEventHandling extends Applet


implements MouseListener {
StringBuffer strBuffer;
public void init() {
addMouseListener(this);
strBuffer = new StringBuffer();
addItem("initializing the apple ");
}
public void start() {
addItem("starting the applet ");
}
public void stop() {
addItem("stopping the applet ");
}
public void destroy() {
addItem("unloading the applet");
}
void addItem(String word) {
System.out.println(word);
strBuffer.append(word);
repaint();
}
public void paint(Graphics g) {
//Draw a Rectangle around the applet's display area.
g.drawRect(0, 0,
getWidth() - 1,
getHeight() - 1);
//display the string inside the rectangle.
g.drawString(strBuffer.toString(), 10, 20);
}
public
}
public
}
public
}
public

void mouseEntered(MouseEvent event) {


void mouseExited(MouseEvent event) {
void mousePressed(MouseEvent event) {
void mouseReleased(MouseEvent event) {

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

}
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");

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

g.drawImage(image, 0, 0, 200, 84, null);


g.drawString("www.javalicense.com", 35, 100);
}
}
Now let us call this applet as follows :
<html>
<title>The ImageDemo applet</title>
<hr>
<applet code="ImageDemo.class" widt h= "300" height= "200">
<param name= "i mag e " value= "java.jpg" >
</applet>
<hr>
</html>
Bas ed on the above exam ples , here is the live applet e xam ple:

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()
{

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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.

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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 .

The javadoc Tags:


The javadoc utility recogni zes the following tags :

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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
*/

What javadoc Outputs?


The javadoc program takes as input your Ja va program 's source file and outputs s everal HTML files that co ntain
the program 's docum entation.
Inform ation about each class will be in its own HTML file. Ja va utility ja vadoc will also output an inde x and
a hierarchy tree . Other HTML files can be generated.
Since different implementations of ja vad oc m ay work differentl y, you will need to check the ins tructions
that accom pany your Ja va de velopm ent s ys tem for details s pecific to your vers ion.

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 {

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

/**
* 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...

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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 .

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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

Methods w ith Description

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 .

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

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

Runtim ePermiss ion


This class is for runtime perm issions .

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 .

JAVA PROGRAMMING TUTORIAL


BILAL AHMED SHAIK

You might also like