Sei sulla pagina 1di 213

Core JAVA

HISTORY OF JAVA
-

Java is a high-level object-oriented programming language developed by the Sun


Microsystems , for the development of enterprise grade applications.
This Language is evolved from a language named Oak.
Oak was developed in the early nineties at Sun Microsystems as a platformindependent language aimed at allowing entertainment appliances such as video
game consoles and VCRs to communicate.
Oak was first slated to appear in television set-top boxes designed to provide
video-on-demand services.
Oak was unsuccessful so in 1995 Sun changed the name to java. Therefore Java
1.0 was officially released to the world.
It was only developed keeping in mind the consumer electronics and
communication equipments.
A team of Sun Microsystems including Patrick Naughton, Mike Sheridan in the
guidance of James Goslings decided to develop an advanced programming
language for the betterment of consumer electronic devices.

Where is Java being Used?


-

Java-programming language was only developed for the small devices but now it
can be found in a variety of devices like cell phones, e-commerce application,
PCs and almost all network or computing devices.
Java is available in different form:
JSP Like PHP and ASP, Java Server Pages based on a code with normal HTML
tags, Which helps in creating dynamic web pages.
Java Applets This is another type of Java program that used within a web page
to add many new features to a web browser. These are small program used in the
programming of instant messaging, chat service, solving some complex
calculation and for many other purposes.
J2EE The software Java 2 Enterprise Edition are used by various companies to
transfer data based on XML structured documents between one another.
JavaBeans This is something like Visual Basic and a reusable software
component that can be easily assemble to create some new and advanced
application.
Mobile Java - Java is also used for various entertainment devices especially

mobile phone. Mobile Information Devices Profile (MIDP) uses Java run time
environment in cell phones, mobile tracking systems and other traditional PDA
devices, including MP3 players, digital TV, video, 3D, simplifying games, etc.

Java as an Internet Language


The features that favors it to be an internet language are:
- Cross Platform Compatibility: The java source files (java files with .java
extension) after compilation generates the bytecode (the files with .class
extension) which is further converted into the machine code by the interpreter.
- The byte code once generated can execute on any machine having a JVM. Every
operating system has it's unique Java

Virtual Machine (JVM) and the Java Runtime Environment (JRE).


-

Support to Internet Protocols: Java has a rich variety of classes that abstracts
the Internet protocols like HTTP , FTP, IP, TCP-IP, SMTP, DNS etc .

Support to HTML: Java programming language provide html pages as a view to


interact with the user, that are used for web application.

Support to XML parsing: This is used to share data among different


applications over the internet.

Support to Web Services : Java has a rich variety of APIs to use xml technology
in diverse applications that supports N-Tiered Enterprise applications over the
internet.

Features like JAXB , JAXM, JAX-RPC , JAXR etc enables to implement web
services in java applications. It makes java a most suited internet language.

Support to java enabled Mobile devices: Java language also works with any java
enabled mobile devices that support MIDP 1.0/2.0 including the symbian OS
mobile devices.

Java Releases
The tables given below provide information about the name and time of releases for
different versions of Java technology.
Releases Event
Month
Year
Java 1.5.0_09
October
2006
Java 1.5.0_08
August
2006
Java 1.5.0_06
December
2005
Java 1.5.0_05
October
2005

Java 1_5_0_04
July
Java 1_5_0_01
February
Java 2 Platform, Standard Edition 1.4
February
(J2SE 1.4)
Java 2 Platform, Standard Edition 1.3
May
(J2SE 1.3)
Java 2 Platform, Enterprise Edition
December
(J2EE)
Java 2 Platform, Standard Edition (J2SE) August
Java Development Kit 1.2 (JDK 1.2)
December
Java Development Kit 1.1 (JDK 1.1)
February
Java Development Kit 1.0 (JDK 1.0)
January

2005
2005
2002
2000
1999
1999
1998
1997
1996

Download JDK
-

JDK(Java Development Kit) is a software development program provided by sun


Microsystems. Java Development Kit or JDK comes in various version and can be
downloaded free from the sun Microsystems.
JVM compiler, debugger and other tools are used with JDK for developing java
based application & java applets. So make sure that your JVM compiler & JDK
versions are same.
JDK also known as Java 2 Platform, That comes in three editions J2ME, J2SE &
J2EE.

Java Features
Platform Independent
-

The concept of Write-once-run-anywhere (known as the Platform independent).


The programs written on one platform can run on any platform provided the
platform must have the JVM.

Simple
-

Programs are easy to write and debug because java does not use the pointers
explicitly.
It is much harder to write the java programs that can crash the system but we can
not say about the other programming languages.
Java provides the bug free system due to the strong memory management. It also
has the automatic memory allocation and deallocation system.

Object Oriented:

If any language used classes and objects that language is called Object Oriented
Programming Language.
- Object: is anything that is existing in the real world.
- Object Properties: An instance of a class, Object is created using new operator
for memory allocation.
Method:
- A method is a function
- A function can return to anywhere
- A method can return to inside a class
- An object contains variables and methods
Class:
-

Is a template for multiple objects with similar features


A class is a model for creating objects
Class does not exists physically
Without class we cannot create object.
Class will also have variables and methods
Objects will also have variables and methods
Without creating atleast one class we cannot write java program

To be an Object Oriented language, any language must follow at least the four
characteristics.
Inheritance:
- It is the process of creating the new classes and using the behavior of the existing
classes by extending them just to reuse the existing code and adding the
additional features as needed.
Encapsulation
-

It is the mechanism of combining the information and providing the abstraction.

Polymorphism :
- As the name suggest one name multiple form.
Dynamic binding :
- It is the way of providing the maximum functionality to a program about the
specific type at runtime.
- As the languages like Objective C, C++ fulfills the above four characteristics yet
they are not fully object oriented languages because they are structured as well as
object oriented languages. But in case of java, it is a fully Object Oriented
language.
Robust

Java has the strong memory allocation and automatic garbage collection
mechanism.
- It provides the powerful exception handling and type checking mechanism as
compare to other programming languages.
- Compiler and interpreter by checking the errors makes the system secure from
crash.
Distributed
- The widely used protocols like HTTP and FTP are developed in java.
- Internet programmers can call functions on these protocols and can get access the
files from any remote machine on the internet rather than writing codes on their
local system.
Portable
- The feature Write-once-run-anywhere makes the java language portable provided
that the system must have interpreter for the JVM.
- Java also have the standard data size irrespective of operating system or the
processor. These features makes the java as a portable language.
Dynamic
- While executing the java program the user can get the required files dynamically
from a local drive or from a computer through the Internet.
Secure
- Java does not use memory pointers explicitly. Security manager determines the
accessibility options of a class like reading and writing a file to the local disk.
- Java uses the public key encryption system to allow the java applications to
transmit over the internet in the secure encrypted form.
- The bytecode Verifier checks the classes after loading.
Performance
- Java uses native code usage, and lightweight process called threads.
- In the beginning interpretation of bytecode resulted the performance slow but the
advance version of JVM uses the adaptive and just in time compilation technique
that improves the performance.
Multithreaded:
- Java is also a Multithreaded programming language.
Multithreading means a single program having different threads executing
independently at the same time.
- Multiple threads execute instructions according to the program code in a process
or a program.
Interpreted
- The interpreter program reads the source code and translates it on the fly into
computations.
- Thus, Java as an interpreted language depends on an interpreter program.

Java as an interpreted language is its error debugging quality. Due to this any
error occurring in the program gets traced.

ArchitectureNeutral
- The Java compiler by generating byte code instructions, to be easily interpreted
on any machine and to be easily translated into native machine code on the fly.
- The compiler generates an architecture-neutral object file format to enable a Java
application to execute anywhere on the network and then the compiled code is
executed on many processors, given the presence of the Java runtime system.

Java Virtual Machine(JVM)


-

JVM is the main component of Java architecture and it is the part of the JRE (Java
Runtime Enviroment) .
It provides the cross platform functionality to java.
This is a software process that converts the compiled Java byte code to machine
code.
Byte code is an intermediary language between Java source and the host system.
Most programming language like C and Pascal converts the source code into
machine code for one specific type of machine as the machine language vary from
system to system .
Mostly compiler produce code for a particular system but Java compiler produce
code for a virtual machine .
JVM provides security to java.
The programs written in Java or the source code translated by Java compiler into
byte code and after that the JVM converts the byte code into machine code for the
computer one wants to run.
JVM is a part of Java Run Time Environment that is required by every operating
system requires a different JRE .

The architecture of the JVM is given below

JRE consists of a number of classes based on JavaAPI and JVM, and without
JRE, it is impossible to run Java.

JVM Block Diagram


Class Loader
Sub System

Run Time Data Areas


Method
Area
(class code)

Execution
Engine

Heap
(create
object)

Java Stack
(execute
method)

Native Method
Interface

PC
Register

Native
method
stacks

Native method Libraries

Java Compiler is outside the JVM


Class loader subsystem loads dot class files into memory and verifies the
bytecode instructions and then allots required memory to execute instruction.

The allotted memory is divided into five parts


1. Method Area: Bytecode instructions will be loaded , contain class code along
with method code.
2. Heap : Heap is second part of memory.It contains objects. It is used for creating
objects
3. Java Stack: Java method is executed. Method parameters and temporary results .
method return results are stored in Java Stack.
4. PC Register: (Program counter Register):These registers store the address of the
instruction being executed by Microprocessor
5. Native Method Stacks: Native methods are methods written in some other
language like C or C++
6. Execution Engine: It contains Interpreter and JIT Compiler which translate the
byte code instruction into machine language,which are executed by
MicroProcessor.

7. Native Method Interface: is useful to linkup with the native methods or


Microprocessor.
Garbage Collection: It is the process that the Java Virtual Machine used to find and
reclaim unreachable objects to free microprocessor memory space. It is a type of
Memory Manager.

Memory Management with JVM :-

Java language in combination with runtime eliminates the problems of memory


management and corrupted pointers.
There is no explicit allocation of memory in Java, memory is allocated only to
objects.
JVM's heap stores all objects created.
JVM ask the operating system for enough memory to run the JVM itself and some
free memory for the application to create new objects.

If the free memory area is getting too small, the JVM will ask the operating
system for more and if there is no more additional memory available from the
operating system, then JVM stops the application and issues the "Out of memory
error".

The Java runtime employs a garbage collector to reclaim the memory occupied
by an object.

Java Virtual Machine Specification


JVM Specification = Java programming language + Java Virtual Machine architecture +
Java class-file format.
JVM Implementation:
-

Though implementations of Java Virtual Machines are designed to be compatible,


no two JVMs are exactly alike.
For example, garbage collection algorithms vary from one JVM to another, so it
becomes impossible to know exactly when memory will be reclaimed.
The thread scheduling algorithms are different between one JVM and another , so
that it is impossible to accurately predict when one thread will be executed over
another.

JVM Runtime Environment contains the two parts such as:


-

Java API classes: Java API classes are the predefined classes required for the
program compilation and interpretation.

Java Virtual Machine: JVM is also a part of the JRE. The Java Virtual Machine
is responsible for interpreting Java bytecode, and translating this into actions or
operating system calls .

Xyz.java--
-

Xyz.class-- JVM --PC

Size of each instruction is 1 byte or 8 bits


JVM can understand byte code instructions
JVM is a program
Converts byte code instructions into machine language instructions and gives
to the microprocessor , understanble by Pentium processor
210 byte code instruction are available
JVM is system dependent
JVM is different for different operating system
.class file is system dependent

- JVM made Java System Independent.

Java Enabled browsers


-

Java language is the most powerful language and is widely used in the web
application. Today most of the web browser are java compatible. Few of them
are:

Internet Explorer
Netscape
HotJava
Firefox 1.0.4
Mozilla 1.6

Security Problems on Internet


1.
2.
3.
4.
5.
6.
7.

Eaves Dropping: Reading others data illegally


Tampering: Not only reading other data but also modifying it.
Impersonation: A person acting as another person on Internet.
Virus: A program that can damage data, s/w or h/w of a computer.
first virus developed by Pakistan
Virus spreads through .exe, .dat , .com, .sis
Virus cannot be carried by text file

Translator is a program that converts any computer program into machine language.
3 types of translators
i.
Interpreter

ii.
iii.
-

Compiler
Assembler

Interpretor: Converts the program one line at a time into machine language
Compiler: Converts all lines of the program at once atleast 10 times faster
than the interpreter.
Assembler: Translates assembly language to machine language Mnemonics
are used in assembly languge.
Assembler s/w Turbo Assemblers
- Macro Assemblers
- Micro Assemblers

compile
Xyz.c
program)

Xyz.obj (contains machine language instructionsof a source


Run

Xyz.exe (machine language instructions with a copy of all header files.


First Microprocessor 4004,8080,8086,8088,80286
Celeron 200 instructions
Pentium 225 instructions

Java Compiler
-

A Java Compiler javac is a computer program or set of programs


which translates java source code into java byte code.

Following figure shows the working of the Java compiler:

10

Once the byte code is generated it can be run on any platform using
Java Interpreter
(JVM). It interprets byte code (.class file) and converts into machine
specific binary code. Then JVM runs the binary code on the host
machine.

Java Compiler
When you run javac command on the command prompt, it shows the following output.
C:\>javac
Usage: javac <options> <source files>
where possible options include:
-g
Generate all debugging info
-g:none

Generate no debugging info

-g:{lines,vars,source}

Generate only some debugging info

-nowarn

Generate no warnings

-verbose

Output messages about what the compiler is doing

-deprecation

Output source locations where deprecated APIs are


used

-classpath <path>
Specify where to find user class files and
annotation processors
-cp <path>

Specify where to find user class files and


annotation processors

11

-sourcepath <path>

Specify where to find input source files

-bootclasspath <path>
-extdirs <dirs>

Override location of bootstrap class files


Override location of installed extensions

-endorseddirs <dirs>

Override location of endorsed standards path

-proc:{none,only}
Control whether annotation processing and/or
compilation is done.
-processor
<class1>[,<class2>,<class3>...]
Names of the annotation processors to run;
bypasses default discovery process
-processorpath <path>

Specify where to find annotation processors

-d <directory>

Specify where to place generated class files

-s <directory>

Specify where to place generated source files

-implicit:{none,class}
Specify whether or not to generate class files
for implicitly referenced files
-encoding <encoding>

Specify character encoding used by source files

-source <release>
release
-target <release>
-version
-help
-Akey[=value]
-X
-J<flag>
C:\>

Provide source compatibility with specified

Generate class files for specific VM version


Version information
Print a synopsis of standard options
Options to pass to annotation processors
Print a synopsis of nonstandard options
Pass <flag> directly to the runtime system

12

Java Interpreter
-

Java interpreter translates the Java bytecode into the code that can be
understood by the Operating System.

Once the class is loaded, java follows a C-like convention and


searches for the class that contains a method called main(). If it finds
an appropriate main() method, the interpreter starts the application by
executing that method.

From there, the application starts additional threads, reference other


classes, and create its user interface.

Java applet is a compiled Java code, the Java interpreter can't directly
run them because

they are used as part of a larger applications. For this we use Java
Applet Viewer.

The Figure below shows the working of Java Interpreter:

Java Debugger
-

Java debugger helps in finding and the fixing of bugs in Java language
programs.
The Java debugger is denoted as jdb. It works like a command-line
debugger for Java classes.

13

Java Comments
-

These comments are advantageous in the sense that they make the
programmer feel convenient to grasp the logic of the program.
Although these comments are ignored by the Java compiler, To
provide the additional information about the code, use comments.

There are three types of comments used in Java. These are:


1. Single LineComment
//text: Comments are non executable statements
2. MultiLine Comment
/*text*/: these comments have several lines as comment
3. Jav aDocumentation Comment
/**text*/

Java Keywords
There are few keywords in Java programming language. Remember, we cannot use these
keywords as identifiers in the program.
The keywords const and goto are reserved though, they are not being currently used.
The brief description of each one of the keyword is given below.
abstract
When a class is not to be instantiated, use abstract keyword but rather extended by other
classes.
This keyword is used in a method declaration to declare a method without providing the
implementation.
assert
It is used to define an assert statement. Any boolean condition in a program is declared
with the help of assert statement.
The condition is checked at runtime if the program is running with assertions .
If the condition is false, the Java runtime system throws an AssertionError.
boolean
This keyword is used to pertain to an expression or variable that can have only a true or
falsevalue.

14

byte
This is 8-bit integer. This keyword is used to declare an expression, method return value,
or variable of type byte.
Case
This keyword is used to defines a group of statements. The value defined by the
enclosing switch statement should match with the specified value.
catch
This keyword is used to handle the exceptions that occur in a program preceding try
keyword.
char
This Java keyword is used to declare an expression, method return value, or variable of
typecharacter.
class
This keyword is used to define the implementation of a particular kind of object.
const
This keyword has been deprecated from Java programming language.
continue
This keyword is used for the continuation of the program at the end of the current loop
body.
default
If the value defined by the enclosing switch statement does not match any value specified
by a case keyword in the switch statement.
do
Used to declare a loop that will iterate a block of statements. The loop's exit condition is
specified with the while keyword. The loop will execute once before evaluating the exit
condition.
Double
A 64-bit floating point value. A Java keyword used to declare an expression, method
return value, or variable of type double-precision floating point number.
else
It is used to define a statement or block of statements that are executed in the case that the
test condition specified by the if keyword evaluates to false.
enum
Enumerations extend the base class Enum.This Java keyword is used to declare an
enumeratedtype.

15

extends
To specify the superclass in a class declaration, extends keyword is used. It is also used
in an interface declaration to specify one or more superinterfaces.
final
It is used to define an entity once that cannot be altered nor inherited later. Moreover, a
final class cannot be subclassed, a final method cannot be overridden, and a final variable
can occur at most once as a left-hand expression. All methods in a final class are
implicitly final.
finally
This keyword is used when the finally block is executed after the execution exits the try
block and any associated catch clauses regardless of whether an exception was thrown or
caught.
break
Used to resume program execution at the statement immediately following the current
enclosing block or statement. If followed by a label, the program resumes execution at
the statement immediately following the enclosing labeled statement or block.
strictfp
To get the precise results in Floating point calculations use strictfp keyword regardless of
any operating system and hardware platform.

Memory Description
Information is stored in the floppy disks as Bytes.
Byte is the basic measuring unit
Byte represents binary digits called bits.
8 bits
=
1 Byte
1024 B
=
1 KB
1024 KB
=
1 MB
1024 MB
=
1 GB
1024 GB
=
1 TB
Data is stored in the form of electric signals.

Java Data Types


There are eight primitive data types which are supported by Java language programming
which is predefined.
int
It is a 32-bit signed two's complement integer data type. It ranges from -2,147,483,648 to
2,147,483,647. However for wider range of values use long.

16

byte
It is an 8-bit signed two's complement integer. It ranges from -128 to127 (inclusive). We
can save memory in large arrays using byte. We can also use byte instead of int to
increase the limit of the code.
short
It is a 16-bit signed two's complement integer. It ranges from -32,768 to 32,767. short is
used to save memory in large arrays.
long
The long data type is a 64-bit signed two's complement integer. It ranges from
-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Use this data type with larger
range of values.
float
The float data type is a single-precision 32-bit IEEE 754 floating point. It ranges from
1.40129846432481707e-45 to 3.40282346638528860e+38 (positive or negative). Use a
float (instead of double) to save memory in large arrays. We do not use this data type for
the exact values such as currency. For that we have to use java.math.BigDecimal class.
double
This data type is a double-precision 64-bit IEEE 754 floating point. It ranges from
4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative).
This data type is generally the default choice for decimal values.
boolean
The boolean data type is 1-bit and has only two values: true and false. We use this data
type for conditional statements. true and false are not the same as True and False. They
are defined constants of the language.
char
The char data type is a single 16-bit, unsigned Unicode character. It ranges from 0 to
65,535. They are not same as ints, shorts etc.
The following table shows the default values for the data types:
Keyword

Description

Size/Format

Byte

Byte-length integer

8-bit two's complement

short

Short integer

16-bit two's complement

Int

Integer

32-bit two's complement

Long

Long integer

64-bit two's complement

17

Float

Single-precision floating point

32-bit IEEE

Double

Double-precision floating point

64-bit IEEE

Char

A single character

16-bit Unicode character

boolean

A boolean value (true or false)

true or false

Java - Variable, Constant and Literal in Java


Variable : You can assign the values to the variable once it has been declared. The values
of the variable can be changed anywhere in the program if the variable is accessible in
that scope.
Constants: Constants are declared using the final keyword. The values of the constant
can't be changed once its declared

An electronic device can understand


1- Presence of voltage
0- Absence of voltage
Are the machine languge instructions

Java Literals
Integer Literals
Integer literals is a sequence of digits and a suffix as L. To represent the type as long
integer we use L as a suffix. We can specify the integers either in decimal, hexadecimal or
octal format. To indicate a decimal format put the left most digit as nonzero. Similarly put
the characters as ox to the left of at least one hexadecimal digit to indicate hexadecimal
format.
659L

Decimal integer literal of type long integer

0x4a

Hexadecimal integer literal of type integer

057L

Octal integer literal of type long integer

Character Literals
18

We can specify a character literal as a single printable character in a pair of single quote
characters such as 'a', '#', and '3'.
The table below shows the codes that can represent these special characters. The letter d
such as in the octal, hex etc represents a number.
Escape
\n
\t
\b

Meaning
New line
Tab
Backspace

\r

Carriage return

\f
\\

Formfeed
Backslash

\'

Single quotation mark

\"

Double quotation mark

\d
\xd

Octal
Hexadecimal

\ud

Unicode character

It is very interesting to know that if we want to specify a single quote, a backslash, or a


nonprintable character as a character literal use an escape sequence. An escape sequence
uses a special syntax to represents a character. The syntax begins with a single backslash
character.
BooleanLiterals
The values true and false are also treated as literals in Java programming.
Floating-pointliterals
Floating-point numbers are like real numbers in mathematics, the default type when you
write a floating-point literal is double.
Type

Size

Range

Precision

Name bytes bits approximate in decimal digits


4

32

+/- 3.4 * 1038 6-7

Double 8

64

+/- 1.8 * 10308 15

Float

19

The following floating-point literals represent double-precision floating-point and


floating-point values.
6.5E+32 (or 6.5E32)

Double-precision floating-point literal

7D

Double-precision floating-point literal

.01f

Floating-point literal

String Literals
The string of characters is represented as String literals in Java. In Java a string is not a
basic data type, rather it is an object.
We represent string literals as
String myString = "How are you?";
Null Literals
We specify the Null literal in the source code as 'null'. To reduce the number of references
to an object, use null literal. The type of the null literal is always null. We typically assign
null literals to object reference variables. For instance
s = null;
In this example an object is referenced by s. We reduce the number of references to an
object by assigning null to s. Now, as in this example the object is no longer referenced
so it will be available for the garbage collection i.e. the compiler will destroy it and the
free memory will be allocated to the other object.

Operators
Operators are symbols that performs some operations on one or more than one operands.
SimpleAssignmentOperator =
Simple assignment operator
Arithmetic Operators
+
*
/
%

Additive operator (also used for String concatenation)


Subtraction operator
Multiplication operator
Division operator
Remainder operator

Unary Operators: An operator may act on a single operand.


+
Unary plus operator; indicates positive value (numbers are positive without this,
however)
Unary minus operator; negates an expression
++ Increment operator; increments a value by 1
-- Decrement operator; decrements a value by 1

20

Logical compliment operator; inverts the value of a boolean

Equality and Relational Operators


= = Equal to
!= Not equal to
>
Greater than
>= Greater than or equal to
<
Less than
<= Less than or equal to
Conditional Operators
&& Conditional-AND
||
Conditional-OR
?:
Ternary (shorthand for if-then-else statement)
Type Comparison Operator(To test whether an object belongs to a class)
instanceof
Compares an object to a specified type
Ex: emp instanceof Employee
Bitwise and Bit Shift Operators
~
Unary bitwise complement
<<
Signed left shift
>>
Signed right sift
>>> Unsigned right shift
&
Bitwise AND
^
Bitwise exclusive OR
|
Bitwise inclusive OR
Bitwise Operator: These operators acts upon individual bits of numbers
- 0,1 Binary Number System
- Convert 45 into binary.
Rule: Divide the no successively by 2 and takes the remainders from bottom to top.
Ex: for 45 we ll get 101101.
Convert 0010 1101 into decimal
Rule: Multiply the digits by the posers of 2 and take the sum of the products.
0 0 1 0 1 1 0 1
0+0+32+0+8+4+0+=45
Bitwise Complement Operator(~):This operator shows the complement of a
number
int x=-5
x=10
~x4
~x-11
This operator perfoms anding operation individual bits of two numbers

21

X
0
0
1
1

Y
0
1
0
1

X&Y
0
0
0
1

Truth table is table showing the relationship between input and output
X=10
Y=11
X+Y=?(output=10)
0000 1010
0000 1011
_________
0000 1010
Bitwise or( | ): This operator performs oring operation on individual bits.
X
0
0
1
1

Y
0
1
0
1

X&Y
0
1
1
1

X=10
Y=11

0000 1010

0000 1011
__________
X|Y=?(output=11)
0000 1011

Bitwise XOR(^): carot/circumflex


This operator performs exclusive OR operation on individual bits
X
0
0
1
1

Y
0
1
0
1

X&Y
0
1
1
0

X=10
Y=11

0000 1010

0000 1011
__________
X^Y=?(output=1)
0000 0001

22

Bitwise Left Shift(<<): This operator shift the bits towards left a specified number of
positions
X=10
0
0
0
0
1
0
1
0
X<<2
0

Bitwise right shift(>>): This operator shifts the bit towards right a specified number
X=10
0

X>>2

Bitwise zero fill right shift(>>>)


First bit specifies the sign bit 0 +ve and 1 ve
The sign bit is not protected
class Bits
{
public static void main(String ar[])
{
byte x,y;
x=10; y=11;
System.out.println(~x=:+ (~x));
System.out.println(x&y=:+ (x&y));
System.out.println(x|y=:+ (x|y));
System.out.println(x^y=:+ (x^y));
System.out.println(x<<2=:+ (x<<2));
System.out.println(x>>2=:+ (x>>2));
}
}
Note: Bit wise operators are used in embedded system programs
The rule to deal with equal precedence operators is that all binary operators except for the
assignment operators are evaluated from left to right; assignment operators are evaluated
from right to left.
23

Operators
Postfix
Unary
Multiplicative
Additive
Shift
Relational
Equality
bitwise AND
bitwise
exclusive OR
bitwise
inclusive OR
logical AND
logical OR
Ternary
Assignment

Precedence
expr++,, expr-++expr, --expr, +expr,
-expr ~ !
*/%
+<< >> >>>
< > , <= , >= instanceof
== , !=
&
^
|
&&
||
?:
= , +=, -=, *=, /=,
%=, &=, ^=, |=, <<=,
>>=, >>, >=

Java - Math class in Java


The Math class is used to operate the calculations. There is not necessary to import any
package for the Math class because this is already in java.lang package.
All the functions have been explained below with example :
E
This is E field of the Math class which returns you a default exponent value that is closer
than any other to e, the base of the natural logarithms.
PI
This is also a field of the Method class which returns you a default pi value, the ratio of
the circumference of a circle to its diameter.
abs()
This is the abs() function which returns you the absolute number.
ceil()
This is the ceil() function which returns you the smallest value but greater than the
argument.
exp()
This is the exp() function which returns you the exponential value raised to the power of
a double value.
floor()
This is the floor() function which returns you the largest value but less than the argument.
24

IEEEremainder()
This is the IEEEremainder() which returns you the remainder for the given dividend and
divisor.
max()
This is the max() function which distinguishes the maximum value from the two given
value.
min()
This is the min() function which distinguishes the minimum value from the two given
value.
pow()
This is the pow() function which returns you the number raised to the power of a first
given value by the another one.
random()
This is the random() function which returns you the random number. It is absolutely
system generated.
rint()
This is the rint() function which returns you a value closest to the given value.
round()
This is the round() function which returns you a value that is in the rounded form.
sqrt()
This is the sqrt() function which returns you the square root of the specified value.

Package : package is a sub directory containing group of class/interface


Java
library(group
of
packageclass/interfacemethodsjava.langString System.

package)

Differences between #include and import


- # include copies all lines of the header file into a C program Thus is
waste the memory & processor time also.
-

Import statement directs the JVM to go to the package execute the


code come back & substitute the result in the java program.
Import does not copy the libraries and #include copies.

class First
{
Block of statements;
}
Block: A group of statements written inside left and right curly braces.
- One method is needed to execute a java program i.e main()
- A method performs a task having a group of statements
- Variables are memory locations to store values
- Amethod needs some variables.
- void main(String args[])

25

void (no value is returned, void doesnt allow to return a value)


argsvariable in which we can store one string
Values passed to main method area called command Line arguments
JVM always starts execution from main() method

Two steps are used to call a method:


1. Create an object to the class to which that method belongs.
className objname=new className();
Ex: Test t=new Test();
2. Then call the method using
ObjectName.methodname();
Obj.main()
-

when we call the main() method the main method is executed so for
calling we need an object and for getting obj we need to run main();

class Test
{
void main(String args[])
{
Test t=new Test();
t.main();
}
}
- So to avoid this or to break the chain we use static methods.
- A static method is a method that is called and executed without an
object.
- Static void main(String args[])
-

Public means the method is available outside our program to other


program(JVM)
If public is not written the main method is not available to JVM.

System.out.println(welcome);
- System.out is a method provided by Java software
- We cannot create an object to print stream class
- Out is a static variable
- System.out is an object of PrintStream class that object takes the input
and gives the output on monitor.

Hello world (First java program)


Java is a case sensitive programming language.

26

For Example
hello world !=(not equal to) Hello World
Write the following code into your note pad to run the Hello World program .
class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello World!");
}
}
-

Save the file and Please remember the location where you save your
file.
In this example we have saved the file in the
"C:\javatutorial\example" directory.
The file name should be match the class name and to save the file give
the .java extension. e.g. HelloWorld.java
Now open the command prompt to compile the HelloWorld.java
program.
Go to the directory where you have saved the file ( in our case
C:\javatutorial\example>) and issue the following command to
compile the program:

C:\javatutorial\example>javac HelloWorld.java
Once the compilation is successful a new file will be created with the name
HelloWorld.class. To run the program issue the following command on command
prompt:
C:\javatutorial\example>java HelloWorld
You will see the following result on the command prompt.
Hello World!
Here is the screen shot of the above steps:

27

println(): displays the result in the next line and throws the cursor to
the next line
print() : displays the result and keeps the cursor in the same line and at
the same position.
It will execute the .class file & displays the output.
Then it will quit from memory

Escape Sequences:
\n next line
\t horizontal tab space
\r enter button
\b backspace button
\\ displays \
\ displays
\ displays
Important Note:
-

Variables passed in the method is called parameters


Values passed to those variables are called arguments
Assignment can be done many times
Initialization can be done only once.
NULL is not a keyword.
To find the address of particular memory location in java by using
hashcode of the object class.
IsSizeOf is an operator but not a keyword

Java is case sensitive


In java every statement should end with ;

28

For classname we should start with capital letters


Naming Conventions start the class Name with capital letters which is
a rule.

Naming Conventions in Java


2. Each word of class names and interface names starts with
capital letter
3. Ex: String ,String Buffer
4. DataInputStream
2. Package Names: In java are written in all small letters
Ex: java.awt, java.io, javax.swing
3. Method Names: start with a small letter, then each word start with a capital
Ex: println(),getchars(), readLine()
4. Variable names: also follow the above rule
Ex: age,empName,
5. Constant Variables: should be written using capital letters
Ex: PI, MAX_VALUE
Java.lang: is a package that is imported into every program by default.Other packages
must be imported
Important Packages of JAVA
1. java.lang: In this package most of the classes are final, this package got primary
classes and interfaces essential for Java language.It consists of Wrapper
classes(used for creating objects)
2. java.util: This package contains useful classes and interfaces like stack, linked
lists,Hashtable and etc
3. java.io: This package handles files and input-output related tasks.
4. java.awt: This package helps to develop GUI.It consists of 2 important packages,
namely java.awt.event and java.awt.image
5. javax.swing: This package helps to develop GUI like java.awt.
6. java.net: client-server programming can be done using this package.It uses
TCP/IP internally
7. java.applet: Smallest package in java, Applets are some intelligent programs that
comes from server which travel from one place to another pace on ternet.
8. java.sql: This package helps to connect to database like oracle,and utilize them in
java
9. java.beans:
Beans
are
software
reusable
components
(ex:
PushButton,RadioButton,Checkbox are examples of components)
10. java.rmi: (Remote Method Invocation) The objects which exist on one computer
in network can be invoked from another computer and can be used.
11. javax.servlet: Servlets are server side programs which can communicate with
several clients at a time.

29

Java - Identifier and Primitive Data Types in java


-

Identifier is a simple variable name which is defined as the value


container.
The type of value stored by identifier is defined by the special java
keyword is termed as primitive data type.

Primitive Data Types


Keyword Description

Size/Format

Integers
Byte

Byte-length integer

8-bit two's complement

Short

Short integer

16-bit two's complement

Int

Integer

32-bit two's complement

Long

Long integer

64-bit two's complement

Real numbers
Float

Single-precision floating point

32-bit IEEE 754

Double

Double-precision floating point

64-bit IEEE 754

Char

A single character

16-bit Unicode character

boolean

A boolean value (true or false) true or false

Other types

Controlling the program


-

We can control the program flow by using statements like decisionmaking statements (if-then, if-then-else, switch),
the looping statements (for, while, do-while),
and the branching statements (break, continue, return)

Selection
- In this section we will learn how to use if-then, if-then else and switch statements
The if statement
- This code gets executed if and only if the test evaluates to true.
- That is the if statement in Java is a test of any boolean expression.
- The statement following the if will only be executed when the boolean
expression evaluates to true.
30

if(condition)
System.out.println(AAA);
The general form of the if else statement is:
if (condition)
statement1;
else
statement2;
-

The above format shows that an else statement will be executed


whenever an if statement evaluates to false. For instance,

class compare{
public static void main(String[] args){
int a = 20;
int b = 40;
if (a<b){
System.out.println("a is smaller");
}
else{
d
System.out.println("b is smaller");
}
}

The switch statement


- This means it allows any number of possible execution paths.
- It depends on the value of a variable or expression. The switch
statement in Java is the best way to test a single expression against a
series of possible values and executing the code.
Here is the general form of switch statement:
switch (expression){
case 1:
code block1
case 2:
code block2
.
.
default:
code default;
}

31

The execution of the switch statement takes place by comparing the


value of the expression with each of the constants.
The comparison of the values of the expression with each of the
constants occurs after the case statements. Otherwise, the statements
after the default statement will be executed.

class Switch{
public static void main(String[] args){
int week = 5;
switch (week){
case 1: System.out.println("monday"); break;
case 2: System.out.println("tuesday"); break;
case 3: System.out.println("wednesday"); break;
case 4: System.out.println("thursday"); break;
case 5: System.out.println("friday"); break;
case 6: System.out.println("saturday"); break;
case 7: System.out.println("sunday"); break;
default: System.out.println("Invalid week");break;
}

The for Statement


- For statement consists of tree parts i.e. initialization, condition, and
iteration.
- initialization : It is an expression that sets the value of the loop control
variable. It executes only once.
- condition : This must be a boolean expression. It tests the loop control
variable against a target value and hence works as a loop terminator.
- iteration : It is an expression that increments or decrements the loop
control variable.
Here is the form of the for loop:
for(initialization; condition; iteration){
//body of the loop
}
class printDemo
{
public static void main(String[] args)
for (int i = 0; i<10; i++){
System.out.println("Hello World!");
}
}

32

The while and do-while Statements


-

while statement continually executes a block of statements while a


particular condition is true.

while (expression)
{
statement(s)
}
Lets see the flow of the execution of the while statement
1. Firstly, It evaluates the condition in parentheses, yielding true or false.

in

steps:

2. Secondly, It continues to execute the next statement if the condition is false and exit
the while statement.
3. Lastly, If the condition is true it executes each of the statements between the brackets
and then go back to step 1.
For example:
class Bonjour{
public static void main (String args[]){
System.out.print("Bonjour ");
// Say Hello
int i = 0;
// Declare and initialize loop counter
while (i < args.length){
// Test and Loop
System.out.print(args[i]);
System.out.print(" ");
i = i + 1;
// Increment Loop Counter
}
System.out.println();
// Finish the line
}
}

do-while statement
Here is the syntax:
do
{
statement(s)
}
while (expression);
class DoWhileDemo
{
public static void main (String args[])

33

{
int i = 0;
do{
System.out.print("Bonjour");
// Say Bonjour
System.out.println(" ");
i = i + 1;
// Increment LoopCounter
}
while (i < 5);

In the above example, it will enter the loop without checking the
condition first and checks the condition after the execution of the
statements.
That is it will execute the statement once and then it will evaluate the
result according to the condition.

Jumping
-

Using for, while and do-while loops is not always the right idea to use
because they are cumbersome to read.
Using jumping statements like break and continue it is easier to jump
out of loops to control other areas of program flow.

The break Statement


We use break statement to terminate the loop once the condition gets satisfied.
class BreakDemo
{
public static void main(String[] args)
{
for (int i = 0; i < 5; i++)
{
System.out.println(i);
if (i==3)
{
break ;
}
}
}
}

The break statement has two forms: labeled and unlabeled. You saw
the labeled form in the above example i.e. a labeled break terminates
an outer statement.
However, an unlabeled break statement terminates the innermost loop
like switch, for, while, or do-

34

while statement
- Now observe the example of unlabeled form below. We have used two
loops here two print '*'. In this example, if we haven't use break
statement thus the loop will continue and it will give the output as
shown below.
class BreaklabDemo1
{
public static void main(String[] args)
{
for (int i = 0; i < 10; i++) {
System.out.print("\n");
for (int j = 0; j<=i; j++)
{
System.out.print("*");
if (j==5)
{
// break;
}
}
}

The continue statement


- Sometimes we do not need to execute some statements under the loop
then we use the continue statement that stops the normal flow of the
control and control returns to the loop without executing the
statements written after the continue statement.
- There is the difference between break and continue statement that the
break statement exit control from the loop but continue statement
keeps continuity in loop without executing the statement written after
the continue statement according to the conditions.

35

public class Continue


{
public static void main(String[] args)
{
Thread t = new Thread();
int a = 0;
try
{
for (int i=1;i<10;i++)
{
if(i == 5)
{
continue;
//control will never reach here (after the continue statement).
//a = I;
}
t.sleep(1000);
System.out.println("chandan");
System.out.println("Value of a : " + a);
}
}
catch(InterruptedException e){}
}
}
Introduction to Java Arrays
-

The java array enables the user to store the values of the same type in
contiguous memory allocations.

Arrays are always a fixed length abstracted data structure which can
not be altered when required.

The Array class implicitly extends java.lang.Object so an array is an


instance of Object.
Structure of Arrays
-

Suppose an array contains "n" integers.


The first element of this array will be indexed with the "0" value and
the last integer will be referenced by "n-1" indexed value.
Presume an array that contains 12 elements as shown in the figure.
Each element is holding a distinct value.
Here the first element is refrenced by a[0] i.e. the first index value. We
have filled the 12 distinct values in the array each referenced as:

36

a[0]=1
a[1]=2
...
a[n-1]=n
...
a[11]=12
The figure below shows the structure of an Array more precisely.

Array Declaration
- As we declare a variable in Java, An Array variable is declared the
same way.
- Array variable has a type and a valid Java identifier i.e. the array's type
and the array's name.
- By type we mean the type of elements contained in an array.
- To represent the variable as an Array, we use [] notation.
- These two brackets are used to hold the array of a variable.
- By array's name, we mean that we can give any name to the array,
however it should follow the predefined conventions.
- Below are the examples which show how to declare an array :-

int[]array_name;

//declares an array of integers

String[]names;
int[][] matrix; //this is an array of arrays

int[]

It is essential to assign memory to an array when we declare it.


Memory is assigned to set the size of the declared array. for example:

array_name = new int[5];

Here is an example that creates an array that has 5 elements.

37

public class Array


{
public

static

void

main(String[]

args)

{
}

int[] a = new int[5];

Array Initialization
- After declaring an array variable, memory is allocated to it. The "new"
operator is used for the allocation of memory to the array object. The
correct way to use the "new" operator is
String names[];
names = new String[10];
-

Here, the new operator is followed by the type of variable and the
number of elements to be allocated. In this example [] operator has
been used to place the number of elements to be allocated.

Lets see a simple example of an array,


public class Sum
{
public static void main(String[] args)
{
int[] x = new int [101];
for (int i = 0; i<x.length; i++ )
x[i] = i;
int sum = 0;
for(int i = 0; i<x.length; i++)
sum += x[i];
System.out.println(sum);
}
}

Array Usage
-

We have already discussed that to refer an element within an array, we


use the [] operator.
The [] operator takes an "int" operand and returns the element at that
index.
We also know that the array indices start with zero, so the first element
will be held by the 0 index. For Example :-

int month = months[4];

//get the 5th month (May)

38

Example:

String months[] =
{"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"July", "Aug", "Sep", "Oct", "Nov", "Dec"};
//use the length attribute to get the number
//of elements in an array
for (int i = 0; i < months.length; i++ ) {
System.out.println("month: " + month[i]);

In this loop int i = 0; indicates that the loop starts from the 0th position
of an array and goes upto the last position which is length-1, i <
months.length; indicates the length of the array and i++ is used for the
increment in the value of i which is i = i+1.

Multi-dimensional arrays
-

A multi-dimensional array of dimension n is a collection of items.

int[][] x = new int[3][5];


-

The expression x[i] is used to select the one-dimensional array; the


expression x[i][j] is used to select the element from that array.
The first element of this array will be indexed with the "0" value and
the last integer will be referenced by "length-1" indexed value.
There is no array assignment operator.

Two-dimensional arrays
Two-dimensional arrays are defined as "an array of arrays". Since an array type is a firstclass Java type,
The command
int[][] A = new int[3][4]
-

declares a variable, A, of type int[][], and it initializes that variable to


refer to a newly created object.
To process a two-dimensional array, we use nested for loops.

39

int[][] a2 = new int[10][5];


// print array in rectangular form
for (int r=0; r<a2.length; r++) {
for (int c=0; c<a2[r].length; c++) {
System.out.print(" " + a2[r][c]);
}
System.out.println("");
}

OOPs and Its Concepts in Java


-

Object Oriented Programming or OOP is the technique to create


programs based on the real world, here in the OOP programming
model programs are organized around objects and data rather than
actions and logic.
Objects in programming language have certain behavior, properties,
type, and identity.
In OOP based language the principal aim is to find out the objects to
manipulate and their relation between each other.
OOPs in Java include class, method, inheritance, encapsulation,
abstraction, polymorphism etc.

Class
-

A set of objects with common behavior. The class definition describes


all the properties, behavior, and identity of objects present within that
class.

Objects are the basic unit of object orientation with behavior, identity,
these are part of a class but are not the same.
An object is expressed by the variable and methods within the objects.
Again these variables and methods are distinguished from each other
as instant variables, instant methods and class variable and class
methods.

Object
-

Methods -

Methods define the abilities of an object.

Inheritance Acquiring the properties of one class to the other is called Inheritance.
Abstraction - The process of abstraction in Java is used to hide certain details and only
show the essential features of the object.

40

Encapsulation making a class and object as a single element.


Polymorphism - It describes the ability of the object in belonging to different types with
specific behavior of each type.

Access Modifiers
Access Modifiers : Access modifiers are used to specify the visibility and accessibility of
a class.
public keyword specifies that the public class, the public fields and the public methods
can be accessed from anywhere.
private: This keyword provides the accessibility only within a class i.e. private fields
and methods can be accessed only within the same class.
protected: This modifier makes a member of the class available to all classes in the same
package and all sub classes of the class.
default : Its not a keyword. When we don't write any access modifier then default is
considered. It allows the class, fields and methods accessible within the package only.
Access Specifiers
-

Access specifiers are used to Controlling Access to Members of a


Class.
Four types of Access Specifiers can be found in Java namely

1. Public: public members of a class are available outside the class


2. Protected: Members are same as public, protected members are available outside the
class.
3. Private:Represents private members are not available outside the class
4. Defaults:When no access specifier is used Java compiler uses default access specifier.
- Default members are available outside the class.

Programming Structure:
package ;
class ClassName
{
Declaration of variables;
Access-specifier return-type function-name(argument-list)
{
block of statements;
}
public static void main(String[] args)
41

{
Instantiation(creating an object);
//syntax to create an object :
//ClassName object=new ClassName();
}
}

Function Prototypes:
There are 4 types of function prototypes are available in java
1.
2.
3.
4.

A function with out arguments and without return statement


A function with out arguments and with return statement.
A function with arguments and without return statement.
A function with arguments and with return statement.

// Example for first function prototype


import java.io.*;
class Rectangle
{
int length, breadth,a;
public void Rect()
{
length=10;
breadth=6;
}
public void Area()
{
a=length*breadth;
System.out.println("Area of a Rectangle="+a);
}
public static void main(String[] args)
{
Rectangle r=new Rectangle();
r.Rect();
r.Area();
}
}
// Example for Second Function prototype
import java.io.*;
class Rectangle
{

42

int length, breadth;


public void Rect()
{
length=10;
breadth=6;
}
public int Area()
{
return(length*breadth);
}
public static void main(String[] args)
{
Rectangle r=new Rectangle();
r.Rect();
System.out.println("Area of a Rectangle="+r.Area());
}
}
// Example for Third function prototype
import java.io.*;
class Rectangle
{
int length, breadth,a;
public void Rect(int l,int b)
{
length=l;
breadth=b;
}
public void Area()
{
a=length*breadth;
System.out.println("Area of a Rectangle=" +a);
}
public static void main(String[] args)
{
Rectangle r=new Rectangle();
r.Rect(10,7);
r.Area();
}
}
// Example for Fourth Function Prototype

43

import java.io.*;
class Rectangle
{
int length, breadth,a;
public void Rect(int l,int b)
{
length=l;
breadth=b;
}
public int Area()
{
return(length*breadth);
}
public static void main(String[] args)
{
Rectangle r=new Rectangle();
r.Rect(10,7);
System.out.println("Area of a Rectangle=" +r.Area());
}
}
// Over Loading a Method
import java.io.*;
class Rectangle
{
int length, breadth,a;
public void Rect()
{
length=8;
breadth=3;
}
public void Rect(int l)
{
length=breadth=l;
}
public void Rect(int l,int b)
{
length=l;
breadth=b;
}
public int Area()

44

{
return(length*breadth);
}
public static void main(String[] args)
{
Rectangle r=new Rectangle();
r.Rect();
System.out.println("Area of a Rectangle=" +r.Area());
r.Rect(5);
System.out.println("Area of a Rectangle=" +r.Area());
r.Rect(9,4);
System.out.println("Area of a Rectangle=" +r.Area());
}
}

Constructor:
-

Constructor creates an instance for the class.


Constructor initiates(initialize) something related to the classs
methods.
Constructor is the method which name is same to the class, which
is used to initialize the instance variables of a class.
But there are many difference between the method(function) and
the Constructor.
Constructor does not return any values.
Constructors are not required to call into main function explicitly.

Types of Constructors:
1.
2.
3.
4.

Default Constructors: A constructor with out any parameters/arguments


Parameterized Constructor: A constructor with parameters
Copy of Constructor:
Overloading Constructor:With the same Constructor name but different
signatures(parameters)

// Example for Default Constructor


import java.io.*;
class Rectangle

45

{
int length, breadth;
public Rectangle()
{
length=8;
breadth=3;
}
public int Area()
{
return(length*breadth);
}
public static void main(String[] args)
{
Rectangle r1=new Rectangle();
System.out.println("Area of a Rectangle=" +r1.Area());
}
}
// Example for Parameterized Constructor
import java.io.*;
class Rectangle
{
int length, breadth;
public Rectangle(int l,int b)
{
length=l;
breadth=b;
}
public int Area()
{
return(length*breadth);
}
public static void main(String[] args)
{
Rectangle r1=new Rectangle(8,3);
System.out.println("Area of a Rectangle=" +r1.Area());
}
}

//Another Example:

46

import java.io.*;
class Rectangle
{
int length, breadth,a;
public Rectangle(int length,int breadth)
{
this.length=length;
this.breadth=breadth;
}
public int Area()
{
return(length*breadth);
}
public static void main(String[] args)
{
Rectangle r1=new Rectangle(8,3);
System.out.println("Area of a Rectangle=" +r1.Area());
}
}
Note: this is used to invoke a constructor of the same class.
// Overloading Constructor
import java.io.*;
class Rectangle
{
int length, breadth,a;
public Rectangle()
{
length=8;
breadth=3;
}
public Rectangle(int l)
{
length=breadth=l;
}
public Rectangle(int l,int b)
{
length=l;
breadth=b;

47

}
public int Area()
{
return(length*breadth);
}
public static void main(String[] args)
{
Rectangle r1=new Rectangle();
System.out.println("Area of a Rectangle=" +r1.Area());
Rectangle r2=new Rectangle(8);
System.out.println("Area of a Rectangle=" +r2.Area());
Rectangle r3=new Rectangle(9,3);
System.out.println("Area of a Rectangle=" +r3.Area());
}
}

Inheritance
-

Acquiring the properties of one class to the other class is called


Inheritance
It is the concept that is used for reusability purpose.
Inheritance is the mechanism through which we can derived classes
from other classes.
The derived class is called as child class or the subclass or we can say
the extended class and the class from which we are deriving the
subclass is called the base class or the parent class.
To derive a class in java the keyword extends is used.
When we hear the word vehicle then we got an image in our mind that
it moves from one place to another place it is used for traveling or
carrying goods but the word vehicle does not specify whether it is two
or three or four wheeler because it is a general word.
But the word car makes a more specific image in mind than vehicle,
that the car has four wheels .
It concludes from the example that car is a specific word and vehicle is
the general word.
If we think technically to this example then vehicle is the super class
(or base class or parent class) and car is the subclass or child class

48

because every car has the features of it's parent (in this case vehicle)
class.
The following kinds of inheritance are there in java.
Single Inheritance
Multilevel Inheritance
Pictorial Representation of Simple and Multilevel Inheritance

Single Inheritance

Multilevel Inheritance

Single Inheritance
When a subclass is derived simply from it's parent class then this mechanism is known
as single inheritance. In case of single inheritance there is only a sub class and it's parent
class.
eg.
class A {
int x;
int y;
int get(int p, int q){
x=p; y=q; return(0);
}
void Show(){
System.out.println(x);
}
}
class B extends A{
public static void main(String args[]){
A a = new A();
a.get(5,6);
a.Show();
}
void display(){
System.out.println("B");
}
}

49

Multilevel Inheritance
- When a subclass is derived from a derived class then this mechanism
is known as the multilevel inheritance.
- The derived class is called the subclass or child class for it's parent
class and this parent class works as the child class for it's just above
( parent ) class. Multilevel inheritance can go up to any number of
level.
e.g.
class A {
int x;
int y;
int get(int p, int q){
x=p; y=q; return(0);
}
void Show(){
System.out.println(x);
}
}
class B extends A{
void Showb(){
System.out.println("B");
}
}
class C extends B{
void display(){
System.out.println("C");
}
public static void main(String args[]){
A a = new A();
a.get(5,6);
a.Show();
}
}

Multiple Inheritance
- The mechanism of inheriting the features of more than one base class
into a single class is known as multiple inheritance.
- Java does not support multiple inheritance but the multiple inheritance
can be achieved by using the interface.
super keyword
-

The super is java keyword.


It is used to access the members of the super class.
It is used for two purposes in java.
The first use of keyword super is to access the hidden data variables of
the super class hidden by the sub class.
e.g. Suppose class A is the super class that has two instance variables
as int a and float b.
50

class B is the subclass that also contains its own data members named
a and b. then we can access the super class (class A) variables a and b
inside the subclass class B just by calling the following command.

super.member;
-

Here member can either be an instance variable or a method.


This form of super most useful to handle situations where the local
members of a subclass hides the members of a super class having the
same name.

class A{
int a;
float b;
void Show(){
System.out.println("b in super class:
}

" + b);

}
class B extends A{
int a;
float b;
B( int p, float q){
a = p;
super.b = q;
}
void Show(){
super.Show();
System.out.println("b in super class:
System.out.println("a in sub class:
}

" + super.b);
" + a);

public static void main(String[] args){


B subobj = new B(1, 5);
subobj.Show();
}

The second use of the keyword super in java is to call super class
constructor in the subclass.
This functionality can be achieved just by using the following
command.

super(param-list);
-

Here parameter list is the list of the parameter requires by the


constructor in the super class.
super must be the first statement executed inside a super class
constructor.
51

If we want to call the default constructor then we pass the empty


parameter list.

class A{
int a;
int b;
int c;
A(int p, int q, int r){
a=p;
b=q;
c=r;
}
}
class B extends A{
int d;
B(int l, int m, int n, int o){
super(l,m,n);
d=o;
}
void Show(){
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}

public static void main(String args[]){


B b = new B(4,3,8,7);
b.Show();
}

Abstract methods and classes


Abstract Method
-

An abstract method one that have the empty implementation. All the
methods in any interface are abstract by default.
Abstract method provides the standardization for the " name and
signature" of any method.
One can extend and implement to these methods in their own classes
according to the requirements.

e.g.
public abstract abs_value();

Abstract Class
-

abstract classes are those that works only as the parent class or the
base class.

52

Subclasses are derived to implement the methods inherited from the


abstract class (base class).
Abstract classes are not instantiated directly.
First extend the base class and then instantiate (create objects).
Abstract classes are generic in nature and implement to those methods
that are used commonly by the subclasses with common
implementation.
An abstract class should be declared with abstract keyword.
All the abstract methods of abstract class should be
implemented(body) in the subclass
If any one abstract method is not implemented , then that subclass
should be declared as abstract.
A class cannot be both final and abstract.

e.g.

abstract class A{
public abstract abs_value();

void show(){
System.out.println("This is an abstract class");
}

Interface
-

Interface is the way just to say something to a media by using another


media.
An interface contains all abstract methods.
An interface is the specification of the method prototypes.
No method body in interface.
We cannot create object to interface.
Implementation class is a class where all the methods of an interface
are implemented.
One single interface can have several implementation class.
We can create an object to implementation class.
Interface is nothing but the collection of methods with empty
implementations and constants variables ( variables with static and
final declarations ).
All the methods in an interface are "public and abstract" by default.
Since interfaces are abstract in nature so they cannot be directly
instantiated.
To define the methods of an interface the keyword "implements" is
used.
Interfaces are similar to abstract classes but the major difference
between these two is that interface have all the methods abstract while
in case of abstract classes must have at least one abstract method.

53

Example:
-

TV Remote is the interface because it is the medium to give the


command to a TV in order to change the channels or to ON/OFF the
TV.
Electric switch is also the interface's example.

Interface Definition
visibility mode interface interfaceName{
constant variable declarations
abstract method declarations
}

e.g.
public interface RacingCar{
public void startcar (int Obj);
public void changegear (int Obj);
public void incrrace (int Obj);
public void stopcar (int Obj);
}

Marker Interface
- Interfaces with no methods are known as marker interfaces.
Marker interfaces are Serializable, Clonable, SingleThreadModel,
Event listener.
- Marker Interfaces are implemented by the classes or their super classes
in order to add some functionality.
-

e.g. Suppose you want to persist (save) the state of an object then you
have to implement the Serializable interface otherwise the compiler
will throw an error.

Suppose the interface Clonable is neither implemented by a class


named Myclass nor it's any super class, then a call to the method
clone() on Myclass's object will give an error.

This means, to add this functionality one should implement the


Clonable interface. While the Clonable is an empty interface but it
provides an important functionality.

Difference between Interfaces and abstract classes


54

Features

Interface

Abstract Class

Methods

An interface contains all theAn abstract class must have at least one
methods
with
emptymethod with empty implementation.
implementation.

Variables

The variables in interfaces areAbstract classes may contain both


final and static.
instance as well as static variables.

Multiple In java multiple inheritance isAbstract classes does not provide this
Inheritance
achieved by using the interfacefunctionality.
(by implementing more than
one interface at a time)

Additional
Functions

If we add a method to anIn Abstract classes we can add a method


interface then we will have towith default implementation and then
implement this interface by anywe can use it by extending the abstract
class..
class.

String Handling
Strings: A string represents a group of characters
Note : String is a class in java.lang package
Creating a string: 1. we can create a string by directly assigning a string literal to a
string object
Ex: String str=Hello;
Object: allocating memory to store data.Internally JVM creates object
2. We can create a string class object using new operator
Ex: String str=new String(hello);
3. We can convert a character array into String class object
Ex: char ch[]={H,e,l,l,o};
String str=new String(ch);
55

String str=new String(ch,1,3);

Java.lang.String:
1. String concat(String str)
Concatenates the calling string with str.concat receives one string object and
returns string.
Note: + will do the same.
Ex: String s1=Hydera;
String s2=bad;
String x=s1.concat(s2);
2. int length (): length gives no of characters in a string returns the length of a string
String s1=Hydera;
Int n=s1.length();
3. char charAt(int index): returns the character at the specified location(from 0)
4. int compareTo(String str):returns a negative value if the string comes before string in
dictionary order, a positive value, if the string comes after str, or 0 if the strings are equal
Ex: String s1=apple;
String s2=grapes;
int n=s1.compareTo(s2);
n==0 if s1==s2;
n>0 if s1>s2;
n<0 if s1<s2
StringBuffer class in Java
StringBuffer is mainly used for the dynamic string concatenation which enhances the
performance. A string buffer implements a mutable sequence of characters. A string
buffer is like a String, but can be modified. At any point of time it contains some
particular sequence of characters, but the length and content of the sequence can be
changed through certain method calls. There are some functions used in the given
example.
append()
This is the append() function used for the concatenate the string in string buffer. This is
better to use for dynamic string concatenation.
insert()
This is the insert() function used to insert any string or character at the specified position
in the given string.
reverse()
This is the reverse() function used to reverse the string present in string buffer.
setCharAt()

56

This is the setCharAt() function which is used to set the specified character in buffered
string at the specified position of the string in which you have to set the given character.
charAt()
This is the charAt() function which is used to get the character at the specified position of
the given string.
substring()
This is the substring() function which is used to get the sub string from the buffered string
from the initial position to end position (these are fixed by you in the program).
deleteCharAt()
This is the deleteCharAt() function which is used to delete the specific character from the
buffered string by mentioning that's position in the string.
length()
This is the length() function is used to finding the length of the buffered string.
delete()
This is the delete() function is used to delete multiple character at once from n position to
m position (n and m are will be fixed by you.) in the buffered string.
capacity()
This is the capacity() function is used to know about the current characters kept which is
displayed like : number of characters + 6.
import java.io.*;
public class stringBuffer{
public static void main(String[] args) throws Exception{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String str;
try{
System.out.print("Enter your name: ");
str = in.readLine();
str += ", This is the example of SringBuffer class and it's functions.";
//Create a object of StringBuffer class
StringBuffer strbuf = new StringBuffer();
strbuf.append(str);
System.out.println(strbuf);
strbuf.delete(0,str.length());
//append()
strbuf.append("Hello");
strbuf.append("World");
System.out.println(strbuf);

//print HelloWorld

//insert()
strbuf.insert(5,"_Java ");
System.out.println(strbuf);

//print Hello_Java World

//reverse()
strbuf.reverse();
System.out.print("Reversed string : ");
System.out.println(strbuf);
//print dlroW avaJ_olleH

57

strbuf.reverse();
System.out.println(strbuf);

//print Hello_Java World

//setCharAt()
strbuf.setCharAt(5,' ');
System.out.println(strbuf);

//prit Hello Java World

//charAt()
System.out.print("Character at 6th position : ");
System.out.println(strbuf.charAt(6));
//print J
//substring()
System.out.print("Substring from position 3 to 6 : ");
System.out.println(strbuf.substring(3,7));
//print lo J
//deleteCharAt()
strbuf.deleteCharAt(3);
System.out.println(strbuf);

//print Helo java World

//capacity()
System.out.print("Capacity of StringBuffer object : ");
System.out.println(strbuf.capacity());
//print 21
//delete() and length()
strbuf.delete(6,strbuf.length());
System.out.println(strbuf);

//no anything

}
catch(StringIndexOutOfBoundsException e){
System.out.println(e.getMessage());
}

Making Tokens of a String


-

Tokens can be used where we want to break an application into tokens.


We have to break a String into tokens as well as we will know how
many tokens has been generated.
In the program a string is passed into a constructor of StringTokenizer
class.
StringTokenizer is a class in java.util.package.
We are using while loop to generate tokens.

The following methods have been used in this program.

countTokens(): It gives the number of tokens remaining in the string.


hasMoreTokens(): It gives true if more tokens are available, else false.
nextToken(): It gives the next token available in the string.

58

To break a string into tokens what we need first is to create a class


named StringTokenizing.
Inside this class we will declare our main method.
Make an object of class StringTokenizer and pass one string inside the
constructor which you want to break into tokens.
By using the instance of StringTokenizer call the method
countTokens() which gives the number of tokens remaining in the
string.
It is a method of StringTokenizer class.
If the object have more tokens available then it will call method
hasMoreTokens() and print the tokens by using nextToken().

The code of the program is given below:


import java.util.*;
public class StringTokenizing{
public static void main(String[] args) {
StringTokenizer stringTokenizer = new
StringTokenizer("You are tokenizing a string");
System.out.println("The total no. of tokens
generated : " + stringTokenizer.countTokens());
while(stringTokenizer.hasMoreTokens()){
System.out.println(stringTokenizer.nextToken());
}
}
}

The StringBuffer is a class that implements multiple sequence of


characters.
The following program construct a string buffer that has '0' capacity.
This program inserts the data in the string buffer using the insert()
method that provides the facility for adding the data in any positions.
But the append() method also add data in string buffer in ending
position. This method inserts always last or end position.

Description of code:
StringBuffer(int len):
This is the constructor of StringBuffer class that implements multiple sequence of
characters. This constructor constructs a string buffer that have no characters. It
takes initial capacity that have to initialized.
insert(int pos, String str):
This method inserts the string into the object of StringBuffer. It takes following
parameters:

59

pos: This is the position that have to be used for inserting the data.
str: This is the string that have to inserted.
append(String str):
This is the method that inserts the string into string buffer. It always inserts a string at last
position.
Here is the code of program
import java.lang.*;
public class AppendInsert{
public static void main(String[] args) {
System.out.println("StringBuffer insert and append example!");
StringBuffer sb = new StringBuffer(0);
//First position
System.out.println(sb.insert(0, "vinod"));
int len = sb.length();
//last position
System.out.println(sb.insert(len, "Deepak"));
//Six position
System.out.println(sb.insert(6, "Raj"));
//Always last
System.out.println(sb.append("Mohit"));
}
}

Passing Command Line Arguments


-

Sequence of character from command line at run time.


Store these strings into an array string.
Show these strings on console as output.
If user forget enter string at run time on command line argument then
the message "No values has been entered at the command line" will
displayed on screen.

public class ArgumentPassingExample{


public static void main(String[] args){
int num=args.length;
String s[]=new String[num];
if(num>0){
System.out.println("The values enter at
argument command line are:");
for (int i = 0; i <num ; i++)
{
System.out.println("Argument " + (i + 1) +
" = " + args[i]);
}
}
else{
System.out.println("No values has been
entered at the command line.");
}
}}

60

Util Packages:
A collection sometimes called a container is simply an object that groups multiple
elements into a single unit. Collections are used to store, retrieve, manipulate, and
communicate aggregate data

Collection Framework
A collections framework is a unified architecture for representing and
manipulating collections. All collections frameworks contain the following:
Interfaces: These are abstract data types that represent collections. Interfaces
allow collections to be manipulated independently of the details of their
representation
Implementations: These are the concrete implementations of the collection
interfaces. In essence, they are reusable data structures.

A collection sometimes called a container is simply an object that


groups multiple elements into a single unit.
Collections are used to store, retrieve, manipulate, and communicate
aggregate data.

- The Collections Framework consists of


three parts
1. interfaces, the abstract data types that the framework supports.
2. implementations, the concrete versions of these interfaces.
3. algorithms, the predefined actions that can be defined on either the
interfaces or their implementations.
1. All implementations are unsynchronized.
2. All implementations are serializable and cloneable
3. All implementations support having null elements.
-

The predefined algorithms for supporting the framework are found


in the Collections and Arrays classes

Interface type and its implementation


61

Interface
Type
Set
SortedSet
List
Queue
Map
SortedMap

Implemented by
HashSet, LinkedHashSet, EnumSet
TreeSet
Vector, Stack, ArrayList, LinkedList
PriorityQueue, LinkedList
Hashtable, HashMap, LinkedHashMap, WeakHashMap,
IdentityHashMap
TreeMap

What Is a Collections Framework?


-

A collections framework is a unified architecture for representing and


manipulating collections.
All collections frameworks contain the following:

Interfaces: These are abstract data types that represent collections.


Interfaces allow collections to be manipulated independently of the details of
their representation.

Implementations: These are the concrete implementations of the


collection interfaces. In essence, they are reusable data structures.

Algorithms: These are the methods that perform useful computations,


such as searching and sorting, on objects that implement collection interfaces.
The algorithms are said to be polymorphic: that is, the same method can be used
on many different implementations of the appropriate collection interface. In
essence, algorithms are reusable functionality.
-

The core collection interfaces encapsulate: These interfaces allow


collections to be manipulated independently of the details of their
representation.
As you can see in the following figure, the core collection interfaces
form a hierarchy.

62

The core collection interfaces.

A Set is a special kind of Collection,


A SortedSet is a special kind of Set,
Note also that the hierarchy consists of two distinct trees a Map is not
a true Collection.

The following list describes the core collection interfaces:

Collection

A collection represents a group of objects known as its elements.


Some types of collections allow duplicate elements, and others do not.
Some are ordered and others are unordered.
The Java platform doesn't provide any direct implementations of this
interface but provides implementations of more specific subinterfaces,
such as Set and List.

Set

List

Queue

a collection that cannot contain duplicate elements. This interface


models the mathematical set abstraction and is used to represent sets,
such as the courses making up a student's schedule, or the processes
running on a machine.

an ordered collection (sometimes called a sequence). Lists can


contain duplicate elements.

a collection used to hold multiple elements prior to processing.


Besides basic Collection operations, a Queue provides additional
insertion, extraction, and inspection operations.
Queues typically, but do not necessarily, order elements in a FIFO (firstin, first-out) manner.
In a FIFO queue, all new elements are inserted at the tail of the queue.

Map

an object that maps keys to values. A Map cannot contain


duplicate keys; each key can map to at most one value.

63

SortedSet

a Set that maintains its elements in ascending order.


Several additional operations are provided to take advantage of the
ordering. Sorted sets are used for naturally ordered sets,

SortedMap

a Map that maintains its mappings in ascending key order.


Sorted maps are used for naturally ordered collections of key/value pairs,
such as dictionaries and telephone directories.

The Collection Interface


-

A Collection represents a group of objects known as its elements.


The Collection interface is used to pass around collections of objects
where maximum generality is desired.
Example, that you have a Collection<String> c, which may be a
List, a Set, or another kind of Collection. This idiom creates a new
ArrayList (an implementation of the List interface), initially
containing all the elements in c.

List<String> list = new ArrayList<String>(c);

The following shows the Collection interface.


public interface Collection<E> extends Iterable<E> {
// Basic operations
int size();
boolean isEmpty();
boolean contains(Object element);
boolean add(E element);
//optional
boolean remove(Object element); //optional
Iterator<E> iterator();
// Bulk operations
boolean containsAll(Collection<?> c);
boolean addAll(Collection<? extends E> c); //optional
boolean removeAll(Collection<?> c);
//optional
boolean retainAll(Collection<?> c);
//optional
void clear();
//optional
// Array operations
Object[] toArray();
<T> T[] toArray(T[] a);

The add method is defined generally enough so that it makes sense for
collections that allow duplicates as well as those that don't.

64

It guarantees that the Collection will contain the specified element


after the call completes, and returns true if the Collection changes as a
result of the call.

Similarly, the remove method is designed to remove a single instance of


the specified element from the Collection, assuming that it contains the
element to start with, and to return true if the Collection was modified
as a result.

Traversing Collections
There are two ways to traverse collections: (1) with the for-each construct and
(2) by using Iterators.
for-each Construct
The for-each construct allows you to concisely traverse a collection or array
using a for loop
for (Object o : collection)
System.out.println(o);

Iterators
An Iterator is an object that enables you to traverse through a collection and
to remove elements from the collection selectively,
public interface Iterator<E> {
boolean hasNext();
E next();
void remove(); //optional
}
- The hasNext method returns true if the iteration has more elements,
and the next method returns the next element in the iteration.
- The remove method removes the last element that was returned by next
from the underlying Collection.
- Iterator.remove is the only safe way to modify a collection during

iteration;
Use Iterator instead of the for-each construct when you need to:
Remove the current element. The for-each construct hides the iterator,
so you cannot call remove.
Therefore, the for-each construct is not usable for filtering.

Collection Interface Array Operations


-

The toArray methods are provided as a bridge between collections and


older APIs that expect arrays on input.
The array operations allow the contents of a Collection to be translated
into an array.
65

The simple form with no arguments creates a new array of Object.


For example, suppose that c is a Collection. The following snippet
dumps the contents of c into a newly allocated array of Object whose
length is identical to the number of elements in c.

Object[] a = c.toArray();

Suppose that c is known to contain only strings (perhaps because c is of type


Collection<String>). The following snippet dumps the contents of c into a
newly allocated array of String whose length is identical to the number of
elements in c.
String[] a = c.toArray(new String[0]);

The Set Interface


-

A Set is a Collection that contain duplicate elements. It models the


mathematical set abstraction.
The Set interface contains only methods inherited from Collection and
instances are equal if they contain the same elements.

The following is the Set interface.


public interface Set<E> extends Collection<E> {
// Basic operations
int size();
boolean isEmpty();
boolean contains(Object element);
boolean add(E element);
//optional
boolean remove(Object element); //optional
Iterator<E> iterator();
// Bulk operations
boolean containsAll(Collection<?> c);
boolean addAll(Collection<? extends E> c); //optional
boolean removeAll(Collection<?> c);
//optional
boolean retainAll(Collection<?> c);
//optional
void clear();
//optional
// Array Operations
Object[] toArray();
<T> T[] toArray(T[] a);

The Java platform contains three general-purpose Set implementations: -

HashSet, TreeSet, and LinkedHashSet.


HashSet, which stores its elements in a hash

guarantees concerning the order of iteration.

66

table, however it makes no

TreeSet,

orders its elements based on their values; it is substantially


slower than HashSet. LinkedHashSet, which is implemented as a hash
table with a linked list running through it,

Collection<Type> noDups = new LinkedHashSet<Type>(c);

Set Interface Basic Operations


-

The size operation returns the number of elements in the Set (its
cardinality).
The add method adds the specified element to the Set if it's not already
present and returns a boolean indicating whether the element was added.
Similarly, the remove method removes the specified element from the
Set if it's present and returns a boolean indicating whether the element
was present.
The iterator method returns an Iterator over the Set.

import java.util.*;
public class FindDups {
public static void main(String[] args) {
Set<String> s = new HashSet<String>();
for (String a : args)
if (!s.add(a))
System.out.println("Duplicate detected: " + a);
System.out.println(s.size() + " distinct words: " + s);
}
}

Set Interface Bulk Operations

Bulk operations are particularly well suited to Sets; when applied, they
perform standard set-algebraic operations.
Suppose s1 and s2 are sets. Here's what bulk operations do:

s1.containsAll(s2) returns true if s2 is a subset of s1. (s2 is a


subset of s1 if set s1 contains all of the elements in s2.)
s1.addAll(s2) transforms s1 into the union of s1 and s2. (The

union of two sets is the set containing all of the elements contained in either set.)
s1.retainAll(s2) transforms s1 into the intersection of s1 and s2.
(The intersection of two sets is the set containing only the elements common to
both sets.)
s1.removeAll(s2) transforms s1 into the (asymmetric) set
difference of s1 and s2. (For example, the set difference of s1 minus s2 is the
set containing all of the elements found in s1 but not in s2.)

67

import java.util.*;
public class FindDups2 {
public static void main(String[] args) {
Set<String> uniques = new HashSet<String>();
Set<String> dups
= new HashSet<String>();
for (String a : args)
if (!uniques.add(a))
dups.add(a);
// Destructive set-difference
uniques.removeAll(dups);
System.out.println("Unique words:
" + uniques);
System.out.println("Duplicate words: " + dups);
}

The List Interface

A List is an ordered Collection (sometimes called a sequence).


Lists may contain duplicate elements. It includes operations for the
following:
Positional access

manipulates elements based on their numerical

position in the list


Search searches for a specified object in the list and returns its
numerical position
Iteration extends Iterator semantics to take advantage of the list's
sequential nature
Range-view performs arbitrary range operations on the list.
The List interface follows.
public interface List<E> extends Collection<E> {
// Positional access
E get(int index);
E set(int index, E element);
//optional
boolean add(E element);
//optional
void add(int index, E element); //optional
E remove(int index);
//optional
boolean addAll(int index,
Collection<? extends E> c); //optional
// Search
int indexOf(Object o);
int lastIndexOf(Object o);
// Iteration
ListIterator<E> listIterator();
ListIterator<E> listIterator(int index);

68

// Range-view
List<E> subList(int from, int to);

The Java platform contains two general-purpose List implementations.


-

ArrayList, which is usually the better-performing implementation, and


LinkedList which offers better performance under certain
circumstances. Also, Vector has been retrofitted to implement List.

Collection Operations
The operations inherited from Collection all do about what you'd expect them
to do, assuming you're already familiar with them. If you're not familiar with
them from Collection, now would be a good time to read The Collection
Interface section. The remove operation always removes the first occurrence of
the specified element from the list. The add and addAll operations always
append the new element(s) to the end of the list. Thus, the following idiom
concatenates one list to another.
list1.addAll(list2);

Here's a nondestructive form of this idiom, which produces a third List


consisting of the second list appended to the first.
List<Type> list3 = new ArrayList<Type>(list1);
list3.addAll(list2);

Note that the idiom, in its nondestructive form, takes advantage of ArrayList's
standard conversion constructor.
Like the Set interface, List strengthens the requirements on the equals and
hashCode methods so that two List objects can be compared for logical
equality without regard to their implementation classes. Two List objects are
equal if they contain the same elements in the same order.

Positional Access and Search Operations


The basic positional access operations (get, set, add and remove) behave
just like their longer-named counterparts in Vector (elementAt, setElementAt,
insertElementAt, and removeElementAt) with one noteworthy exception: The
set and remove operations return the old value that is being overwritten or
removed; the Vector counterparts (setElementAt and removeElementAt)
return nothing (void). The search operations indexOf and lastIndexOf
behave exactly like the identically named operations in Vector.

69

The addAll operation inserts all the elements of the specified Collection
starting at the specified position. The elements are inserted in the order they are
returned by the specified Collection's iterator. This call is the positional access
analog of Collection's addAll operation.
Here's a little method to swap two indexed values in a List. It should look
familiar from Programming 101.
public static <E> void swap(List<E> a, int i, int j) {
E tmp = a.get(i);
a.set(i, a.get(j));
a.set(j, tmp);
}

Of course, there's one big difference. This is a polymorphic algorithm: It swaps


two elements in any List, regardless of its implementation type. Here's another
polymorphic algorithm that uses the preceding swap method.
public static void shuffle(List<?> list, Random rnd) {
for (int i = list.size(); i > 1; i--)
swap(list, i - 1, rnd.nextInt(i));
}

This algorithm, which is included in the Java platform's Collections class,


randomly permutes the specified list using the specified source of randomness.
It's a bit subtle: It runs up the list from the bottom, repeatedly swapping a
randomly selected element into the current position. Unlike most naive attempts
at shuffling, it's fair (all permutations occur with equal likelihood, assuming an
unbiased source of randomness) and fast (requiring exactly list.size()-1
swaps). The following program uses this algorithm to print the words in its
argument list in random order.
import java.util.*;
public class Shuffle {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
for (String a : args)
list.add(a);
Collections.shuffle(list, new Random());
System.out.println(list);
}
}

In fact, this program can be made even shorter and faster. The Arrays class has
a static factory method called asList, which allows an array to be viewed as a
List. This method does not copy the array. Changes in the List write through
to the array and vice versa. The resulting List is not a general-purpose List
implementation, because it doesn't implement the (optional) add and remove
operations: Arrays are not resizable. Taking advantage of Arrays.asList and
70

calling the library version of shuffle, which uses a default source of


randomness, you get the following tiny program whose behavior is identical to
the previous program.
import java.util.*;
public class Shuffle {
public static void main(String[] args) {
List<String> list = Arrays.asList(args);
Collections.shuffle(list);
System.out.println(list);
}
}

Iterators
As you'd expect, the Iterator returned by List's iterator operation returns
the elements of the list in proper sequence. List also provides a richer iterator,
called a ListIterator, which allows you to traverse the list in either direction,
modify the list during iteration, and obtain the current position of the iterator.
The ListIterator interface follows.
public interface ListIterator<E> extends Iterator<E> {
boolean hasNext();
E next();
boolean hasPrevious();
E previous();
int nextIndex();
int previousIndex();
void remove(); //optional
void set(E e); //optional
void add(E e); //optional
}

The three methods that ListIterator inherits from Iterator (hasNext, next,
and remove) do exactly the same thing in both interfaces. The hasPrevious and
the previous operations are exact analogues of hasNext and next. The former
operations refer to the element before the (implicit) cursor, whereas the latter
refer to the element after the cursor. The previous operation moves the cursor
backward, whereas next moves it forward.
Here's the standard idiom for iterating backward through a list.
for (ListIterator<Type> it =
list.listIterator(list.size());
it.hasPrevious(); ) {
Type t = it.previous();
...
}

71

Note the argument to listIterator in the preceding idiom. The List interface
has two forms of the listIterator method. The form with no arguments
returns a ListIterator positioned at the beginning of the list; the form with an
int argument returns a ListIterator positioned at the specified index. The
index refers to the element that would be returned by an initial call to next. An
initial call to previous would return the element whose index was index-1. In
a list of length n, there are n+1 valid values for index, from 0 to n, inclusive.
Intuitively speaking, the cursor is always between two elements the one that
would be returned by a call to previous and the one that would be returned by a
call to next. The n+1 valid index values correspond to the n+1 gaps between
elements, from the gap before the first element to the gap after the last one. The
following figure shows the five possible cursor positions in a list containing four
elements.

The five possible cursor positions.

Calls to next and previous can be intermixed, but you have to be a bit careful.
The first call to previous returns the same element as the last call to next.
Similarly, the first call to next after a sequence of calls to previous returns the
same element as the last call to previous.
It should come as no surprise that the nextIndex method returns the index of
the element that would be returned by a subsequent call to next, and
previousIndex returns the index of the element that would be returned by a
subsequent call to previous. These calls are typically used either to report the
position where something was found or to record the position of the
ListIterator so that another ListIterator with identical position can be
created.
It should also come as no surprise that the number returned by nextIndex is
always one greater than the number returned by previousIndex. This implies
the behavior of the two boundary cases: (1) a call to previousIndex when the
cursor is before the initial element returns -1 and (2) a call to nextIndex when
the cursor is after the final element returns list.size(). To make all this
concrete, the following is a possible implementation of List.indexOf.
public int indexOf(E e) {
for (ListIterator<E> it = listIterator();
it.hasNext(); )

72

if (e == null ? it.next() == null :


e.equals(it.next()))
return it.previousIndex();
return -1; // Element not found
}

Note that the indexOf method returns it.previousIndex() even though it is


traversing the list in the forward direction. The reason is that it.nextIndex()
would return the index of the element we are about to examine, and we want to
return the index of the element we just examined.
The Iterator interface provides the remove operation to remove the last
element returned by next from the Collection. For ListIterator, this
operation removes the last element returned by next or previous. The
ListIterator interface provides two additional operations to modify the list
set and add. The set method overwrites the last element returned by next or
previous with the specified element. The following polymorphic algorithm
uses set to replace all occurrences of one specified value with another.
public static <E> void replace(List<E> list, E val, E
newVal) {
for (ListIterator<E> it = list.listIterator();
it.hasNext(); )
if (val == null ? it.next() == null :
val.equals(it.next()))
it.set(newVal);
}

The only bit of trickiness in this example is the equality test between val and
it.next. You need to special-case a val value of null to prevent a
NullPointerException.
The add method inserts a new element into the list immediately before the
current cursor position. This method is illustrated in the following polymorphic
algorithm to replace all occurrences of a specified value with the sequence of
values contained in the specified list.
public static <E> void replace(List<E> list, E val,
List<? extends E> newVals)
{
for (ListIterator<E> it = list.listIterator();
it.hasNext(); ){
if (val == null ? it.next() == null :
val.equals(it.next())) {
it.remove();
for (E e : newVals)
it.add(e);
}
}
}

73

Range-View Operation
The range-view operation, subList(int fromIndex, int toIndex), returns
a List view of the portion of this list whose indices range from fromIndex,
inclusive, to toIndex, exclusive. This half-open range mirrors the typical for
loop.
for (int i = fromIndex; i < toIndex; i++) {
...
}

As the term view implies, the returned List is backed up by the List on which
subList was called, so changes in the former are reflected in the latter.
This method eliminates the need for explicit range operations (of the sort that
commonly exist for arrays). Any operation that expects a List can be used as a
range operation by passing a subList view instead of a whole List. For
example, the following idiom removes a range of elements from a List.
list.subList(fromIndex, toIndex).clear();

Similar idioms can be constructed to search for an element in a range.


int i = list.subList(fromIndex, toIndex).indexOf(o);
int j = list.subList(fromIndex, toIndex).lastIndexOf(o);

Note that the preceding idioms return the index of the found element in the
subList, not the index in the backing List.
Any polymorphic algorithm that operates on a List, such as the replace and
shuffle examples, works with the List returned by subList.
Here's a polymorphic algorithm whose implementation uses subList to deal a
hand from a deck. That is, it returns a new List (the "hand") containing the
specified number of elements taken from the end of the specified List (the
"deck"). The elements returned in the hand are removed from the deck.
public static <E> List<E> dealHand(List<E> deck, int n) {
int deckSize = deck.size();
List<E> handView = deck.subList(deckSize - n,
deckSize);
List<E> hand = new ArrayList<E>(handView);
handView.clear();
return hand;
}

Note that this algorithm removes the hand from the end of the deck. For many
common List implementations, such as ArrayList, the performance of

74

removing elements from the end of the list is substantially better than that of
removing elements from the beginning.
The following is a program that uses the dealHand method in combination with
Collections.shuffle to generate hands from a normal 52-card deck. The
program takes two command-line arguments: (1) the number of hands to deal
and (2) the number of cards in each hand.
import java.util.*;
class Deal {
public static void main(String[] args) {
int numHands = Integer.parseInt(args[0]);
int cardsPerHand = Integer.parseInt(args[1]);
// Make a normal 52-card deck.
String[] suit = new String[]
{"spades", "hearts", "diamonds", "clubs"};
String[] rank = new String[]
{"ace","2","3","4","5","6","7","8",
"9","10","jack","queen","king"};
List<String> deck = new ArrayList<String>();
for (int i = 0; i < suit.length; i++)
for (int j = 0; j < rank.length; j++)
deck.add(rank[j] + " of " + suit[i]);
Collections.shuffle(deck);
for (int i=0; i < numHands; i++)
System.out.println(dealHand(deck,
cardsPerHand));
}
}

Running the program produces the following output.


% java Deal 4 5
[8 of hearts, jack of spades, 3 of spades, 4 of spades,
king of diamonds]
[4 of diamonds, ace of clubs, 6 of clubs, jack of hearts,
queen of hearts]
[7 of spades, 5 of spades, 2 of diamonds, queen of
diamonds,
9 of clubs]
[8 of spades, 6 of diamonds, ace of spades, 3 of hearts,
ace of hearts]

Although the subList operation is extremely powerful, some care must be


exercised when using it. The semantics of the List returned by subList
become undefined if elements are added to or removed from the backing List in
any way other than via the returned List. Thus, it's highly recommended that
you use the List returned by subList only as a transient object to perform
75

one or a sequence of range operations on the backing List. The longer you use
the subList instance, the greater the probability that you'll compromise it by
modifying the backing List directly or through another subList object. Note
that it is legal to modify a sublist of a sublist and to continue using the original
sublist (though not concurrently).

List Algorithms
Most polymorphic algorithms in the Collections class apply specifically to
List. Having all these algorithms at your disposal makes it very easy to
manipulate lists. Here's a summary of these algorithms, which are described in
more detail in the Algorithms section.

sorts a List using a merge sort algorithm, which provides a fast,


stable sort. (A stable sort is one that does not reorder equal elements.)
shuffle randomly permutes the elements in a List.
reverse reverses the order of the elements in a List.
rotate rotates all the elements in a List by a specified distance.
swap swaps the elements at specified positions in a List.
replaceAll replaces all occurrences of one specified value with
another.
fill overwrites every element in a List with the specified value.
copy copies the source List into the destination List.
binarySearch searches for an element in an ordered List using the
binary search algorithm.
indexOfSubList returns the index of the first sublist of one List that
is equal to another.
lastIndexOfSubList returns the index of the last sublist of one List
that is equal to another.
sort

1. An array is a named set of same-type variables.


2. Each variable in the array is called an array element.
3. The first element will have an index of 0.
public class MainClass {
public static void main(String[] arg) {
int[] intArray = new int[10];
for (int i = 0; i < 10; i++) {
intArray[i] = 100;
}
for (int i = 0; i < 10; i++) {
System.out.println(intArray[i]);

76

}
}
}

Exception in Java
-

Exception are such anomalous conditions (or typically an event) which


changes the normal flow of execution of a program.
Exceptions are used for signaling erroneous (exceptional) conditions
which occur during the run time processing.
Exceptions may occur in any programming language.
Occurrence of any kind of exception in java applications may result in
an abrupt termination of the JVM or simply the JVM crashes which
leaves the user unaware of the causes of such anomalous conditions.

Exception Object
-

In java, when any kind of abnormal conditions occurs with in a


method then the exceptions are thrown in the form of Exception
Object i.e. the normal program control flow is stopped and an
exception object is created to handle that exceptional condition.
The method creates an object and hands it over to the runtime system.
Basically, all the information about the error or any unusual condition
is stored in this type of object in the form of a stack.
This object created is called an exception object the process is termed
as throwing an exception.
The mechanism of handling an exception is called catching an
exception or handling an Exception or simply Exception handling.
As we have known that after throwing an exception it is handed off to
the runtime system that finds a possible method from an ordered list of
methods to handle it.
The list of this type of methods is known as the call stack
The exceptions are not errors rather they are some abnormal conditions
that aren't necessarily errors.
Therefore, the process of detecting the exceptions and responding to
them as well is known as Exception handling.

Following are the advantages of Exception-handling in Java:


-

Exception provides the means to separate the details of what to do


when something out of the ordinary happens from the main logic of a
program.

77

One of the significance of this mechanism is that it throws an


exception whenever a calling method encounters an error providing
that the calling method takes care of that error.
With the help of this mechanism the working code and the errorhandling code can be disintegrated.
It also gives us the scope of organizing and differentiating between
different error types using a separate block of codes.
This is done with the help of try-catch blocks.
Furthermore the errors can be propagated up the method call stack i.e.
problems occurring at the lower level in the chain can be handled by
the methods higher up the call chain .

Sample Code
The basic syntax to handle an Exception looks like this:

String myException()
{
try
{
return myMethod();
}
catch ( IOException e )
{
return null;
}
}
There are three types of Exceptions:

Checked Exceptions

78

These are the exceptions which occur during the compile time of the
program.
The compiler checks at the compile time that whether the program
contains handlers for checked exceptions or not. These exceptions do
not extend RuntimeException class and must be handled to avoid a
compile-time error by the programmer.
These exceptions extend the java.lang.Exception class These
exceptional conditions should be anticipated and recovered by an
application.
Furthermore Checked exceptions are required to be caught. Remember
that all the exceptions are checked exceptions unless and until those
indicated by Error, RuntimeException or their subclasses.

Here is the list of checked exceptions.


NoSuchFieldException
InstantiationException
IllegalAccessException
ClassNotFoundException
NoSuchMethodException
CloneNotSupportedException
InterruptedException
Unchecked Exceptions
- Unchecked exceptions are the exceptions which occur during the
runtime of the program.
- Unchecked exceptions are internal to the application and extend the
java.lang.RuntimeException
that
is
inherited
from
java.lang.Exception class.
- These exceptions cannot be anticipated and recovered like
programming bugs, such as logic errors or improper use of an API.
- These type of exceptions are also called Runtime exceptions that are
usually caused by data errors, like arithmetic overflow, divide by zero
etc.
Here is the list of unchecked exceptions.
IndexOutOfBoundsException
ArrayIndexOutOfBoundsException
ClassCastException
ArithmeticException
NullPointerException
IllegalStateException
SecurityException
Error

79

The errors in java are external to the application.


These are the exceptional conditions that could not be usually
anticipated by the application and also could not be recovered from.
Error exceptions belong to Error and its subclasses are not subject to
the catch or Specify requirement.

Suppose a file is successfully opened by an application for input but


due to some system malfunction could not be able to read that file then
the java.io.IOError would be thrown.

This error will cause the program to terminate but if an application


wants then the error might be caught.

An Error indicates serious problems that a reasonable application


should not try to catch.

Most such errors are abnormal conditions.

Hence we conclude that Errors and runtime exceptions are together


called as unchecked exceptions

The hierarchy of exception classes commence from Throwable class


which is the base class for an entire family of exception classes,
declared in java.lang package as java.lang.Throwable.

A throwable contains a snapshot of the execution stack at the time it


was created and also a message string that gives more information
about the error.

This class can be instantiated and thrown by the program.

The throwable class is further divided into two subclasses :-

Exceptions are thrown if any kind of unusual condition occurs that can
be caught.
Sometimes it also happens that the exception could not be caught and
the program may get terminated.
Remember that they are a member of Exception family and can be of
type Checked or Unchecked exception.

Exceptions
Errors
-

When any kind of serious problem occurs which could not be handled
easily like OutOfMemoryError then an error is thrown.

80

Well, errors are not something which is thrown by you rather they are
thrown by the Java API or by the Java virtual machine itself i.e. only
the exceptions are thrown by your code and not the errors.
Also Remember that they are a member of Error family.

The exception classes can be explained as well seeing the hierarchy structure:

The java.lang package defines several classes and exceptions. Some of these classes are
not checked while some other classes are checked.
EXCEPTIONS
DESCRIPTION CHECKED UNCHECKED
Arithmetic
ArithmeticException
errors such as aYES
divide by zero
Arrays index is
ArrayIndexOutOfBoundsException not
withinYES
array.length
Related Class
ClassNotFoundException
YES
not found
InputOuput
IOException
YES
field not found
Illegal argument
IllegalArgumentException
when calling aYES
method
One thread has
been interrupted
InterruptedException
YES
by
another
thread
NoSuchMethodException
Nonexistent
YES
-

81

NullPointerException
NumberFormatException

method
Invalid use of
null reference
Invalid
string
for conversionto number

YES
YES

Exceptions are Objects that means an object is thrown when you throw
an exception.
Moreover only those objects could be thrown whose classes are
derived from Throwable.
Objects of your own design could also be thrown provided that they
should be the subclass of some member of the Throwable family.
Also the throwable classes which are defined by you must extend
Exception class.

It depends upon the situation that whether to use an existing exception


class from

java.lang
or
create
any
of
your
own.
Such
as
IllegalArgumentException, a subclass of RuntimeException in
java.lang can be thrown if any method with an invalid argument is
thrown .

For example, if a thrown exception object has class


IllegalArgumentException, that indicates someone passed an illegal
argument to a method.

// In Source Packet in file


except/ex1/SpeedException.java
class SpeedException extends Exception
{
}
// In Source Packet in file
except/ex1/VeryFastException.java
class VeryFastException extends SpeedException
{
}
// In Source Packet in file except/ex1/VerySlowException.java
class VerySlowException extends SpeedException
{
}

82

The various keywords for handling exceptions are below.


try
catch
finally
throw
throws
-

The three exception handler components are used to catch and handle
the exceptions.
These are try, catch and finally clause.
The mechanism to catch an exception in Java is to use try and catch
block.
Every catch block can handle only one type of exception however you
can use more than one catch clause in a single try block.
Simply a statement is surrounded by the try block that may cause the
exception to occur.
Then the try block is followed by the catch block.
And if the exception occurs then this catch block specifies a code that
should be executed.

Using try and catch:The syntax for the usage of try, catch and finally block is given below.
try{

}
catch(<exceptionclass1> <obj1>)
{

}
finally
{

}
-

For using an exception handler in an application, the first step we need


to do is to enclose the code that is likely to generate an exception
inside a try block.
If an exception occurs in the try block then it is handled by the
exception handler associated with it.

83

For doing this we need to have one or more catch blocks after the try
block, where each catch block acts as an exception handler and can
handle the type of exception indicated by its arguments.

Lets have a look at the example which shows the implementation of


the try, catch and finally block. Here we have used "fis = new
FileInputStream (new File (args[0]));" which throws an exception if
we write a name of a file which doesn't exist as shown in the output.

import java.io.*;
class Test
{
public static void main(String args[])throws IOException
{
FileInputStream fis=null;
try
{
fis = new FileInputStream (new File (args[0]));
}
catch (FileNotFoundException e)
{
System.out.println("File not found!");
}
finally
{
fis.close();
}
}
}
Using finally:
-

It is always a good practice to use finally clause after the try and catch
block because the finally block always executes even if an unexpected
exception occurs i.e. whether or not an exception thrown.
The finally block executes if and only if the try block exits.
Other than exception handling the finally clause helps you in avoiding
any cleanup code accidentally bypassed by a return etc.
The statements within the finally block gets executed by the the
runtime system without taking care of what happens within the try
block.

There are two steps to use the finally clause:


First, you need to enclose the code in a try block that has multiple exit points.

84

Secondly after the try block exits place the code that must be executed in a finally clause.
import java.io.*;
class Test
{
public static void main(String args[])
{
FileInputStream fis=null;
try
{
fis = new FileInputStream (new File (args[0]));
int ch;
while ((ch = fis.read()) != -1)
{
System.out.print ((char) ch);
}
}
catch (FileNotFoundException e)
{
System.out.println("File not found!");
}
catch (IOException e)
{
System.out.println("Unable to read file!");
}
finally{
System.out.println();
System.out.println("In finally.");
try{
if(fis!=null){
fis.close();
}
}
catch (IOException ioe)
{
System.out.println("In finally.");
}
}
}
}
-

Using throws: The other way to handle an exception is using the


throws clause.
When we call a method from the java API that throws a checked
exception, you must either throw the exception or catch it.

85

If you decide that you can't handle the exception properly, then the
exception can be declared to the method header using the throws
keyword followed by the class name of the exception.
Add the throws clause to the surrounding method to pass the error up
to the next level (or else write your own catch/try handler).
While the throw keyword (note the singular form) is used to force an
exception.

import java.io.*;
class Test3
{
public static void main(String args[]) throws
FileNotFoundException,IOException
{
FileInputStream fis=null;
fis = new FileInputStream (new File (args[0]));
int ch;
while ((ch = fis.read()) != -1){
System.out.print ((char) ch);
}
fis.close();
}
}
How to Throw Exceptions
-

Before catching an exception it is must to be thrown first.


We use throw statement to throw an exception or simply use the throw
keyword with an object reference to throw an exception.
A single argument is required by the throw statement i.e. a throwable
object.
As mentioned earlier Throwable objects are instances of any subclass
of the

Throwable class.
throw new VeryFastException();
Note: The reference should be of type Throwable or one of its subclasses.
class MyException extends Exception
{
public MyException(String msg)
{
super(msg);
}
}
86

public class Test {


static int divide(int first,int second) throws MyException{
if(second==0)
throw new MyException("can't be divided by zero");
return first/second;
}
public static void main(String[] args)
{
try
{
System.out.println(divide(4,0));
}
catch (MyException exc)
{
exc.printStackTrace();
}
}
}
Handling Multiple Catch Clauses
-

We can have multiple catch blocks for a particular try block to handle
many different kind of exceptions that may be generated while running
the program

The syntax for using this clause is given below:try{

}
catch(<exceptionclass_1> <obj1>){
//statements to handle the exception
}
catch(<exceptionclass_2> <obj2>){
//statements to handle the exception
}
catch(<exceptionclass_N> <objN>){
//statements to handle the exception
}

87

When an exception is thrown, normal execution is suspended. The


runtime system proceeds to find a matching catch block that can
handle the exception.
If no handler is found, then the exception is dealt with by the default
exception handler at the top level.

public class Multi_Catch


{
public static void main (String args[])
{
int array[]={20,10,30};
int num1=15,num2=0;
int res=0;
try
{
res = num1/num2;
System.out.println("The result is" +res);
for(int ct =2;ct >=0; ct--)
{
System.out.println("The value of array are" +array[ct]);
}
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Error. Array is out of Bounds");
}
catch (ArithmeticException e)
{
System.out.println ("Can't be divided by Zero");
}
}
}

Handling the Unreachable Code Problem


-

The multiple catch blocks can generate unreachable code error i.e. if
the first catch block contains the Exception class object then the
subsequent catch blocks are never executed.
This is known as Unreachable code problem.
To avoid this, the last catch block in multiple catch blocks must
contain the generic class object that is called the Exception class.
88

This exception class being the super class of all the exception classes
and is capable of catching any types of exception.

Nested Try-Catch Blocks


-

In Java we can have nested try and catch blocks. It means that, a try
statement can be inside the block of another try.
If an inner try statement does not have a matching catch statement for
a particular exception, the control is transferred to the next try
statements catch handlers that are expected for a matching catch
statement.
This continues until one of the catch statements succeeds, or until all
of the nested try statements are done in.
If no one catch statements match, then the Java run-time system will
handle the exception.

The syntax of nested try-catch blocks is given below:


try {
try {
//
...
}
catch (Exception1 e)
{
//statements
to
handle
the
exception
}
}
catch (Exception 2 e2)
{
//statements to handle the
exception
}
Lets have an example that uses the nested try-catch blocks
import java.io.*;
public class NestedTry{
public static void main (String args[])throws IOException
int num=2,res=0;
try{
FileInputStream fis=null;
fis = new FileInputStream (new File (args[0]));
try{
res=num/0;
System.out.println("The result is"+res);
}
catch(ArithmeticException e){
System.out.println("divided by Zero");
}

89

}
}

}
catch (FileNotFoundException e){
System.out.println("File not found!");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Array index is Out of bound! Argument required");
}
catch(Exception e){
System.out.println("Error.."+e);
}

Catching Normal Exceptions


The exceptions that are generated by methods are referred to as normal exceptions. We
have already learned that to catch an exception we use try and catch block.
try {
myTestException();
}
catch(ExceptionType1 e)
{
System.out.println(e.getMessage());
}
catch(Exceptiontype2 e)
{
System.out.println(e.getMessage());
}
Catching Runtime Exceptions
The exceptions which are not easily traced are known as Runtime Exceptions. For
instance,
try {
int x = 50;
for (int i = 15; i >= 0; i--)
System.out.println(x / i);
}
catch(ArithmeticException e) {
System.out.println(e.getMessage());
}
-

The above code displays a for loop trying to divide a number by zero
in its last iteration which would result in runtime exception.
We have used try block to handle this exception and a corresponding
handler by means of a catch clause.

90

And if we won't handle the exception the program will end up with the
termination.
The disadvantage in handling the runtime exception is that we need to
put the doubtful code inside a try block.
This approach sometimes causes a mess so its always better to avoid
the problems which land you up with the troubles.

Making Custom (User Define Exceptions)


-

If you can't find the appropriate exception in the Java API, you can
code a class that defines an exception that is more appropriate and that
mechanism of handling exception is called Custom or User Defined
Exception.
In Java API all exception classes have two type of constructor.
First is called default constructor that doesn't accept any arguments.
Another constructor accepts a string argument that provides the
additional information about the exception.

public class ExceptionClassName extends Exception


{
public ExceptionClassName(){ }
public ExceptionClassName(StringMessage)
{
super(message);
}
}
Lets see an example that has the implementation of User Define Exception:
import java.io.*;
import java.util.*;
class MyException extends Exception
{
private String nm="";
public String getMessage(String s)
{
nm=s;
return ("you are not permitted to enter inside "+nm);
}
}
public class ExcepDemo
{
public static void main(String args[])throws
91

MyException,IOException
{
String temp="";
try
{
String str="amit";
System.out.println("Enter the your name");
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
temp=br.readLine();
if(!temp.equals(str))
throw new MyException();
else
System.out.println("Welcome to India");
}
catch(MyException e)
{
System.err.println(e.getMessage(temp));
}
catch(Exception e)
{
System.err.println(e);
}
}
}

What are Chained Exceptions?


-

Whenever in a program the first exception causes an another


exception, that is termed as Chained Exception.
Java provides new functionality for chaining exceptions.
Exception chaining (also known as "nesting exception") is a technique
for handling the exception, which occur one after another i.e. most of
the time is given by an application to response to an exception by
throwing another exception.
Typically the second exception is caused by the first exception.
Therefore chained exceptions help the programmer to know when one
exception causes another.

The constructors that support chained exceptions in Throwable class are:


Throwable initCause(Throwable)
Throwable(Throwable)
Throwable(String, Throwable)

92

Throwable getCause()
The methods of the Throwable class are:
METHOD
DESCRIPTION
Returns the exception followed by a message string (if
toString()
one exit) .
getMessage()
printStackTrace()
GetCause()
InitCause()

Returns the message string of the Throwable object.


Returns the full name of the exception class and some
additional information apart from the information of
first two method.
Returns the exception that caused the occurrence of
current exception.
Returns the current exception due to the Throwable
constructors and the Throwable argument to initCause.

The syntax for using a chained exception is as follows in which a new TestException
exception is created with the attached cause when an IOException is caught. Thus the
chain exception is thrown to next level of exception handler.
try
{ }
catch (IOException e)
{
throw new TestException("Other IOException", e);
}
Lets see an example having the implementation of chained exceptions:

93

import java.io.*;
import java.util.*;
class MyException extends Exception{
MyException(String msg){
super(msg);
}
}
public class ChainExcep{
public static void main(String args[])throws MyException,
IOException{
try
{
int rs=10/0;
}
catch(Exception e)
{
System.err.println(e.getMessage());
System.err.println(e.getCause());
throw new MyException("Chained ArithmeticException");
}
}
}
How to Print a Stack Trace Message
-

Java provides a method getMessage() method that is used with an


object of the Exception class to print errors to debug the process.

Try {
// ......
}
catch (IOException e) {
// ...........
System.out.println("Got an IOException: " +
e.getMessage());
}

Instead of this method you can get more information about the error
process if you print a stack trace from the exception using the
printStackTrace() method
That is the method of the Throwable class and prints the stack trace to
the console and provides the line numbers of statements that called the
methods in the current stack.

Lets see an example that prints an exception's message.

94

Public class PrintStack{


public static void main (String args[]){
String str = "Exception" ;
int len=0;
try{
StringBuffer sbuf = new StringBuffer(str);
len = str.length() ;
for(int ct=len;ct>=0;ct--){
System.out.print(sbuf.charAt(ct));
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

MultiThreading
Multitasking
-

Multitasking allow to execute more than one tasks at the same time, a
task being a program.
In multitasking only one CPU is involved
Multitasking allow processes (i.e. programs) to run concurrently on the
program.
For Example running the spreadsheet program and you are working
with word processor also.
Multitasking is running heavyweight processes by a single OS.

Multithreading :
-

Multithreading is a technique that allows a program or a process to


execute many tasks concurrently (at the same time and parallel).
It allows a process to run its tasks in parallel mode on a single
processor system

Advantages of multithreading over multitasking :


-

Reduces the computation time.


Improves performance of an application.
Threads share the same address space so it saves the memory.
Context switching between threads is usually less expensive than
between processes.
Cost of communication between threads is relatively low.

95

Process
-

A process is an instance of a computer program that is executed


sequentially.
It is a collection of instructions which are executed simultaneously at
the rum time.
Thus several processes may be associated with the same program.
For example, to check the spelling is a single process in the Word
Processor program and you can also use other processes like printing,
formatting, drawing, etc. associated with this program.

Thread
-

A thread is a lightweight process which exist within a program and


executed to perform a special task.
Several threads of execution may be associated with a single process.
Thus a process that has only one thread is referred to as a singlethreaded process,
while a process with multiple threads is referred to as a multi-threaded
process.
In Java Programming language, thread is a sequential path of code
execution within a program.
Each thread has its own local variables, program counter and lifetime.
In single threaded runtime environment, operations are executes
sequentially i.e. next operation can execute only when the previous
one is complete.
It exists in a common memory space and can share both data and code
of a program.
Using threads we can increase the speed of any application.
Diagram shown below in which a thread is executed along with its
several operations with in a single process.

Main Thread
-

When any standalone application is running, it firstly execute the


main() method runs in a one thread, called the main thread.

96

If no other threads are created by the main thread, then program


terminates when the main() method complete its execution.
The main thread creates some other threads called child threads.
The main() method execution can finish, but the program will keep
running until the all threads have complete its execution

Different states of a thread are :

New state
-

After the creations of Thread instance the thread is in this state but
before the start() method invocation. At this point, the thread is
considered not alive.

Runnable (Ready-to-run) state


- A thread start its life from Runnable state.
- A thread first enters runnable state after the invoking of start() method
but a thread can return to this state after either running, waiting,
sleeping or coming back from blocked state also.
- On this state a thread is waiting for a turn on the processor.
Running state
- A thread is in running state that means the thread is currently
executing.
- There are several ways to enter in Runnable state but there is only one
way to enter in Running state:
- the scheduler select a thread from runnable pool.
Dead state
-

A thread can be considered dead when its run() method completes. If


any thread comes on this state that means it cannot ever run again.

97

Blocked
-

A thread can enter in this state because of waiting the resources that
are hold by another thread.

Different states implementing Multiple-Threads are:

A running thread can enter to any non-runnable state, depending on the


circumstances.
A thread cannot enters directly to the running state from non-runnable
state, firstly it goes to runnable state.
Now lets understand the some non-runnable states which may be occur
handling the multithreads.

Sleeping
-

On this state, the thread is still alive but it is not runnable, it might be
return to runnable state later, if a particular event occurs.
On this state a thread sleeps for a specified amount of time.
the method sleep( ) can be used to stop the running state of a thread.

static void sleep(long millisecond) throws InterruptedException


Waiting for Notification
- A thread waits for notification from another thread. The thread sends
back to runnable state after sending notification from another thread.
final void wait(long timeout) throws InterruptedException
final void wait(long timeout, int nanos) throws InterruptedException
final void wait() throws InterruptedException
Blocked on I/O
- The thread waits for completion of blocking operation.
- A thread can enter on this state because of waiting I/O resource.
- In that case the thread sends back to runnable state after availability of
resources.
Blocked for joint completion
- The thread can come on this state because of waiting the completion of
another thread.
98

Blocked for lock acquisition


- The thread can come on this state because of waiting to acquire the
lock of an object.
Methods that can be applied on a Thread:
Some Important Methods defined in java.lang.Thread are shown in the table:
Return
Method
Description
Type
currentThread(
Returns an object reference to the thread in which it
Thread
)
is invoked.
getName( )
String
Retrieve the name of the thread object or instance.
start( )
void
Start the thread by calling its run method.
This method is the entry point to execute thread, like
run( )
void
the main method for applications.
Suspends a thread for a specified amount of time (in
sleep( )
void
milliseconds).
This method is used to determine the thread is
isAlive( )
boolean
running or not.
This method returns the number of active threads in a
activeCount( ) int
particular thread group and all its subgroups.
The method interrupt the threads on which it is
interrupt( )
void
invoked.
By invoking this method the current thread pause its
yield( )
void
execution temporarily and allow other threads to
execute.
This method and join(long millisec) Throws
InterruptedException. These two methods are
join( )
void
invoked on a thread. These are not returned until
either the thread has completed or it is timed out
respectively.
-

Thread can be implemented through any one of two ways:

1. Extending the java.lang.Thread Class

2. Implementing the java.lang.Runnable Interface

99

Extending the java.lang.Thread Class


For creating a thread by this procedure
- Extend the java.lang.Thread Class.
- Override the run( ) method in the subclass from the Thread class to
define the code executed by the thread.
- Create an instance of this subclass. This subclass may call a Thread
class constructor by subclass constructor.
- Invoke the start( ) method on the instance of the class to make the
thread eligible for running.
-

The following program demonstrates a single thread creation


extending the "Thread" Class:

class MyThread extends Thread{


String s=null;
MyThread(String s1){
s=s1;
start();
}
public void run(){
System.out.println(s);
}
}
public class RunThread{
public static void main(String args[]){
MyThread m1=new MyThread("Thread started....");
}

II. Implementing the java.lang.Runnable Interface


-

A Class implements the Runnable Interface, override the run() method


to define the code executed by thread.
An object of this class is Runnable Object.
Create an object of Thread Class by passing a Runnable object as
argument.

100

Invoke the start( ) method on the instance of the Thread class.

class MyThread1 implements Runnable{


Thread t;
String s=null;
MyThread1(String s1){
s=s1;
t=new Thread(this);
t.start();
}
public void run(){
System.out.println(s);
}
}
public class RunableThread{
public static void main(String args[]){
MyThread1 m1=new MyThread1("Thread started....");
}
}

There are two reasons for implementing a Runnable interface


preferable to extending the Thread Class:
If you extend the Thread Class, that means that subclass cannot extend
any other Class,
but if you implement Runnable interface then you can do this.
The class implementing the Runnable interface can avoid the full
overhead of Thread class which can be excessive.
join() & isAlive() methods:

The following program demonstrates the join() & isAlive() methods:


class DemoAlive extends Thread {
int value;
public DemoAlive(String str){
super(str);
value=0;
start();
}
public void run(){
try{
while (value < 5){
System.out.println(getName() + ": " + (value++));
Thread.sleep(250);
}
} catch (Exception e) {}
System.out.println("Exit from thread: " + getName());
}
}
public class DemoJoin{

101

public static void main(String[] args){


DemoAlive da = new DemoAlive("Thread a");
DemoAlive db = new DemoAlive("Thread b");
try{
System.out.println("Wait for the child threads to finish.");
da.join();
if (!da.isAlive())
System.out.println("Thread A not alive.");
db.join();

if (!db.isAlive())
System.out.println("Thread B not alive.");
} catch (Exception e) { }
System.out.println("Exit from Main Thread.");

Several

constructors

are

available

for

creating

new

Thread

instances.

Thread()
Thread(String)
Thread(Runnable)
Thread(Runnable,String)
Thread(ThreadGroup,String)
Thread(ThreadGroup,Runnable)
Thread(ThreadGroup,Runnable,String)
Thread(ThreadGroup, Runnable, String, long)
ThreadGroup
-

All threads belongs to an instance of the ThreadGroup Class.


ThreadGroup is used to represent a group of threads.
There is only one root ThreadGroup that contains all other thread and
groups and each subgroups can contain other groups and threads.
All thread have only one thread group.
And all thread groups (except the root thread group) belongs to exactly
one parent thread group.
Threads can access only belonging thread group.
When a new ThreadGroup is created, it is added as a member of
existing ThreadGroup.
If a thread x in group1, and executes the code:

ThreadGroup group2=new ThreadGroup(group2);


-

Then the newly formed group2 comes under group1. If you want a
parent group other than default then you have to specify the parent
group at the time of creation.

102

ThreadGroup group2=new ThreadGroup(group2,group3);


Then newly formed group3 comes under the group2.
Some important methods are:
getName() This method is used to retrieve the name of particular group.
ThreadGroup g=new ThreadGroup(RoseIndia);
String gname=g.getName();
getParent() This method is used to retrieve the name of parent threadgroup of sub
group.
ThreadGroup group=group3.getParent();
activeGroupCount() This method returns the number of active thread group in a
particular thread group and all its subgroups.
int size=group.activeGroupCount();
getThreadGroup() This method is used to know the thread is belong to which thread
group.
ThreadGroup group=threadx.getThreadGroup();

103

class MyThread extends Thread{


MyThread(String s){
super(s);
start();
}
public void run(){
for(int i=0;i<5;i++){
System.out.println("Thread Name :"
+Thread.currentThread().getName());
try{
Thread.sleep(1000);
}catch(Exception e){}
}
}
}

public class MultiThread1{


public static void main(String args[]){
System.out.println("Thread Name :"
+Thread.currentThread().getName());
MyThread m1=new MyThread("My Thread 1");
MyThread m2=new MyThread("My Thread 2");
}

Thread Priorities
- In Java, thread scheduler can use the thread priorities in the form of
integer value to each of its thread to determine the execution schedule
of threads .
- Thread gets the ready-to-run state according to their priorities.
- The thread scheduler provides the CPU time to thread of highest
priority during ready-to-run state.
- Priorities are integer values from 1 (lowest priority given by the
constant Thread.MIN_PRIORITY) to 10 (highest priority given by the
constant Thread.MAX_PRIORITY).
- The default priority is 5(Thread.NORM_PRIORITY).
Constant

Description

The maximum priority of


any thread (an int value of
10)
The minimum priority of
Thread.MAX_PRIORITY
any thread (an int value of 1)
The normal priority of any
Thread.NORM_PRIORITY
thread (an int value of 5)
Thread.MIN_PRIORITY

The methods that are used to set the priority of thread shown as:
Method

Description

104

This is method is used to set the


priority of thread.
This method is used to get the
getPriority()
priority of thread.
setPriority()

When a Java thread is created, it inherits its priority from the thread
that created it.
when multiple threads are ready to be executed, the runtime system
chooses the runnable thread with the highest priority for execution.
In Java runtime system, preemptive scheduling algorithm is applied. If
at the execution time a thread with a higher priority and all other
threads are runnable then the runtime system chooses the new higher
priority thread for execution.
On the other hand, if two threads of the same priority are waiting to be
executed by the CPU then the round-robin algorithm is applied in
which the scheduler chooses one of them to run according to their
round of time-slice.

Thread Scheduler
-

In the implementation of threading scheduler usually applies one of the


two following strategies:
Preemptive scheduling
- If the new thread has a higher priority then current running thread
leaves the runnable state and higher priority thread enter to the
runnable state.
Time-Sliced (Round-Robin) Scheduling
- A running thread is allowed to be execute for the fixed time, after
completion the time, current thread indicates to the another thread to
enter it in the runnable state.
- can also set a thread's priority at any time after its creation using the
setPriority method.
- Lets see, how to set and get the priority of a thread.
class MyThread1 extends Thread{
MyThread1(String s){
super(s);
start();
}
public void run(){
for(int i=0;i<3;i++){
Thread cur=Thread.currentThread();
cur.setPriority(Thread.MIN_PRIORITY);
int p=cur.getPriority();
System.out.println("Thread Name :"+Thread.currentThread().getName());
System.out.println("Thread Priority :"+cur);
}

105

}
}

class MyThread2 extends Thread{


MyThread2(String s){
super(s);
start();
}

public void run(){


for(int i=0;i<3;i++){
Thread cur=Thread.currentThread();
cur.setPriority(Thread.MAX_PRIORITY);
int p=cur.getPriority();
System.out.println("Thread Name :"+Thread.currentThread().getName());
System.out.println("Thread Priority :"+cur);
}
}
}
public class ThreadPriority{
public static void main(String args[]){
MyThread1 m1=new MyThread1("My Thread 1");
MyThread2 m2=new MyThread2("My Thread 2");
}
}

DeadLock
-

A situation where a thread is waiting for an object lock that holds by


second thread, and this second thread is waiting for an object lock that
holds by first thread, this situation is known as Deadlock.
Lets see a situation in the diagram shown below where the deadlock condition is occurred

In this diagram two threads having the Printing & I/O operations
respectively at a time.
But Thread1 need to printer that is hold up by the Thread2, likewise
Thread2 need the keyboard that is hold up by the Thread1.

106

In this situation the CPU becomes ideal and the deadlock condition
occurs because no one thread is executed until the hold up resources
are free.
The following program demonstrates the deadlock situation:
public class DeadDemo{
public static void main(String args[]){
String s1="Dead";
String s2="Lock";
MyThread1 m=new MyThread1(s1,s2);
MyThread2 m1=new MyThread2(s1,s2);
}
}
class MyThread1 extends Thread{
String s1;
String s2;
MyThread1(String s1, String s2){
this.s1=s1;
this.s2=s2;
start();
}
public void run(){
while(true){
synchronized(s1){
synchronized(s2){
System.out.println(s1+s2);
}
}
}
}
}
class MyThread2 extends Thread{
String s1;
String s2;
MyThread2(String s1,String s2){
this.s1=s1;
this.s2=s2;
start();
}
public void run(){
while(true){
synchronized(s2){

}
}

synchronized(s1){
System.out.println(s2+s1);
}

107

Synchronized Threads
-

In Java, the threads are executed independently to each other.


These types of threads are called as asynchronous threads.
But there are two problems may be occur with asynchronous threads.

Two or more threads share the same resource (variable or method)


while only one of them can access the resource at one time.
If the producer and the consumer are sharing the same kind of data in a
program then either producer may produce the data faster or consumer
may retrieve an order of data and process it without its existing.
Suppose, we have created two methods as increment( ) and decrement(
).
which increases or decreases value of the variable "count" by 1
respectively shown as:

public void increment( )


{
count++;
}
public void decrement( ) {
count--;
}
public int value()
{
return count;
}
-

When the two threads are executed to access these methods (one for
increment( ),another for decrement( )) then both will share the variable
"count". in that case, we can't be sure that what value will be returned
of variable "count".
We can see this problem in the diagram shown below:

108

To avoid this problem, Java uses monitor also known as semaphore


to prevent data from being corrupted by multiple threads by a keyword
synchronized to synchronize them and intercommunicate to each
other.
General form of the synchronized statement is as:
synchronized(object)
{
// statements to be synchronized
}

Lock:
-

Lock term refers to the access granted to a particular thread that can
access the shared resources.
At any given time, only one thread can hold the lock and thereby have
access to the shared resource.
Every object in Java has build-in lock that only comes in action when
the object has synchronized method code.
By associating a shared resource with a Java object and its lock, the
object can act as a guard, ensuring synchronized access to the
resource.
Only one thread at a time can access the shared resource guarded by
the object lock.
Since there is one lock per object, if one thread has acquired the lock,
no other thread can acquire the lock until the lock is not released by
first thread.
Acquire the lock means the thread currently in synchronized method
and released the lock means exits the synchronized method.

Remember the following points related to lock and synchronization:


-

Only methods (or blocks) can be synchronized, Classes and variable


cannot be synchronized.
Each object has just one lock.All methods in a class need not to be
synchronized.
A class can have both synchronized and non-synchronized methods.
If two threads wants to execute a synchronized method in a class, and
both threads are using the same instance of the class to invoke the
method then only one thread can execute the method at a time.
If a class has both synchronized and non-synchronized methods,
multiple threads can still access the class's non-synchronized methods.

109

If you have methods that don't access the data you're trying to protect,
then you don't need to synchronize them.
Synchronization can cause a hit in some cases (or even deadlock if
used incorrectly), so you should be careful not to overuse it.

Note : If a thread goes to sleep, it holds any locks it has,it doesn't release them.
A thread can acquire more than one lock.
Constructors cannot be synchronized
There are two ways to synchronized the execution of code:
Synchronized Methods
Synchronized Blocks (Statements)
Synchronized Methods:
wait.
-

Synchronized methods are useful in those situations where methods


are executed concurrently, so that these can be intercommunicate
manipulate the state of an object in ways that can corrupt the state if .
class Share extends Thread{
static String msg[]={"This", "is", "a", "synchronized", "variable"};
Share(String threadname){
super(threadname);
}
public void run(){
display(getName());
}
public synchronized void display(String threadN){
for(int i=0;i<=4;i++)
System.out.println(threadN+msg[i]);
try{
this.sleep(1000);
}catch(Exception e){}
}
}
public class SynThread1 {
public static void main(String[] args)
{
Share t1=new Share("Thread One: ");
t1.start();
Share t2=new Share("Thread Two: ");
t2.start();
}
}

Synchronized Blocks (Statements)


- Another way of handling synchronization is Synchronized Blocks
(Statements).

110

Synchronized statements must specify the object that provides the


native lock. The synchronized block allows execution of arbitrary code
to be synchronized on the lock of an arbitrary object.
synchronized (object reference expression)
{
// statements to be synchronized
}
The following program demonstrates the synchronized block that shows the same output
as the output of the previous example:
class Share extends Thread{
static String msg[]={"This", "is", "a", "synchronized", "variable"};
Share(String threadname){
super(threadname);
}
public void run(){
display(getName());
}
public
void display(String threadN){
synchronized(this){
for(int i=0;i<=4;i++)
System.out.println(threadN+msg[i]);
try{
this.sleep(1000);
}catch(Exception e){}
}
}
public class SynStatement {
public static void main(String[] args)
{
Share t1=new Share("Thread One: ");
t1.start();
Share t2=new Share("Thread Two: ");
t2.start();
}
}

Inter-Thread Communication
-

A process where, a thread is paused running in its critical region and


another thread is allowed to enter (or lock) in the same critical section
to be executed. This technique is known as Interthread communication
which is implemented by some methods. These methods are defined in
"java.lang" package and can only be called within synchronized code
shown as:

111

Method

Description
It indicates the calling thread to give up the monitor and
Wait( ) go to sleep until some other thread enters the same monitor
and calls method notify() or notifyAll().
It wakes up the first thread that called wait() on the same
notify( )
object.
notifyAll( Wakes up (Unloack) all the threads that called wait( ) on
)
the same object. The highest priority thread will run first.
All these methods must be called within a try-catch block.
Lets see an example implementing these methods :
class Shared {
int num=0;
boolean value = false;
synchronized int get() {
if (value==false)
try {
wait();
}
catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("consume: " + num);
value=false;
notify();
return num;
}
synchronized void put(int num) {
if (value==true)
try {
wait();
}
catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
this.num=num;
System.out.println("Produce: " + num);
value=false;
notify();
}
}
class Producer extends Thread {
Shared s;
Producer(Shared s) {
this.s=s;
this.start();

112

}
public void run() {
int i=0;
s.put(++i);
}
}
class Consumer extends Thread{
Shared s;
Consumer(Shared s) {
this.s=s;
this.start();
}

public void run() {


s.get();
}

public class InterThread{


public static void main(String[] args)
{
Shared s=new Shared();
new Producer(s);
new Consumer(s);
}
}

Daemon Threads
-

Daemon threads are like a service providers for other threads or


objects running in the same process as the daemon thread.
Daemon threads are used for background supporting tasks and are only
needed while normal threads are executing.
If normal threads are not running and remaining threads are daemon
threads then the interpreter exits.
setDaemon(true/false) This method is used to specify that a thread is
daemon thread.
public boolean isDaemon() This method is used to determine the
thread is daemon thread or not.

The following program demonstrates the Daemon Thread:


public class DaemonThread extends Thread {
public void run() {
System.out.println("Entering run method");
try {
System.out.println("In run Method: currentThread() is"
+ Thread.currentThread());

113

while (true) {
try {
Thread.sleep(500);
} catch (InterruptedException x) {
}
System.out.println("In run method: woke up again");
}
} finally {
System.out.println("Leaving run Method");
}
}
public static void main(String[] args) {
System.out.println("Entering main Method");
DaemonThread t = new DaemonThread();
t.setDaemon(true);
t.start();
try {
Thread.sleep(3000);
} catch (InterruptedException x) {
}
System.out.println("Leaving main method");
}
}

Files (IOStreams)
Introduction
-

The Java Input/Output (I/O) is a part of java.io package. The java.io


package contains a relatively large number of classes that support
input and output operations.
The classes in the package are primarily abstract classes and streamoriented that define methods and subclasses which allow bytes to be
read from and written to files or other input and output sources.
The InputStream and OutputStream are central classes in the package
which are used for reading from and writing to byte streams,
respectively.

The java.io package can be categories along with its stream classes in a hierarchy
structure shown below:

114

InputStream:
-

The InputStream class is used for reading the data such as a byte and
array of bytes from an input source.
An input source can be a file, a string, or memory that may contain the
data. It is an abstract class that defines the programming interface for
all input streams that are inherited from it. An input stream is
automatically opened when you create it.
close a stream with the close( ) method,
The subclasses inherited from the InputStream class can be seen in a
hierarchy manner shown below:

115

InputStream is inherited from the Object class.


OutputStream:
- The OutputStream class is a sibling to InputStream that is used for
writing byte and array of bytes to an output source.
- Similar to input sources, an output source can be anything such as a
file, a string, or memory containing the data.
- Like an input stream, an output stream is automatically opened when
you create it.
- Explicitly close an output stream with the close( ) method, or let it be
closed implicitly when the object is garbage collected.
The classes inherited from the OutputStream class can be seen in a hierarchy structure
shown below:

OutputStream is also inherited from the Object class.


How Files and Streams Work:
-

Java uses streams to handle I/O operations through which the data is
flowed from one location to another.
For example, an InputStream can flow the data from a disk file to the
internal memory and an OutputStream can flow the data from the
internal memory to a disk file.

116

The disk-file may be a text file or a binary file.


When we work with a text file, we use a character stream where one
character is treated as per byte on disk.
When we work with a binary file, we use a binary stream.

The working process of the I/O streams can be shown in the given diagram.

Classes and Interfaces of the I/O Streams


Classes:
The following listing of classes are provided by the java.io package shown in the table:
Class
Description
BufferedInputStream
It used for creating an internal buffer array. It
supports the mark and reset methods.
BufferedOutputStream

This class used for writes byte to output


stream. It implements a buffered output
stream.

BufferedReader
This class provides read text from character
input stream and buffering characters. It also
reads characters, arrays and lines.
BufferedWriter
This class provides write text from character
output stream and buffering characters. It also
writes characters, arrays and lines.
ByteArrayInputStream
ByteArrayOutputStream

It contains the internal buffer and read data


from the stream.
This class used for data is written into byte
array. This is implement in output stream

117

CharArrayReader
CharArrayWriter
DataInputStream
DataOutputStream
File
FileDescriptor
FileInputStream
FileOutputStream
FilePermission
FileReader
FileWriter
FilterInputStream

FilterOutputStream

FilterReader
FilterWriter
InputStream
InputStreamReader
LineNumberReader
ObjectInputStream
ObjectInputStream.GetField
ObjectOutputStream

class.
It used for char input stream and implements
a character buffer.
This class also implements a character buffer
and it uses an writer.
This class reads the primitive data types from
the input stream in a machine format.
This class writes the primitive data types
from the output stream in machine format.
This class shows a file and directory
pathnames.
This class uses for create a FileInputStream
and FileOutputStream.
It contains the input byte from a file and
implements an input stream.
It uses for writing data to a file and also
implements an output stream.
It provides the permission to access a file or
directory.
This class used for reading characters file.
This class used for writing characters files.
This class overrides all methods of
InputStream and contains some other input
stream.
This class overrides all methods of
OutputStream and contains some other output
stream.
It reads the data from the filtered character
stream.
It writes data from the filtered character
stream.
This class represents an input stream of bytes.
It reads bytes and decodes them into
characters.
This class has a line numbers
This class used for recover the object to
serialize previously.
This class access to president fields read form
input stream.
This class used for write the primitive data
types and also write the object to read by the

118

ObjectOutputStream.GetField
ObjectStreamClass
ObjectStreamField
OutputStream
OutputStreamWriter
PipedInputStream

PipedOutputStream

PipedReader
PipedWriter
PrintStream
PrintWriter
PushbackInputStream

PushbackReader
RandomAccessFile
Reader
SequenceInputStream
SerializablePermission
StreamTokenizer

StringReader
StringWriter
Writer

ObjectInputStream.
This class access to president fields write in
to ObjectOutput.
Serialization's descriptor for classes.
This class describes the serializable field.
This class represents an output stream of
bytes.
It writes bytes and decodes them into
characters.
In this class the data bytes are written into
piped output stream. This class also
connected into a piped output stream.
This class also communicates the piped input
stream into piped output stream. It creates
communication between both.
It is a piped character-input stream.
It is a piped character-output stream.
This class adds the functionality of another
output stream.
This class adds the functionality of another
input stream.
It also include the another function of input
stream. Such as: "push back" or "unread" one
byte.
This is a character stream reader and reads
the data push back into the stream.
It supports both reading and writing to a
random access file.
It used for reading character stream.
It represents the logical concatenation of
other input stream.
This is a serializable permission class.
It takes an input stream and parse it into
"tokens" . The token to be allowed at the read
time.
This is a character string class. It has
character read source.
This is also a character string class. It uses to
shows the output in the buffer.
It uses for writing to character stream.

119

Interfaces:
The following summary of Interfaces provided by the java.io package shown in the table:
Interface
Description
DataInput
This interface can be used for reading byte stream
and reconstructing the java primitive data types.
DataOutput

Externalizable

This interface can be used for writing the byte


stream and converting data from the java primitive
data types.
This is written in Serializable Stream. It save and
store it's contents.

FileFilter

It can be used for Filtering the Pathnames.

FilenameFilter

This interface used for Filter the Filenames.

ObjectInput

This interface used for reading of objects and it


extends the DataInput interface.

ObjectInputValidation

This is a Callback interface. It allows the


validation of objects within a graph.

ObjectOutput

This interface used for writing of objects and it


extends the DataOutput interface.

ObjectStreamConstants
Serializable

This interface used for Constants writing into


Serialization Objects Stream.
This
interface
implementing
java.io.Serializable interface.

in

the

Exceptions Classes:
The following summary of the exception classes provided by the java.io package shown
in the table:
Exceptions
Description
CharConversionException
It provides detail message in the catch block
to
associated
with
the
CharConversionException
EOFException
This exception indicates the end of file.
When the file input stream to be end then
EOFException to be occuted.

120

FileNotFoundException

When the open file's pathname does not find


then this exception to be occured.

InterruptedIOException

When the I/O operations to interrupted from


any causes then it becomes.

InvalidClassException

Any problems to be created with class, when


the Serializing runtime to be detected.

InvalidObjectException

When the de-serialized objects failed then it


occurs.
When the I/O operations to be failed then it
occurs.

IOException
NotActiveException

The
Serialization
or
deserialization
operations are not active then it occurs.

NotSerializableException

This exception when the instance is required


to a Serializable interface.

ObjectStreamException

This is a supper class of all exception class.


It used for specific to Object Stream Classes.

OptionalDataException
When the reading data operations to failed
then it these exception occurs. It is
belonging to the serialized object
StreamCorruptedException

It thrown when the control information that


was read form an object stream vioaltes
internal consistency checks.

SyncFaieldException

The sync operation is failed


SyncFaieldException to be occure.

UnsupportedEncodingException

The Character Encoding is not supported.

UTFDataFormatException

A molformed UTF-8 has been read in a data


input stream, it implemented by data input
interface.

WriteAbortedException

In this exception to be thrown by the


ObjectStreamException during a write
121

then

operating.

Reading Text from the Standard Input


Standard Streams:
-

Standard Streams are a feature provided by many operating systems.


By default, they read input from the keyboard and write output to the
display. They also support I/O operations on files.

Java also supports three Standard Streams:


Standard Input: Accessed through System.in which is used to read input from the
keyboard.
Standard Output: Accessed through System.out which is used to write output to be
display.
Standard Error: Accessed through System.err which is used to write error output to be
display.
-

These objects are defined automatically and do not need to be opened


explicitly.
- Standard Output and Standard Error, both are to write output; having
error output separately so that the user may read error messages
efficiently.
- System.in is a byte stream that has no character stream features.
- To use Standard Input as a character stream, wrap System.in within the
InputStreamReader as an argument.
InputStreamReader inp = new InputStreamReader(system.in);
Working with Reader classes:
-

Java provides the standard I/O facilities for reading text from either the
file or the keyboard on the command line.
- The Reader class is used for this purpose that is available in the java.io
package.
- It acts as an abstract class for reading character streams.
- The only methods that a subclass must implement are read(char[], int,
int) and close(). the Reader class is further categorized into the
subclasses.
The following diagram shows a class-hierarchy of the java.io.Reader class.

122

However, most subclasses override some of the methods in order to provide higher
efficiency, additional functionality, or both.
InputStreamReader:
-

An InputStreamReader is a bridge from byte streams to character


streams i.e. it reads bytes and decodes them into Unicode characters
according to a particular platform.
- Thus, this class reads characters from a byte input stream. When you
create an InputStreamReader,
The syntax of InputStreamReader is written as:
InputStreamReader <variable_name> = new InputStreamReader(system.in)
BufferedReader :
-

The BufferedReader class is the subclass of the Reader class.


It reads character-input stream data from a memory area known as a
buffer maintains state.
The buffer size may be specified, or the default size may be used that
is large enough for text reading purposes.
BufferedReader converts an unbuffered stream into a buffered stream
using the wrapping expression, where the unbuffered stream object is
passed to the constructor for a buffered stream class.

For example the constructors of the BufferedReader class shown as:


BufferedReader(Reader in):Creates a buffering character-input stream that uses a
default-sized input buffer.
BufferedReader(Reader in, int sz): Creates a buffering character-input stream that uses an
input buffer of the specified size.
-

BufferedReader class provides some standard methods to perform


specific reading operations shown in the table.
All methods throws an IOException, if an I/O error occurs.

123

Method

Return Type

Description

read( )
read(char[] cbuf,
int len)

int

Reads a single character

int

Read characters into a portion of an array.

readLine( )

String

Read a line of text. A line is considered to be


terminated by ('\n').

close( )

void

Closes the opened stream.

int off,

This program illustrates you how to use standard input stream to read the user input..
import java.io.*;
public class ReadStandardIO{
public static void main(String[] args) throws IOException{
InputStreamReader

inp
=
new InputStreamReader(System.in)
BufferedReader br = new BufferedReader(inp);
System.out.println("Enter text : ");

String str = in.readLine();


System.out.println("You entered String : ");
System.out.println(str);

}
}

Working With File


-

Streams don't support all the operations that are common with a disk
file
In lesson, we will learn how to work with a file using the non-stream
file I/O.
The File class deals with the machine dependent files in a machineindependent manner i.e. it is easier to write platform-independent code
that examines and manipulates files using the File class.
This class is available in the java.lang package.
The java.io.File is the central class that works with files and
directories.
When a File object is created, the system doesn't check to the existence
of a corresponding file/directory.

124

If the file exist, a program can examine its attributes and perform
various operations on the file, such as renaming it, deleting it, reading
from or writing to it.

The constructors of the File class are shown in the table:


Constructor
Description
Create File object for default directory
(usually where program is located).

File(path)

File(dirpath,fname)
File(dir, fname)

Create File object for directory path given


as string.
Create File object for directory.

Thus the statement can be written as:


File f = new File("<filename>");
The methods that are used with the file object to get the attribute of a corresponding file
shown in the table.
Method
Description
f.exists()
Returns true if file exists.
f.isFile()
Returns true if this is a normal file.
f.isDirectory()
true if "f" is a directory.
f.getName()
Returns name of the file or directory.
f.isHidden()
Returns true if file is hidden.
f.lastModified()
Returns time of last modification.
f.length()
Returns number of bytes in file.
f.getPath()
path name.
f.delete()
Deletes the file.
Renames f to File f2. Returns true if
f.renameTo(f2)
successful.
f.createNewFile()

Creates a file and may throw IOException.

Create a File
Introduction
-

A file is used to store the data. File is a collection of stored information


that are arranged in string, rows, columns and lines etc.
For creating a new file File.createNewFile( ) method is used.
This method returns a boolean value true if the file is created otherwise
return false.

125

If the mentioned file for the specified directory is already exist then the
createNewFile() method returns the false otherwise the method creates
the mentioned file and return true.

Lets see an example that checks the existence of a specified file.


import java.io.*;
public class CreateFile1{
public static void main(String[] args) throws IOException{
File f;
f=new File("myfile.txt");
if(!f.exists()){
f.createNewFile();
System.out.println("New file \"myfile.txt\" has been created
to the current directory");
}
}
}

Constructing a File Name path


-

In Java, it is possible to set dynamic path, which is helpful for


mapping local file name with the actual path of the file using the
constructing filename path technique.

import java.io.*;
public class PathFile{
public static void main(String[] args) throws IOException{
File f;
f=new File("example" + File.separator + "myfile.txt");
f.createNewFile();
System.out.println("New file \"myfile.txt\"
has been created
to the specified location");
System.out.println("The absolute path of the file is: "
+f.getAbsolutePath());
}
}

Java read file line by line - Java Tutorial


Introduction
-

will learn how to write java program to read file line by line.

Java supports the following I/O file streams.


FileInputstream
126

FileOutputStream
FileInputstream:
-

This class is a subclass of Inputstream class that reads bytes from a


specified file name .
The read() method of this class reads a byte or array of bytes from
the file. It returns -1 when the end-of-file has been reached.
We typically use this class in conjunction with a BufferedInputStream
and DataInputstream class to read binary data.
To read text data, this class is used with an InputStreamReader and
BufferedReader class.
This class throws FileNotFoundException, if the specified file is not
exist. You can use the constructor of this stream as:

FileInputstream(File filename);
FileOutputStream:
-

This class is a subclass of OutputStream that writes data to a specified


file name.
The write() method of this class writes a byte or array of bytes to
the file.
We typically use this class in conjunction with a
BufferedOutputStream and a DataOutputStream class to write
binary data.
To write text, we typically use it with a PrintWriter, BufferedWriter
and an OutputStreamWriter class.

FileOutputstream(File filename);
DataInputStream:
-

This class is a type of FilterInputStream that allows you to read


binary data of Java primitive data types in a portable way.
In other words, the DataInputStream class is used to read binary Java
primitive data types in a machine-independent way.
An application uses a DataOutputStream to write data that can later be
read by a DataInputStream.

DataInputStream(FileOutputstream finp);
The following program demonstrate, how the contains are read from a file.
This program reads the bytes from file and display it to the user.

127

import java.io.*;
public class ReadFile{
public static void main(String[] args) throws IOException{
File f;
f=new File("myfile.txt");
if(!f.exists()&& f.length()<0)
System.out.println("The specified file is not exist");

else{
FileInputStream finp=new FileInputStream(f);
byte b;
do{
b=(byte)finp.read();
System.out.print((char)b);
}
while(b!=-1);
finp.close();
}
}

The another program use DataInputStreams for reading textual input line by line with an
appropriate BufferedReader.
import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null)
{
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}

128

Java Write To File - Java Tutorial


Introduction
-

FileOutputStream class is used to write data to a file.


Lets see an example that writes the data to a file converting into the
bytes.
This program first check the existence of the specified file.
If the file exist, the data is written to the file through the object of the
FileOutputStream class.

import java.io.*;
public class WriteFile{
public static void main(String[] args) throws IOException{
File f=new File("textfile1.txt");
FileOutputStream fop=new FileOutputStream(f);
if(f.exists()){
String str="This data is written through the program";
fop.write(str.getBytes());
fop.flush();
fop.close();
System.out.println("The data has been written");
}

else
System.out.println("This file is not

exist");

The another way for writing data to a file, the class FileWriter and BufferedWriter are
used.
FileWriter :
-

FileWriter is a subclass of OutputStreamWriter class that is used to


write text (as opposed to binary data) to a file.
You create a FileWriter by specifying the file to be written to, or
optionally, when the data should be appended to the end of an existing
file instead of overwriting that file.
The FileWriter class creates an internal FileOutputStream to write
bytes to the specified file

129

BufferedWriter :
-

The BufferedWriter class is used to write text to a character-output


stream, buffering characters so as to provide for the efficient writing of
single characters, arrays and strings.
The constructor of the FileWriter class takes the file name which has
to be buffered by the BufferedWriter stream.
The write( ) method of BufferedWriter class is used to create the file
into specified directory.

Following code write data into new file:


out.write(read_the_Buffered_file_name);
Following code creates the object of FileWriter and BufferedWriter:
FileWriter fstream = new FileWriter(file_name);
BufferedWriter out = new BufferedWriter(fstream);
-

Lets see an another example that writes the text input by the user using
the FileWriter and the BufferedWriter class.

import java.io.*;
public class FileWriter{

public static void main(String[] args) throws IOException{


BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter the file name to create : ");
String file_name = in.readLine();
File file = new File(file_name);
boolean exist = file.createNewFile();
if (!exist)
{
System.out.println("File already exists.");
System.exit(0);
}
else
{
FileWriter fstream = new FileWriter(file_name);
BufferedWriter out = new BufferedWriter(fstream);
out.write(in.readLine());
out.close();
System.out.println("File created successfully.");
}
}

130

Append To File - Java Tutorial


Introduction
- the class FileWriter and BufferedWriter to append the data to a file.
FileWriter
-

The FileWriter is a class used for writing character files.


The constructors of this class assume that the default character
encoding and the default byte-buffer size are acceptable.
This constructor simply overwrite the contents in the file by the
specified string but if you put the boolean value as true with the file
name (argument of the constructor) then the constructor append the
specified data to the file i.e. the pre-exist data in a file is not
overwritten and the new data is appended after the pre-exist data.

BufferedWriter
-

The BufferWriter class is used to write text to a character-output


stream, buffering characters so as to provide for the efficient writing of
single characters, arrays, and strings.

import java.io.*;
class FileWrite
{
public static void main(String args[])
{
try{
// Create file
FileWriter fstream = new FileWriter("out.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write("Hello Java");
//Close the output stream
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}

Getting the Size of a File in Java


Introduction
-

How to get the size (in bytes) of a specified file.


About the methods that can be used to get the file size.
If you give the text based file then the program tells you the number of
characters otherwise it will give you the file size in bytes.
Program takes the file name through the keyboard and checks whether
the file exists.
131

If the file exists then the length( ) method of the instance of the File
class gives you size of the file.

import java.io.*;
public class FileSize{
public static void main(String[] args) throws IOException{
System.out.print("Enter file name : ");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
File f = new File(in.readLine());
if(f.exists()){
long file_size = f.length();
System.out.println("Size of the file : " + file_size);
}
else{
System.out.println("File does not exists.");
}

System.exit(0);

}
}

Count lines of a particular file


-

Count the availability of text lines in the particular file.


A file is read before counting lines of a particular file,
File is a collection of stored information that are arranged in string,
rows, columns and lines etc.
Description of program:
- At the execution time of this program, it takes a file name with its
extension from a particular directory and checks it using the exists()
method.
- If the file exists, it will count lines of a particular file otherwise it will
display a message "File does not exists!".
Description of code:
FileReader(File file)
- This is the constructor of FileReader class that is reliable for reading a
character files.
- It constructs a new FileReader and takes a file name that have to be
read.

132

FileNumberReader():
-

This is the constructor of FileNumberReader class.


It constructs a new line-numbering reader.
It reads characters and puts into buffer. By default the numbering of
line begins from '0'.

import java.io.*;
public class NumberOfLine{
public static void main(String[] args) {
try{
System.out.println("Getting line number of a paritcular file example!");
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter file name with extension:");
String str = bf.readLine();
File file = new File(str);
if (file.exists()){
FileReader fr = new FileReader(file);
LineNumberReader ln = new LineNumberReader(fr);
int count = 0;
while (ln.readLine() != null){
count++;
}
System.out.println("Total line no: " + count);
ln.close();
}
else{
System.out.println("File does not exists!");
}
}
catch(IOException e){
e.printStackTrace();

133

}
}
}

Change a file timestamp


import java.io.*;
import java.util.*;
import java.text.*;
public class ChangeFileDate{
public static void main(String[] args) {
try{
System.out.println("Change file timestamp example!");
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter file name with extension:");
String str = bf.readLine();
System.out.println("Enter last modified date in 'dd-mm-yyyy' format:");
String strDate = bf.readLine();
SimpleDateFormat sdf= new SimpleDateFormat("dd-MM-yyyy");
Date date = sdf.parse(strDate);
File file = new File(str);
if (file.exists()){
file.setLastModified(date.getTime());
System.out.println("Modification is successfully!");
}
else{
System.out.println("File does not exists!");
}
}
catch(Exception e){
e.printStackTrace();

134

}
}
}

Applets
Introduction
-

Applet is java program that can be embedded into HTML pages. Java
applets runs on the java enabled web browsers such as mozila and
internet explorer .
Applet can't access system resources on the local computer.

Applets are used to make the web site more dynamic and entertaining.

Advantages of Applet:

Applets are cross platform and can run on Windows, Mac OS and Linux platform
Applets can work all the version of Java Plugin
Applets runs in a sandbox, so the user does not need to trust the code, so it can
work without security approval
Applets are supported by most web browsers
Applets are cached in most web browsers, so will be quick to load when returning
to a web page
User can also have full access to the machine if user allows

Disadvantages of Java Applet:

Java plug-in is required to run applet


Java applet requires JVM so first time it takes significant startup time
If applet is not already cached in the machine, it will be downloaded from internet
and will take time
Its difficult to desing and build good user interface in applets compared to HTML
technology

Applet versus Application


-

Applets as previously described, are the small programs while


applications are larger programs.
Applets don't have the main method while in an application execution
starts with the main method.
Applets can run in our browser's window or in an appletviewer. To run
the applet in an appletviewer will be an advantage for debugging.

135

Applets are designed for the client site programming purpose while the
applications don't have such type of criteria.

Applets are designed just for handling the client site problems. while
the java applications are designed to work with the client as well as
server.

Applications are designed to exists in a secure area. while the applets


are typically used.

Applications and applets have much of the similarity such as both have
most of the same features and share the same resources.

Applets are created by extending the java.applet.Applet class while the


java applications start execution from the main method. Applications
are not too small to embed into a html page so that the user can view
the application in your browser.

On the other hand applet have the accessibility criteria of the


resources. The key feature is that while they have so many differences
but both can perform the same purpose.
Applets are not capable of reading and writing the user's file system.
This means that the applet neither can access nor place anything
locally.

Applets are not capable of communicating the server than one from
which they are originating.

There are the cases in which an encryption key is used for the
verification purpose for a particular applet to a server. But accessing a
remote server is not possible.

The conclusion is that the java applets provides a wide variety of


formats for program execution and a very tight security model on the
open environment as on the Internet.

Applet runs in the browser and its lifecycle method are called by JVM
when it is loaded and destroyed.
Here are the lifecycle methods of an Applet:

Introduction

init(): This method is called to initialized an applet

136

start(): This method is called after the initialization of the applet.


stop(): This method can be called multiple times in the life cycle of an
Applet.
destroy(): This method is called only once in the life cycle of the applet
when applet is destroyed.
-

init () method: The life cycle of an applet is begin on that time when
the applet is first loaded into the browser and called the init() method.
The init() method is called only one time in the life cycle on an applet.

The init() method is basically called to read the PARAM tag in the
html file.

The init () method retrieve the passed parameter through the PARAM
tag of html file using get Parameter() method

After the initialization of the init() method user can interact with the
Applet and mostly applet contains the init() method.

Start () method: The start method of an applet is called after the


initialization method init().

This method may be called multiples time when the Applet needs to be
started or restarted.

For Example if the user wants to return to the Applet, in this situation
the start Method() of an Applet will be called by the web browser and
the user will be back on the applet.

In the start method user can interact within the applet.

Stop () method: The stop() method can be called multiple times in


the life cycle of applet like the start () method.

Or should be called at least one time.

There is only miner difference between the start() method and stop ()
method.

For example the stop() method is called by the web browser on that
time When the user leaves one applet to go another applet and the

137

start() method is called on that time when the user wants to go back
into the first program or Applet.
-

destroy() method: The destroy() method is called only one time in


the life cycle of Applet like init() method. This method is called only
on that time when the browser needs to Shut down.

< PARAM NAME = appletParameter1 VALUE = value >


-

The only way to specify applet-specific parameters is to use the


<PARAM> tags.
Applets read user-specified values for parameters with the
getParameter() method.

alternateHTML
If we use this <applet> tag in an HTML page to be viewed by the
browser, probably the browser will ignore the <APPLET> and
<PARAM> tags that doesn't understand the <APPLET> tag. Instead of
interpreting any other HTML code between the <APPLET> and
</APPLET> tags. Java-compatible browsers ignore this extra HTML
code.

<APPLET> Tag Parameters: The <PARAM> Tag


-

These are the parameters passed directly to a Java applet.


Parameters are to applets what command-line arguments are to
applications.

These parameters allow the user to customize the applet's operation.

APPLET parameters stored in the PARAM tag actually have little


directly to do with HTML.

It is the responsibility of the applet to check the parameter values and


respond accordingly.

We can increase the applet's flexibility, making the applet work in


multiple situations without recoding and recompiling it, by defining
the parameters.

The two steps of passing parameters to applets are:

138

1. First, add the PARAM tag (with values) to the HTML source file.
2. Second, add necessary code to the applet to retrieve these parameter values.
Lets see how to Pass Parameters to the Applet
<PARAM NAME=param_name VALUE=param_value>
Retrieving Parameters Within the Applet
-

These parameter values are retrieved by Java applets using the


getParameter() method.
This function is commonly called in the applet's init() method.

The
method
syntax
String getParameter(String name);

is

the

following:

Don't forget that the parameter names are case-sensitive when passing
parameters to applets.

Moreover all parameter values are converted to strings.

An applet is a program written in java programming language and


embedded within HTML page.
It run on the java enabled web browser such as Netscape navigator or
Internet Explorer.

Introduction
-

import java.applet.*;
import java.awt.*;
public class FirstApplet extends Applet{
public void paint(Graphics g){
g.drawString("Welcome in Java Applet.",40,20);
}
}

Here is the HTML code of the program:


<HTML>
<HEAD>
</HEAD>
<BODY>
<APPLET
ALIGN="CENTER"
HEIGHT="500"></APPLET>
</BODY>
</HTML>

CODE="FirstApplet.class"

Java - Drawing Shapes Example in java


Introduction
139

WIDTH="800"

Applet is a program to run on the browser and it is embedded on the


web page.
This program is not system level program but it is a network level
program.

The Applet class is a super class of any applet.

Applet viewer is used to view or test the applet whether the applet is
running properly or not.

There are different types of methods for the Graphics class of the
java.awt.*; package have been used to draw the appropriate shape.
Graphics.drawLine():The drawLine() method has been used in the program to draw the
line in the applet. Here is the syntax for the drawLine() method
drawLine(int X_from_coordinate, int Y_from_coordinate, int X_to_coordinate, int
Y_to_coordinate);
Graphics.drawString() :The drawSring() method draws the given string as the parameter.
Here is the syntax of the drawString() method :
drawString(String string, int X_coordinate, int Y_coordinate);
Graphics.drawOval():The drawOval() method draws the circle. Here is the syntax of the
drawOval() method :
g.drawOval(int X_coordinate, int Y_coordinate, int Wdth, int height);

Graphics.drawRect()

The drawRect() method draws the rectangle. Here is the syntax of the
drawRect() method :
g.drawRect(int X_coordinate, int Y_coordinate, int Wdth, int height)

import java.applet.*;
import java.awt.*;
public class CircleLine extends Applet{
int x=300,y=100,r=50;
public void paint(Graphics g){
g.drawLine(3,300,200,10);
g.drawString("Line",100,100);
g.drawOval(x-r,y-r,100,100);
g.drawString("Circle",275,100);

140

g.drawRect(400,50,200,100);
g.drawString("Rectangel",450,100);

Here is the HTML code of the program:


<HTML>
<HEAD>
</HEAD>
<BODY>
<div align="center">
<APPLET CODE="CircleLine.class" WIDTH="800" HEIGHT="500"></APPLET>
</div>
</BODY>
</HTML>

Java - Drawing Shapes Example using color in java


Introduction
Graphics.setColor()
:
This is the setColor() method which is the Graphics class method imported by the
java.awt.*; package. This method sets the color for the object by specified color. Here is
the syntax of the setColor() method :
g.setColor(Color.color_name);
Graphics.fillOval()
:
This is the fillOval() method used to fill the color inside the oval by specified color. Here
is the syntax of the fillColor() method :
g.fillColor(Color.color_name);
Graphics.fillRect()
:
This is the fillRect() method used to fill the color inside the rectangle by specified color.
Here is the syntax of the fillRect() method :
g.fillRect(int X_coordinate, int Y_coordinate, int Wdth, int height)
import java.applet.*;
import java.awt.*;
public class ShapColor extends Applet{
int x=300,y=100,r=50;
public void paint(Graphics g){
g.setColor(Color.red); //Drawing line color is red
g.drawLine(3,300,200,10);
g.setColor(Color.magenta);

141

g.drawString("Line",100,100);
g.drawOval(x-r,y-r,100,100);
g.setColor(Color.yellow);
//Fill the yellow color in circle
g.fillOval( x-r,y-r, 100, 100 );
g.setColor(Color.magenta);
g.drawString("Circle",275,100);
g.drawRect(400,50,200,100);
g.setColor(Color.yellow);
//Fill the yellow color in rectangel
g.fillRect( 400, 50, 200, 100 );
g.setColor(Color.magenta);
g.drawString("Rectangel",450,100);
}

Here is the HTML code of the program:


<HTML>
<HEAD>
</HEAD>
<BODY>
<div align="center">
<APPLET ALIGN =
"500"></APPLET>
</div>
</BODY>
</HTML>

"CENTER"

CODE

"ShapColor.class"

WIDTH

"800">

HEIGHT

Applet Passing Parameter in Java Applet


Introduction
-

Java applet has the feature of retrieving the parameter values passed
from the html page.
So, you can pass the parameters from your html page to the applet
embedded in your page.

The param tag(<parma name="" value=""></param>) is used to pass


the parameters to an applet.

For the illustration about the concept of applet and passing parameter
in applet, a example is given below.

In this example, we will see what has to be done in the applet code to retrieve the value
from parameters. Value of a parameter passed to an applet can be retrieved using
getParameter() function. E.g. code:
String strParameter = this.getParameter("Message");

Printing the value:


142

Then in the function paint (Graphics g), we prints the parameter value
to test the value passed from html page.
Applet will display "Hello! Java Applet" if no parameter is passed to
the applet else it will display the value passed as parameter.
In our case applet should display "Welcome in Passing parameter in
java applet example." message.

Here is the code for the Java Program :


import java.applet.*;
import java.awt.*;
public class appletParameter extends Applet {
private String strDefault = "Hello! Java Applet.";
public void paint(Graphics g) {
String strParameter = this.getParameter("Message");
if (strParameter == null)
strParameter = strDefault;
g.drawString(strParameter, 50, 25);
}
}
Here is the code for the html program :
<HTML>
<HEAD>
<TITLE>Passing Parameter in Java Applet</TITLE>
</HEAD>
<BODY>
This is the applet:<P>
<APPLET code="appletParameter.class" width="800" height="100">
<PARAM name="message" value="Welcome in Passing parameter in java applet example.">
</APPLET>
</BODY>
</HTML>

There is the advantage that if need to change the output then you will
have to change only the value of the param tag in html file not in java
code.
Compile the program :

javac appletParameter.java

Output after running the program :


-

To run the program using appletviewer, go to command prompt and


type appletviewer appletParameter.html Appletviewer will run the
applet for you and and it should show output like Welcome in Passing
parameter in java applet example.

143

Alternatively you can also run this example from your favorite java
enabled browser.

Security Issues with the Applet


Some security issues to applet are following :

Applets are loaded over the internet and they are prevented to make open network
connection to any computer, except for the host, which provided the .class file.
Because the html page come from the host or the host specified codebase
parameter in the applet tag, with codebase taking precedence.

They are also prevented from starting other programs on the client. Applets are
not allowed to invoke any program to list the contents of your file system that
means it cant invoke System.exit() function to terminate you web browser. And
they are not allowed to manipulate the threads outside the applets own thread
group.

Applets are loaded over the net. A web browser uses only one class loader thats
established at start up. Then the system class loader can not be overloaded,
overridden, extended, replaced. Applet is not allowed to create the reference of
their own class loader.
They cant load the libraries or define the native method calls. But if it can define
native method calls then that would give the applet direct access to underlying
computer

What is Java Swing?


-

The Java Swing provides the multiple platform independent APIs


interfaces for interacting between the users and GUIs components.
All Java Swing classes imports form the import javax.swing.*;
package.

Java provides an interactive features for design the GUIs toolkit or


components like: labels, buttons, text boxes, checkboxes, combo
boxes, panels and sliders etc.

All AWT flexible components can be handled by the Java Swing.

The Java Swing supports the plugging between the look and feel
features.

144

The look and feel that means the dramatically changing in the
component like JFrame, JWindow, JDialog etc. for viewing it into the
several types of window.

Here the following APIs interfaces and classes are available:


The following interfaces and it's descriptions to be used by the Java swing.

Interfaces
Action

Descriptions
This interface performed the action with the
ActionListener where the multiple controls are
used for same purposes.
BoundedRangeModel
This interface defines the data model of components
like: sliders and progressBars.
ButtonModel
It defines the state model for the buttons like: radio
buttons, check boxes etc.
CellEditor
This interface used by the developer for creating the
new editor and it has the new components
implement interfaces. The CellEditor implements
the wrapper based approach.
ComboBoxEditor
In this interface, the editor component used to
JComboBox components.
ComboBoxModel
This interface represents the data model in a list
model with the selected items.
DesktopManager
This interface has JDesktopPane object. The
JInternalFrame implements in the JDesktopPane
with the help of DesktopManager.
Icon
This interface used to graphical representation of the
components. It has fixed size picture.
JComboBox.KeySelectionManager This interface has KeySelectionManager and used
for the combo box data model.
ListCellRenderer
This interface used for paint the cell in the list with
the help of "rubber stamps" .
ListModel
This interface used for JList components method. It
gets the value of each cell of list.
ListSelectionModel
This interface indicates the components, which are
stable or not.
MenuElement
This interface used where the any components are
implements in the menu.
MutableComboBoxModel
This interface extends from the ComboBoxModel.
It is a mutable version of ComboBoxModel.
Renderer
It defines the requirements of an object for
145

RootPaneContainer

Scrollable
ScrollPaneConstants
SingleSelectionModel
SwingConstants
UIDefaults.ActiveValue
UIDefaults.LazyValue

WindowConstants

displaying the values.


This interface uses the RootPane properties and it
has the components like: JFrame, JInternalFrame
and JWindow etc.
This interface provides the scrolling to show the
large amount of data with the help of JScrollPane.
This interface used for JScrollPane components.
This interface used to select the one index in a
model.
You can set the components on the screen to own
requirements.
It constructs the DefaultListCellRenderer.
This enables one to store an entry in the default
table. The entered value is not constructed until first
time is a real value is created through it using
LazyValue.createValue() method.
This interface has two methods
setDefaultCloseOperation and
getDefaultCloseOperation and provides the window
close opration.

The following classes and it's descriptions to be used by the Java swing.

Classes
AbstractAction
AbstractButton
AbstractCellEditor
AbstractListModel
ActionMap
BorderFactory
Box

Box.Filler

Descriptions
This class handles the any types of action and
provides JFC Action interface.
This class defines the nature of buttons and menu
items.
It provides a list and contents of the data model.
This class defines the data model which provides
the list with its contents.
This class works with InputMap and performs
any action when the key is pressed.
This class extends from Object and creates the
Border instance in the factory.
It provides the fixed spaces between two
components and uses the BoxLayout object of
the layout manager.
This class participates in the Layout and uses the
lightweight components.

146

BoxLayout

This class uses the arranging the multiple


components either horizontally or vertically. The
Box container uses this class.
ButtonGroup
This class used to create the multiple buttons in a
ButtonGroup object.
CellRandererPane
This class used to insert the components like:
JList, JTable and JTree.
ComponentInputMap
This class has ComponentInputMap constructor
and creates the components with the help of
InpuMap.
DebugGraphics
It extends from the Graphics and used to debug
the graphics
DefaultBoundedRangeModel
This class provides the implementation of default
BoundedRangeModel.
DefaultButtonModel
This class implements the generic ButtonModel.
DefaultCellEditor
It implements the TableCellEditor and
TreeCellEditor for the table and tree cells.
DefaultComboBoxModel
It provides the default model for combo boxes.
DefaultDesktopManager
It implements the DesktopManager. The
DesktopManager has the JInternalFrame for
creating the internal fame in a frame.
DefaultFocusManager
It provides the implementing the FocusManager.
DefaultListCellRanderer
It implements the default ListCellRanderer.
DefaultListCellRanderer.UIResource This extends the DefaultListCellRanderer and
implementing in the UIResource.
DefaultListModel
It extends the AbstractListModel and
implementing the java.util.Vector.
DefaultListSelectionModel
This class used for select the list in a data model.
DefaultSingleSelectionModel
This class provides the default
SingleSelectionModel.
FocusManager
It handles all focus like: gainedFocus and
lostFocus.
GrayFilter
It extends the RGBImageFilter and used for
disabling the image through the button.
ImageIcon
This class implements the Icon and paints the
icons from the images.
InputMap
This class uses the ActionMap to performed the
action when you press any key of keyboard. It
bounds data between the input event and an
object.
InputVerifier
This class helps you when you works with the
text fields through the focus.
147

JApplet
Jbutton
JCheckBox

JCheckBoxMenuItem
JColorChooser

JComboBox

JComponent

JDesktopPane

Jdialog

JEditorPane
JFileChooser
Jframe
JInternalFrame

JInternalFrame.JDesktopIcon
Jlabel
JLayeredPane
Jlist

This class extends the Applet and implements the


Accessible and RootPaneContainer.
This class extends the AbstractButton and you
can create the new button.
This class extends the JToggleButton and
implements the check box in which buttons are
selected or deselected.
It extends the JMenuItem and determines the
items which is selected or deselected.
It extends the JComponent and implementing the
Accessable. Here, you choose and manipulate the
colors.
This class extends the JComboBox. It provides
the drop-down list where user select only one
item or value at a time. But combo box is a
combination of multiple text or buttons etc.
In java swing, All components are used the
JComponent except the top-level containers like:
JFrame, JDialog etc.
This class extends the JLayeredPane and when
you create the object of JInternalFrame to be
maintained in the JDesktopPane. The
JDesktopPane has DesktopManager.
It extends the Dialog. This class used to create the
dialog window and when you want to create the
custom dialog window with the help of
JOptionPane method.
This class extends the JTextComponent. It edits
the component by the EditorKit.
This class provides the facility to choosing the
file.
It extends the Frame and supports the swing
components architecture.
This class extends from the JComponent and
provides the facility to dragging, closing, resizing
and menu bar of the internal frame. The
JInternalFrame added into the JDesktopPane.
It displays the desktop icon and create the
instance of JInternalFrame and iconify.
This class used to show the small text and image.
It has JFC/Swing container that can be used to
overlap the components to each other.
This class used to create a list where you select
148

Jmenu

JMenuBar
JMenuItem
JOptionPane

Jpanel
JPassworkField

JPopupMenu

JPopupMenu.Separator
JProgressBar

JRadioButton
JRadioButtonMenuItem
JRootPane

JScrollBar

JScrollPane
JSeparator
Jslider
JSplitPane

the one or more than objects.


This class used to create a new menu where you
add the JMenuItems. When you select the item
then shows the popup menu items in the
JMenuBar.
It used to create a new menu bar where the
JMenu objects are added.
This class used to create new menu items in the
mebus.
It used to create some different types of dialog
box like: message dialog box, error dialog box
etc.
It extends the JComponent and used to create a
new panel.
It provides the single line text editing. Here, don't
available the original characters but view type
indication characters are available.
This class used to create a popup menu. It
provides small window where the various types
of choices are available.
Here the popup menu and the separator are
available.
It shows the integer types values in percent within
a bounded range to determine the working
process.
It implements the radio button and shows the
state of an item selected or deselected.
It extends the JMenuItem and implements the
radio button menu item
This class provides the component behind the
scenes by JFrame, JWindow, JDialog etc. for
providing the task-orientation and functionality.
This class used to create a scroll bar. It provides
the view content area where you show the content
to scroll this.
It provides the scrollable view components.
This class use the separator among the
components.
This class provides a control to represent a
numeric value by dragging the slider.
This class used to divides the two components
graphically like: top and button, left and right.

149

JTabbedPane

Jtable
JTextArea
JTextField
JTextPane
JToggleButton
JToggleButton.ToggleButtonModel
JToolBar
JToolBar.Separator
JToolTip
Jtree
JTree.DynamicUtilTreeNode
JTree.EmptySelectionModel
JViewPort
JWindow

KeyStroke
LayoutFocusTraversalPolicy
LookAndFeel

MenuSelectionManager
OverlayLayout
ProgressMonitor
ProgressMonitorInputStream

This class provides the tab component through


which you can switch from one component to
another component regarding to the specific tab
button by clicking on that.
It provides the user interface component and
represents the two dimensional data.
It provides the multi line plain text area.
It provides the facility to editing the text in a
single line.
This class provides the component like JTexArea
for multiple lines text with more capabalities.
It implements two state button that means
selected or deselected.
It extends the DefaultButtonModel and provides
the ToggleButton model.
It provides set of command buttons icons that
performs the different actions or controls.
It provides the tool bar separator.
It shows the tool tips related to it's components.
It shows the data in a hierarchical way.
This extends the DefaultMutableTreeNode and
create children nodes.
It does not allows the any selection.
It gives you about the underlying information.
It extends window and shows the any location or
area on the desktop. It couldn't any title bar and
window management buttons.
This class controls the key events on the
keyboard for the equivalent device.
This class conducts the sorting objects according
to their size, type, position or orientation.
It provides the dramatically changes in the
component like frame related to the graphics for
the application. Through this the application can
be done very efficient and easier.
It has menu selection hierarchy.
The layout manager arrange the components.
This class is used to monitoring the progress of
any operation to be done.
This class creates a progress monitor to monitor
the progress of reading input from the input

150

RepaintManager
ScrollPaneLayout

ScrollPaneLayout.UIResource
SizeRequirements
SizeSequence
SwingUtilities
Timer
ToolTipManager
UIDefaults
UIDefaults.LazyInputMap

UIDefaults.ProxyLazyValue

UIManager
UIManager.LookAndFeelInfo

ViewportLayout

stream. It cleanups all the rights when the stream


is closed.
This class manage and override the repaint
requests.
It implements the LayoutManager and manage
the components like: scroll bar, row header,
column header etc.
It extends the ScrollPaneLayout and implements
the UIResource.
It calculates the size and positions of components.
It represents the order list of size and it's
positions.
This class has utilities methods for swing.
Actions perform the predefined rate.
It manages the all tool tips.
It extends the Hashtable and you set/get the
value with the help of UIManager.
This class creates a Input Map through it's
createValue() method. The array of key after
binding is passed to the constructor of this.
Example of binding of key is array of pressing
key information (e.g. ctrl + c or alt + f).
This class is used to create a lazy value which is
used to delay loading of the class to create
instance for that.
This class has track of the current look and feel
details.
This is the nested class of UIManager class i.e.
used for getting information about all the look
and feels installed with the software development
kit.
It implements the LayoutManager and defines
the policy for the layout.

The following Exceptions and it's description to be used by the Java swing.

Exception

Descriptions
This exception occurred when the look and feel
UnsupportedLookAndFeelException
classes are not supported to user's system.

151

Creating a Frame : Swing Tutorials


-

In the Java Swing, top-level windows are represented by the JFrame


class. Java supports the look and feel and decoration for the frame.
For creating java standalone application you must provide GUI for a
user.

The most common way of creating a frame is, using single argument
constructor of the JFrame class.

The argument of the constructor is the title of the window or frame.

Other user interface are added by constructing and adding it to the


container one by one.

The frame initially are not visible and to make it visible the
setVisible(true) function is called passing the boolean value true.

The close button of the frame by default performs the hide operation
for the JFrame.

In this example we have changed this behavior to window close


operation
by
setting
the
setDefaultCloseOperation()
to
EXIT_ON_CLOSE value.

setSize (400, 400):


Above method sets the size of the frame or window to width (400) and height (400)
pixels.
setVisible(true):
Above method makes the window visible.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE):
Above code sets the operation of close operation to Exit the application using the System
exit method.
import javax.swing.*;

152

public class Swing_Create_Frame{


public static void main(String[] args){
JFrame frame = new JFrame("Frame in Java Swing");
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Show Dialog Box in Java - Swing Dialogs


-

Message dialog box is used to display informative messages to the


user.
In this section we will use JOptionPane class to display the message
Dialog box.
Our program display "Click Me" button on the window and when user
clicks on it program displays Message box with "OK" button and
message "Welcome".

Program description:
JOptionPane Class:
-

In non-swing application we were using System.in class for input or


output some text or numeric values but now in the swing application
we can use JOptionPane to show the output or show the message.

This way of inputting or outputting works very efficiently in the Swing


Applications.

The window for showing message for input or output makes your
application very innovative.

JOptionPane class is available in the javax.swing.*; package. This class provide various
types of message dialog box as follows:

153

A simple message dialog box which has only one button i.e. "Ok". This type of
message dialog box is used only for showing the appropriate message and user
can finish the message dialog box by clicking the "Ok" button.
A message dialog box which has two or three buttons. You can set several values
for
viewing
several
message
dialog
box
as
follows:
1.) "Yes" and "No"
2.) "Yes", "No" and "Cancel"
3.) "Ok", and "Cancel"
A input dialog box which contains two buttons "Ok" and "Cancel".

The JOptionPane class has three methods as follows:

showMessageDialog(): First is the showMessageDialog() method which is used


to display a simple message.
showInputDialog(): Second is the showInputDialog() method which is used to
display a prompt for inputting. This method returns a String value which is
entered by you.
showConfirmDialog(): And the last or third method is the
showConfirmDialog() which asks the user for confirmation (Yes/No) by
displaying message. This method return a numeric value either 0 or 1. If you click
on the "Yes" button then the method returns 1 otherwise 0.

How program Works:


This program illustrates you how to show a message dialog box when you click on the
button.
showMessageDialog():
-

This method is used to show a message dialog box which contains


some text messages.
This is being used with two arguments in the program where the first
argument is the parent object in which the dialog box opens and
another is the message which has to be shown.

import javax.swing.*;
import java.awt.event.*;
public class ShowDialogBox{
JFrame frame;
public static void main(String[] args){
ShowDialogBox db = new ShowDialogBox();
}
public ShowDialogBox(){
frame = new JFrame("Show Message Dialog");
JButton button = new JButton("Click Me");
button.addActionListener(new MyAction());

154

frame.add(button);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

public class MyAction implements ActionListener{


public void actionPerformed(ActionEvent e){
JOptionPane.showMessageDialog(frame,"Welcome");
}
}
}

Swing Input Dialog Box Example - Swing Dialogs


-

Input dialog box is very important and interactive feature of Java


Swing.
You have been using the System.in for inputting anything from user.
Java Swing provides the facility to input any thing (whether the text or
the numeric values) in a normal window i.e. the Input Dialog Box. The
input dialog box contains two buttons, first is the "Ok" button and
another is the "Cancel" button

When you run the given program, this shows a button labeled by "Show Input Dialog
Box" on the frame. If you click on the button then a input dialog box will open. If you
click on the "Ok" button of the input dialog button then a message dialog box is seen
which has the message "You entered the text : entered_text" otherwise it will display a
message dialog box that has the message "You pressed cancel button.".
Here is the code of the program:
import javax.swing.*;
import java.awt.event.*;
public class ShowInputDialog{
public static void main(String[] args){
JFrame frame = new JFrame("Input Dialog Box Frame");
JButton button = new JButton("Show Input Dialog Box");
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
String str = JOptionPane.showInputDialog(null, "Enter some text : ",
Welcome
", 1);
if(str != null)
JOptionPane.showMessageDialog(null, "You entered the text : " + str,
"
Welcome
", 1);
else
JOptionPane.showMessageDialog(null, "You pressed cancel button.",
"
Welcome
", 1);
}
});

155

JPanel panel = new JPanel();


panel.add(button);
frame.add(panel);
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

Drawing with Color in Java


drawRect():
This is the method of the Graphics class (The Graphics class is used to drawing
different-different type of shapes). This method draws the rectangle. It takes some integer
value as parameter. This method is written like : Graphics.drawRect(x, y, height, width);.
x - This is the variable represents the row no. or the x - coordinate.
y - This is also a variable represents the column no. or the y - coordinate.
drawOval():
This is the method of the Graphics class which draws the oval on the frame. This method
takes argument same as the drawRect() method. In this method first come the width and
then height is specified.
fillRect():
This is the method of the Graphics class which is used to fill rectangle with the specified
color which is set before using the setColor() method of the Graphics class. It also takes
argument same as the drawRect() method.
fillOval():
This is also the method of the Graphics class which is used to fill the oval with color
specified in the setColor() method before. This method also takes argument same as the
drawOval() method.
Here is the code of program:
import javax.swing.*;
import java.awt.*;
public class DrawingColor{
public static void main(String[] args) {
DrawingColor d = new DrawingColor();
}
public DrawingColor(){
JFrame frame = new JFrame("Drawing with Alpha");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

156

frame.getContentPane().add(new MyComponent());
frame.setSize(400,400);
frame.setVisible(true);
}
public class MyComponent extends JComponent{
public void paint(Graphics g){
int height = 200;
int width = 120;
g.setColor(Color.red);
g.drawRect(10,10,height,width);
g.setColor(Color.gray);
g.fillRect(11,11,height,width);
g.setColor(Color.red);
g.drawOval(250,20, height,width);
g.setColor(Color.magenta);
g.fillOval(249,19,height,width);
}
}
}

Creating Check Box in Java Swing


This section illustrates you how to create a Check Box component in Java Swing.
In this section, you can learn simply creating the Check Box in Java Swing. Check Boxes
are created in swing by creating the instance of the JCheckBox class using it's
constructor which contains the string which has to be shown beside the check box on the
frame or window like this:
This is written like:
JCheckBox chk = new JCheckBox("This is the Check Box");
This component of the javax.swing.*; is added to the frame using the add(component)
method of the JFrame class.
Here is the code of the program:
import javax.swing.*;
public class CreateCheckBox{
public static void main(String[] args){
JFrame frame = new JFrame("Check Box Frame");
JCheckBox chk = new JCheckBox("This is the Check Box");
frame.add(chk);
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

157

frame.setVisible(true);
}

Create a JComboBox Component in Java


In this section, you will learn about the JComboBox Component of swing in java. The
JComboBox is used to display drop-down list. It provides you options to select an item
from the item list. You can never select more than one items from a combo box. Combo
Box can be whether editable or only non-editable means only readable.
This program displays a simple combo box on the frame which contains multiple items
like: BCA, MCA, PPC etc. The background color of this combo box is gray and
foreground color is red. Here, the background color of the combo box and the foreground
color is set using the setBackground(Color) and setForeground(Color) method of the
JComboBox class. When you select the item from the combo box then the selected item
is displayed in the text box. Image of the result for the given program is as follows in the
pictorial form:
APIs used in the program:
JComboBox:
This is the class which is used to create a combo box in swing using it's constructor.
itemStateChanged():
This is the method which receives the ItemEvent generated by the addItemListener()
method of the JComboBox class. The event is generated when you select item from the
combo box.
Here is the code of program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ComboBox{
JComboBox combo;
JTextField txt;
public static void main(String[] args) {
ComboBox b = new ComboBox();
}
public ComboBox(){
String course[] = {"BCA","MCA","PPC","CIC"};
JFrame frame = new JFrame("Creating a JComboBox Component");
JPanel panel = new JPanel();
combo = new JComboBox(course);

158

combo.setBackground(Color.gray);
combo.setForeground(Color.red);
txt = new JTextField(10);
panel.add(combo);
panel.add(txt);
frame.add(panel);
combo.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent ie){
String str = (String)combo.getSelectedItem();
txt.setText(str);
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
frame.setVisible(true);
}

Combo Box operation in Java Swing


In this section, you can learn how to operate the Combo Box component, you will learn
how to add items to the combo box, remove items from the combo box.
This program shows a text field, a combo box and two command buttons, first is for the
adding items to the combo box and another is for the removing items from the combo.
When you click on the add command button then the text of the text box is added to the
combo box if the text box is not blank otherwise a message box will display with the
message "Please enter text in Text Box". But when you click on the remove button the
item at the 0th (zero) position of the combo box will be remove from the combo box if
the combo box has one item at least otherwise a message box will display with the
message "Item not available.". Following is the image for the result of the given program:
This program has used various java APIs for doing required are explained as follows:
JComboBox combo = new JComboBox(items);
The above code has been used to create a combo box in this program. The JComboBox
instance combo is created using the constructor of the JComboBox class of the
javax.swing.*; package. This constructor holds the string array in which items for the
combo box are kept.
getItemCount():
This is the method of the JComboBox class which return the number of the items present
is the combo box.
getItemAt(index):
this is the method of the JComboBox class which returns the name of the item of the

159

combo box at the specified position. This specification of position the item in the combo
box is held by the getItemAt() method as a parameter.
showMessageDialog():
This the method of the JOptionPane class of javax.swing.*; package. This method
displays some messages in the special dialog box. This method holds two argument in
this program in which first is the parent object name and another is the message text
which has to be displayed.
addItem(String):
This is the method of the JComboBox class which adds items to the combo box. This
method takes a string argument which is to be used to add to the combo box.
removeItemAt(index):
This is the method of the JComboBox class which remove the item at the specified
position of the combo box. This method holds the integer value for the position number
of he of the item in combo box to remove it.
Here is the code of the program:
import javax.swing.*;
import java.awt.event.*;
public class AddRemoveItemFromCombo{
JComboBox combo;
JTextField txtBox;
public static void main(String[] args){
AddRemoveItemFromCombo ar = new AddRemoveItemFromCombo();
}
public AddRemoveItemFromCombo(){
JFrame frame = new JFrame("Add-Remove Item of a Combo Box");
String items[] = {"Java", "JSP", "PHP", "C", "C++"};
combo = new JComboBox(items);
JButton button1 = new JButton("Add");
txtBox = new JTextField(20);
button1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if (!txtBox.getText().equals("")){
int a = 0;
for(int i = 0; i < combo.getItemCount(); i++){
if(combo.getItemAt(i).equals(txtBox.getText())){
a = 1;
break;
}
}
if (a == 1)
JOptionPane.showMessageDialog(null,"Combo has already this item.");
else
combo.addItem(txtBox.getText());
}
else{

160

JOptionPane.showMessageDialog(null,"Please enter text in Text Box");


}

}
});
JButton button2 = new JButton("Remove");
button2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if (combo.getItemCount() > 0)
combo.removeItemAt(0);
else
JOptionPane.showMessageDialog(null,"Item not available");
}
});
JPanel panel = new JPanel();
JPanel panel1 = new JPanel();
panel.add(txtBox);
panel.add(combo);
panel.add(button1);
panel.add(button2);
frame.add(panel);
frame.add(panel1);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//

Create a JRadioButton Component in Java


In this section, you will learn how to create a radio button in java swing. Radio Button is
like check box. Differences between check box and radio button are as follows:
1. Check Boxes are separated from one to another where Radio Buttons are the
different-different button like check box from a same ButtonGroup.
2. You can checks multiple check boxes at once but this can never done in the case
of radio button. You can select only one radio button at once from a group of the
radio button.
3. You can check or uncheck the check box but you can on check the radio button by
clicking it once.
Here, you will see the JRadioButton component creation procedure in java with the help
of this program. This example provides two radio buttons same ButtonGroup. These
radio buttons represent the option for choosing male or female. Following is the image
for the result of the given program:

The creation of JRadioButton are completed by the following methods:


161

ButtonGroup:
This is the class of the javax.swing.*; package, which is used to create a group of radio
buttons from which you can select only one option from that group of the radio buttons.
This is class is used by creating a instance of if using it's constructor. Radio Buttons are
added to the specified group using the add(JRadioButton) method of the ButtonGroup
class.
JRadioButton:
This is the class has been used to create a single radio button for the application.
setSelected():
This method sets the value of the radio button. This method takes a boolean value either
true or false. If you pass true value then the radio button will be selected otherwise the
radio button is not selected.
Here is the code of program:
import javax.swing.*;
import java.awt.*;
public class CreateRadioButton{
public static void main(String[] args) {
CreateRadioButton r = new CreateRadioButton();
}
public CreateRadioButton(){
JRadioButton Male,Female;
JFrame frame = new JFrame("Creating a JRadioButton Component");
JPanel panel = new JPanel();
ButtonGroup buttonGroup = new ButtonGroup();
Male = new JRadioButton("Male");
buttonGroup.add(Male);
panel.add(Male);
Female = new JRadioButton("Female");
buttonGroup.add(Female);
panel.add(Female);
Male.setSelected(true);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
frame.setVisible(true);
}
}

Setting Tool Tip Text for items in a JList


Component
162

In this section, you will learn how to set the tool tip text for items present in the JList
component of the Java Swing. Tool Tip text is the help text of any component for user.
When you rest the mouse cursor on the component then at that point a message which
small font and yellow background stay there for few seconds. This text show the
information about that component.
This program has used the tool tip text for items present in the JList component in Java
Swing. In this program, you can add more and more items. You can enter the item name
in the text box and click on the "Add" button. When you move the mouse pointer around
the items in the list, it shows the specific item name as a tool tip text like the following
image:

Following are some methods and APIs are explained as follows:


JScrollPane:
This is the class of javax.swing.*; package of Java Swing. This class is used to create
scroll bar (Horizontal or Vertical) for any component. This program has used this for
creating scroll bar for the text area. It creates scroll bar using it's constructor which holds
the component name for which the scroll bar has to be created.
DefaultListModel:
This is the class of javax.swing.*; package of Java. This class is used to create a list
model which is helpful for adding items for the list. This class has used own method to
add items in the list.
locationToIndex():
This is the method of the MultiListUI class which is imported from the
javax.swing.plaf.multi.*; package of Java. This method locate the item to the index where
the mouse pointer points. This method takes a integer value for locating item from the list
according to the given point.
getModel():
This is the method of JList class which holds the list of item which are shown in the JList
component of Java Swing. It returns the list model.

163

getElementAt(index):
This is the method of DefaultListModel class which gets the item from the returned list
model by getModel() method according to the given integer index no. as parameter.
addElement(String):
This is the method of DefaultListModel class which adds the item into the list.
Here is the code of the program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TooltipTextOfList{
private JScrollPane scrollpane = null;
JList list;
JTextField txtItem;
DefaultListModel model;
public static void main(String[] args){
TooltipTextOfList tt = new TooltipTextOfList();
}
public TooltipTextOfList(){
JFrame frame = new JFrame("Tooltip Text for List Item");
String[] str_list = {"One", "Two", "Three", "Four"};
model = new DefaultListModel();
for(int i = 0; i < str_list.length; i++)
model.addElement(str_list[i]);
list = new JList(model){
public String getToolTipText(MouseEvent e) {
int index = locationToIndex(e.getPoint());
if (-1 < index) {
String item = (String)getModel().getElementAt(index);
return item;
} else {
return null;
}
}
};
txtItem = new JTextField(10);
JButton button = new JButton("Add");
button.addActionListener(new MyAction());
JPanel panel = new JPanel();
panel.add(txtItem);
panel.add(button);
panel.add(list);
frame.add(panel, BorderLayout.CENTER);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public class MyAction extends MouseAdapter implements ActionListener{
public void actionPerformed(ActionEvent ae){

164

}
}

String data = txtItem.getText();


if (data.equals(""))
JOptionPane.showMessageDialog(null,"Please enter text in the Text Box.");
else{
model.addElement(data);
JOptionPane.showMessageDialog(null,"Item added successfully.");
txtItem.setText("");
}

Disabling Keyboard Editing in a JSpinner Component


In this section, you will see how to create a non editable Spinner component of Java
Swing. You can increase it's value by clicking up and down button. Through the given
program you can only increase and decrease the value nor write the value directly in the
Spinner component of java. The JSpinner component, which is disable for the keyboard
editing looks like the following image:

In this program, a Spinner component has been created and set for editing mode of the
Spinner. The Spinner has been disabled for editing using setEditable() method. Some
following methods and APIs are explained as follows:
JFormattedTextField:
This is the class of javax.swing.*; package which creates formatted text field for edit text
in the specified format. For creating a JFormattedTextField, the syntax is written like:
JFormattedTextField tf =
((JSpinner.DefaultEditor)spinner.getEditor()).getTextField();
getTextField():
This method creates a JFormattedTextField for edit in the specified format. This is
defined in the JSpinner.DefaultEditor class.
getEditor():
This is the method of JSpinner class. This method is used to get the editor which has
been using for the JSpinner component.
Here is the code of the program:

165

import javax.swing.*;
import java.awt.*;
public class DesableEditingSpinner{
public static void main(String[] args){
JFrame frame = new JFrame("Desabling editing Spinner");
JSpinner spinner = new JSpinner();
JFormattedTextField tf = ((JSpinner.DefaultEditor)spinner.getEditor())
.getTextField();
tf.setEditable(false);
spinner.setValue(new Integer(100));
JPanel panel = new JPanel();
panel.add(spinner);
frame.add(panel, BorderLayout.NORTH);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

JSlider Component of Java Swing


In this section, you will learn how to create a JSlider component of Java Swing. A Slider
is a Swing tool which you can use for selecting a range. There is minimum chances of
being mistake to illegal input values.
In this program, events on the JSlider component have also been shown. If you increase
or decrease the slider by selecting then the actual position of the slider will be displayed
on a label. The figure for the result of the given program is followed below:
Before touch the JSlider Component:

After drag the JSlider Component:

For these purposes, some methods and APIs have been used to create a JSlider
component and performs various tasks related to the slider. Methods and APIs are as
follows:

166

JSlider:
This is the class which creates the slider for the swing application. For creating the slider
this class creates a instance using it's constructor JSlider().
ChangeListener:
This is the interface of which is used to call stateChanged() method which receives the
event generated by the slider using addChangeListener() method of the JSlider class.
ChangeEvent:
This is the class which handle the event generated by the JSlider component on change
the state.
addChangeListener(object):
This is the method of the JSlider class which is used to handle event on change the
selected state of the JSlider component.
Here is the code of the program:
import
import
import
import

javax.swing.*;
javax.swing.event.*;
java.awt.*;
java.awt.event.*;

public class CreateSlider{


JSlider slider;
JLabel label;
public static void main(String[] args){
CreateSlider cs = new CreateSlider();
}
public CreateSlider(){
JFrame frame = new JFrame("Slider Frame");
slider = new JSlider();
slider.setValue(70);
slider.addChangeListener(new MyChangeAction());
label = new JLabel("Roseindia.net");
JPanel panel = new JPanel();
panel.add(slider);
panel.add(label);
frame.add(panel, BorderLayout.CENTER);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public class MyChangeAction implements ChangeListener{
public void stateChanged(ChangeEvent ce){
int value = slider.getValue();
String str = Integer.toString(value);
label.setText(str);
}
}

167

Progress Bar in Java Swing

In this section, you can learn how to handle progress bar in java swing. This section
shows you how the progress bar starts and stops with the timer. Through the given
example you can understand how the progress bar is created for showing your work is in
progress.
This program shows you a frame in which a button labeled by the string "Start", a
progress bar and another is the label which has been used to display some messages.
When you click on the "Start" button progress bar is started to progress the completed
process in percent and the label which holds the text "Roseindia.net" is change to with the
label text "Downloading is in process......" in green color and the button is disabled.
When the value of the progress bar is become 100% then the label text of the label is
changed with the text "Downloading completed." in red color and "Start" button is
enabled.
The label display the information about the Downloading process whether completed or
not. But here, nothing is downloading through the program. This message on the label
has been used only for showing in output of the program. For completion the process,
there are some methods and APIs are used in the program has been explained as follows:
JProgressBar:
This is the class which creates the progress bar using it's constructor JProgressBar() to
show the status of your process completion. The constructor JProgressBar() takes two
argument as parameter in which, first is the initial value of the progress bar which is
shown in the starting and another argument is the counter value by which the value of the
progress bar is incremented. Here, the value of the progress bar is incremented by 20.
setStringPainted(boolean):
This is the method of the JProgressBar class which shows the complete process in
percent on the progress bar. It takes a boolean value as a parameter. If you pass the true
then the value will be seen on the progress bar otherwise not seen.
setValue():
This is the method of the JProgressBar class which sets the value to the progress bar.
168

Timer():
This the constructor of the Timer class which starts the timer for timing. This constructor
takes two argument as parameter first is the interval (in milliseconds) of the timer and
second one is the listener object. Time is started using the start() method of the Timer
class.
Here is the code of the program:
import
import
import
import

java.awt.*;
java.awt.event.*;
javax.swing.*;
javax.swing.text.html.*;

public class SwingProgressBar{


final static int interval = 1000;
int i;
JLabel label;
JProgressBar pb;
Timer timer;
JButton button;
public SwingProgressBar() {
JFrame frame = new JFrame("Swing Progress Bar");
button = new JButton("Start");
button.addActionListener(new ButtonListener());
pb = new JProgressBar(0, 20);
pb.setValue(0);
pb.setStringPainted(true);
label = new JLabel("Roseindia.net");
JPanel panel = new JPanel();
panel.add(button);
panel.add(pb);
JPanel panel1 = new JPanel();
panel1.setLayout(new BorderLayout());
panel1.add(panel, BorderLayout.NORTH);
panel1.add(label, BorderLayout.CENTER);
panel1.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
frame.setContentPane(panel1);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create a timer.
timer = new Timer(interval, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (i == 20){
Toolkit.getDefaultToolkit().beep();
timer.stop();
button.setEnabled(true);
pb.setValue(0);

169

String str = "<html>" + "<font color=\"#FF0000\">" + "<b>" +


"Downloading completed." + "</b>" + "</font>" + "</html>";
label.setText(str);
}
i = i + 1;
pb.setValue(i);
}
});
}
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent ae) {
button.setEnabled(false);
i = 0;
String str = "<html>" + "<font color=\"#008000\">" + "<b>" +
"Downloading is in process......." + "</b>" + "</font>" + "</html>";
label.setText(str);
timer.start();
}
}

public static void main(String[] args) {


SwingProgressBar spb = new SwingProgressBar();
}

Create menus and submenus in Java

In this section, you will learn about creation of menus, submenus and Separators in Java
Swing. Menu bar contains a collection of menus. Each menu can have multiple menu
items these are called submenu. Similarly, all menus have multiples menu items. The
Separator divides the menu items in a separate groups like same types of menu Items are
divided into a individual parts. For pictorial representation, the image for the result of the
given program is given below:

170

This program shows how to create menu bar, menus, submenus and Separators. Here, all
items shows on a frame with the help of following methods and APIs:
JMenuBar:
This is the class which constructs a menu bar that contains several menus.
JMenu(String):
This is the constructor of JMenu class. This constructor constructs the new menu. It
takes the string type value which is the name label for the menu.
JMenuItem(String):
This is the constructor of JMenuItem class which constructs new menu items for the
specific menu. It takes string types value which is the label for the menu item.
JSeparator():
This is the constructor of JSeparator class which adds an extra line between menu items.
This line, only separates the menu items.
setJMenuBar():
This method is used to set the menu bar to the specified frame. It takes the object of the
JMenuBar class.
Here is the code of program:
import javax.swing.*;
public class SwingMenu{
public static void main(String[] args) {
SwingMenu s = new SwingMenu();
}
public SwingMenu(){
JFrame frame = new JFrame("Creating a JMenuBar, JMenu, JMenuItem and
seprator Component");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menubar = new JMenuBar();

171

JMenu filemenu = new JMenu("File");


filemenu.add(new JSeparator());
JMenu editmenu = new JMenu("Edit");
editmenu.add(new JSeparator());
JMenuItem fileItem1 = new JMenuItem("New");
JMenuItem fileItem2 = new JMenuItem("Open");
JMenuItem fileItem3 = new JMenuItem("Close");
fileItem3.add(new JSeparator());
JMenuItem fileItem4 = new JMenuItem("Save");
JMenuItem editItem1 = new JMenuItem("Cut");
JMenuItem editItem2 = new JMenuItem("Copy");
editItem2.add(new JSeparator());
JMenuItem editItem3 = new JMenuItem("Paste");
JMenuItem editItem4 = new JMenuItem("Insert");
filemenu.add(fileItem1);
filemenu.add(fileItem2);
filemenu.add(fileItem3);
filemenu.add(fileItem4);
editmenu.add(editItem1);
editmenu.add(editItem2);
editmenu.add(editItem3);
editmenu.add(editItem4);
menubar.add(filemenu);
menubar.add(editmenu);
frame.setJMenuBar(menubar);
frame.setSize(400,400);
frame.setVisible(true);
}

Create a Popup Menu in Java


Here, you will learn how to create a Popup menu in Java. Popup menu is the list of menu
which is displayed at that point on the frame where you press the right mouse button.
Following figure shows the popup menu when you right click on the frame:

172

This program illustrates you about the creation of the popup menu. Following methods
and APIs have been used in this program for getting popup menu:
JPopupMenu:
This is the class which constructs the popup menu using it's constructor. This class is
helpful to add the object of the JMenuItem class which creates a particular menu.
isPopupTrigger():
This is the method of the MouseEvent class of the java.awt.event.*; package. This
method returns a boolean type value either true or false. This method returns true if the
event is generated when the popup is triggered.
mouseReleased
This is the method of the FormView.MouseEventListener class which is imported from
the javax.swing.text.html.*; package. This method receives the generated mouse event
when the object is release by clicking the mouse.
getX():
This is the method of the MouseEvent class which is imported from the
java.awt.event.*; package. This method returns the integer type value which is the
position on the x-axis for the source component where you click the mouse.
getY():
This is also the method of the the MouseEvent class. This method returns the vertical
positions of the y-coordinate for the source component where you click the mouse.
show(me.getComponent(), me.getX(), me.getY()):
This is the method of JPopupMenu class which displays the popup menu where you
press the right mouse button on the specified location or positions. This positions
calculated by the getX() and getY().
getComponent():
This is the method of the ComponentEvent class of the java.awt.event.*; package. This
method returns the source component of the generated event.
Here is the code of program:
import javax.swing.*;
import java.awt.event.*;
public class PopUpMenu{
JPopupMenu Pmenu;
JMenuItem menuItem;
public static void main(String[] args) {
PopUpMenu p = new PopUpMenu();
}
public PopUpMenu(){

173

JFrame frame = new JFrame("Creating a Popup Menu");


frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Pmenu = new JPopupMenu();
menuItem = new JMenuItem("Cut");
Pmenu.add(menuItem);
menuItem = new JMenuItem("Copy");
Pmenu.add(menuItem);
menuItem = new JMenuItem("Paste");
Pmenu.add(menuItem);
menuItem = new JMenuItem("Delete");
Pmenu.add(menuItem);
menuItem = new JMenuItem("Undo");
Pmenu.add(menuItem);
menuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){}
});
frame.addMouseListener(new MouseAdapter(){
public void mouseReleased(MouseEvent Me){
if(Me.isPopupTrigger()){
Pmenu.show(Me.getComponent(), Me.getX(), Me.getY());
}
}
});
frame.setSize(400,400);
frame.setVisible(true);
}

Creating a JTabbedPane Container in Java Swing


In this section, you will learn how to create the JTabbedPane container in Java Swing.
The example for illustration is given in which, all the things related to the creation of
JTabbedPane container have been illustrated in efficient manner.
This program has used various tools of swing to implement the JTabbed component of
Java. The following figure shows the JTabbedPane component of Java Swing:

174

These are explained as follows:


JTabbedPane:
This is the class of javax.swing.*; package which creates the JTabbedPane component of
Java Swing which contains separate button for the separate tab. You can also container
component with the specific tab.
add():
This is the method of JTabbedPane class which is used to add container component to
the JTabbedPane component of Java Swing. This method takes different-different types
of arguments but in this program this method has taken two argument, first is the title for
the tab and another is the component name which is specified for a particular tab to show
for that.
Here is the code of the program:
import javax.swing.*;
import java.awt.*;
public class CreateTabbedPane{
public static void main(String[] args){
JFrame frame = new JFrame("Tabbed Pane Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTabbedPane tab = new JTabbedPane();
frame.add(tab, BorderLayout.CENTER);
JButton button = new JButton("1");
tab.add("Tab 1", button);
button = new JButton("2");
tab.add("Tab 2", button);
frame.setSize(400,400);
frame.setVisible(true);
}
}

AWT in Java
-

AWT stands for Abstract Windowing Toolkit.


It contains all classes to write the program that interface between the user and
different windowing toolkits.

AWT package is used to develop user interface objects like buttons, checkboxes,
radio buttons and menus etc.

This package provides following interfaces and classes as follows:

Interfaces and Descriptions of AWT Package:


175

ActionEvent
Adjustable

This interface is used for handling events.


This interface takes numeric value to adjust
within the bounded range.

CompositeContext

This interface allows the existence of several


context simultaneously for a single composite
object. It handles the state of the operations.
This interface is used for maintaining zero or
more selection for items from the item list.
The KeyEventDispatcher implements the current
KeyboardFocusManager and it receives
KeyEvents before despatching their targets.
This interface also implements the current
KeyboardFocusManager. The
KeyboardFocusManager receives the KeyEvents
after that dispatching their targets.
It defines the interface class and it has layout
containers.
This is the interface extends from the
LayoutManager and is subinterface of that.
This interface has all menu containers.
This interface is used to color pattern. It used for
the Graphics2D operations.
This interface also used the color pattern. It
provides an important color for the Graphics2D
operation and uses the ColorModel.
This interface provides print a graphics context
for a page.
This interface used for represent the geometric
shapes.

ItemSelectable
KeyEventDispatcher

KeyEventPostProcessor

LayoutManager
LayoutManager2
MenuContainer
Paint
PaintContext

PaintGraphics
Shape

Classes and Descriptions of AWT Package:


AlphaComposite

This class implements the


basic alpha compositing rules.
It combines the source and
destination pixels to achieve
transparency effects to
graphics and images.
This is a supper class of all
AWT Events.

AWTEvent

176

AWTEventMulticaster

This class implements threadsafe multi-cast event and it is


despatching for the AWT
event. The AWT events
defined in the java.awt.event
package.
This class used to key action
on the keyboard or equivalent
input devices.
This class uses for the AWT
permissions.
This class defines the basic
set of rendering attributes for
using outlines of graphics.
This class uses to arranging
the components. It has five
components such as: east,
west, north, south and the
center.
This class has properties of
buffers.
This class has a type-safe
enumeration of buffer. It
contains after page-flipping.
This class used to create a
label button
It represents the blank
rectanglular area on screen. It
can draw or trap input events
from the user.
It is a layout manager for a
comtainer.
It is a graphical component. It
has two states. True state that
means "on" or false sate that
means "off".
This class to be used together
multiple checkbox buttons.
This class represents the
checkbox and also include the
menu.
This class represents pop-up
menu to user's choice.

AWTKeyStroke

AWTPermission
BasicStroke

BorderLayout

BufferCapabilities
BufferCapabilities.FlipContents

Button
Convas

CardLayout
Chaeckbox

CheckboxGroup
CheckboxMenuItem

Choice

177

Color

This class has colors. The


default color is RGB color.
Color library specify the all
color, it identified by
ColorSpace.
This is a graphical
representation to interacted by
user. It displays on the
screen.
This class encapsulates the
language-sensitive
orientation. It also used the
order the element of
component or text..
A generic AWT container
object has other AWT
components.
It determines the traversal
order based on the order of
child components in a
container.
This class represents the
bitmap representation of the
mouse cursor.
This class determines the
traversal order on the order of
child components of
container.
This class used for handle the
AWT applecations.
This is a top label window. It
has title and border. It can be
used for taking a some input
of users.
This class describe the height
and width of a component in a
single object.
This class encapsulates the bit
depth, height, width and
refresh rate of a
GraphicsDevice.
This class available only for
the backwards compatilibility.

Component

ComponentOritentation

Container

ContainerOrderFocusTraversalPolicy

Cursor

DefultFocusTraversalPolicy

DefultKeyboardFocusManager
Dialog

Dimension

DisplayMode

Event

178

EventQueue

It is a platform independent
class. It has both classes
underlying peer class and
trusted application class.
This class displays dialog
window. Here user can be
select the file.
This class arrange the
components and flow the left
to right. It uses to write lines
in a paragraph.
This class defines the order in
which components traverse
particular focus cycle root.
This class defines fonts and it
uses render text that is
visible.
This class defines font matrix
object.. It encapsulate the
information and rendering the
paritcular fonts.
This class defines top-level
window and it designs the any
area of border.
With the help of
GradientPaint you fill any
shapes.
This class uses to drawing all
types of graphics such as:
oval, rectangle etc.
This class controls all
geometry, coordinate
transformation, color
management etc. It extends
form the Graphics class.
This class contains a valid
GraphicConfiguration.
This class describes the
characteristics of graphics
destination such as printer and
monitor.
This class describes the
graphics devices and it

FileDialog

FlowLayout

FocusTraversalPolicy

Font

FontMetrics

Frame

GradientPaint

Graphics

Graphics2D

GraphicsConfigTemplate
GraphicsConfiguration

GraphicsDevice

179

GraphicsEnvironment

GridBagConstraints

GridBagLayout

GridLayout

Image
ImageCompabilities
Insets

JobAttributes
JonAttributes.DefaultSelectionType

JobAttributes.DestinatinType

JobAttributes.DialogType

JobAttributes.MultipleDocumentHandlingType

180

available particular graphics


environment.
This class is a collection of
GraphicsDevices object and
Font objects. The
GraphicsDevices objects are
screen, images and printers
etc.
This class specify the
constraint for components by
using the GrideBagLayout
class.
This class uses the layout
manager and uses the
vertically and horizontally
components.
This class is a layout
manager. It has rectangular
grid components.
This class is a supper class of
all graphical images.
It has compabilities and
properties of images.
This class represents all types
of border's container. It
includes borders, blank space
and titles.
This class control the print
job.
It has default selection states
and extends from the
java.awt.AttributeValue
package.
It possible for the job
destinations and extends form
the java.awt.AttributeValue
package.
It displays the user dialog and
extends from the
java.awt.AttributeValue
package.
This class handles the
multiple copy states and

JobAttributes.SidesType

KeyboardFocusManager

Label
List

MediaTracker

Menu

MenuBar

MenuComponent
MenuItem
MenuShortcut

PageAttributes
PageAttributes.ColorType

PageAttributes.MediaType

PageAttributes.OrientationRequestedType

181

extends form the


java.awt.AttributeValue
package.
It uses multi-page impositions
and extends from the
java.awt.AttributeValue
package.
This class manage the current
focus owner, active and
focused windows
It is a component which
contains the text in container.
This component uses by the
uses and it choose the list of
item.
This class has status of a
number of media objects. It is
a utility class.
It has pull-down menu
components that displayed as
like menu bar.
This class has the concept of
menu bar and it also bounded
into a frame.
This is supper class of all
menu related components.
This is a supper class and it
represents the item of menu.
This class represents the
handling MenuItem through
help of keyboard .
It controls the output of the
printed page.
It handles the color states and
extends form the
java.awt.AttributeValue
package.
It handles the paper size and
extends from the
java.awt.AttributeValue
package.
It handles the possible
orientations and extends from

the java.awt.AttributeValue
package.
It handles the origins and
extends from the
java.awt.AttributeValue
package.
It handles the print qualities
and extends from the
java.awt.AttributeValue
package.
This is a simplest container
class. It includes components
and other panels. It extends
Container and implements to
Accessible.
The point represents the
location of coordinate (x, y)
space. It extends Point2D.
It has two dimensional region
and it bounded by the
multiple number of lines.
It extends the Menu and
specify the positions of
components.
This class executes a print job
and extends from the Object.
A rectangle object has length
and width and it also specify
an area in a coordinate space.
It extends Rectangle2D.
This class contains rendering
hints by using the Graphics2D
class.
This class used to control the
randering and imaging
pipelines.
This class used to generate
the native system input events
and it automatically test the
java platform
implementations.
This class provide the user
interface components and also

PageAttributes.OriginType

PageAttributes.PrintQualityType

Panel

Point

Polygon

PopupMenu

PrintJob
Rectangle

RenderingHints

RenderingHints.Key

Robot

Scrollbar

182

include the scroll bar. Which


implements the Adjustable
interface.
It includes the horizontal and
vertical scrolling for a single
child components. The
horizontal and vertical state
represented by the
ScrollPaneAdjustable objects.
This class represents the state
of horizontal and vertical
scrollbar of ScrollPane.
This class represents the
system's color through the
symbolic representation color.
The value depends on the
actual value of RGB.
It displays multi line text.
This is a supper class of any
component. It allows to
editing the some text.
It has text component and It
allows to editing a single line
of text.
It provides a way to fill a
shape with a texture and
specify by the BufferedImage.
This is a supper class of all
Abstract Windowing Toolkit.
It is a top-level window. It has
not borders and menubar. It
capable for generating the
window events like:
WindowOpend,
WindowClosed.

ScrollPane

ScrollPaneAdjustable

SystemColor

TextArea
TextComponent

TextField

TexturePaint

Toolkit
Window

Java AWT Components


Introduction
-

Following some components of Java AWT are explained :

1. - Labels : This is the simplest component of Java Abstract Window Toolkit.

183

This component is generally used to show the text or string in your application and
label never perform any type of action.
Label label_name = new Label ("This is the label text.");
-

Label label_name = new Label ("This is the label text.", Label.CENTER);


Justification of label can be left, right or centered. Above declaration used the
center justification of the label using the Label.CENTER.

2. Buttons : Used to trigger actions and other events required for your application.
The syntax of defining the button is as follows :
-

Button button_name = new Button ("This is the label of the button.");


Changing the Button's label or get the label's text by using the
Button.setLabel(String) and Button.getLabel() method.
Buttons are added to the it's container using the add (button_name) method.

3. Check Boxes : The syntax of the definition of Checkbox is as follows :


-

CheckBox checkbox_name = new Checkbox ("Optional check box 1", false);


Above code constructs the unchecked Checkbox by passing the boolean valued
argument false with the Checkbox label through the Checkbox() constructor.
Defined Checkbox is added to it's container using add (checkbox_name) method.
get the checkbox's label using the setLabel (String) and getLabel() method.
We can also set and get the state of the checkbox using the setState(boolean) and
getState() method provided by the Checkbox class.
Radio Button : This is used as a group of checkboxes which group name is same.
Only one Checkbox from a Checkbox Group can be selected at a time.
Syntax for creating radio buttons is as follows :

CheckboxGroup chkgp = new CheckboxGroup();


add (new Checkbox ("One", chkgp, false);
add (new Checkbox ("Two", chkgp, false);
-

In the above code we are making three check boxes with the label "One", "Two"

and "Three". If you mention more than one true valued for checkboxes then your
program takes the last true and show the last check box as checked.
4. Text Area: This is the text container component of Java AWT package. The Text
Area contains plain text. TextArea can be declared as follows:
- TextArea txtArea_name = new TextArea();

184

Make the Text Area editable or not using the setEditable (boolean) method.
Pass the boolean valued argument false then the text area will be non-editable
otherwise it will be editable.
The text area is by default in editable mode.
Text are set in the text area using the setText(string) method of the TextArea
class.

5. Text Field: This component contains single line and limited text information.
This is declared as follows :
TextField txtfield = new TextField(20);

import java.awt.*;
import java.applet.Applet;
public class MyButton extends Applet {
public void init() {
Button button = new Button("SUBMIT");
add(button);
}
}

Here is the HTML code:


<HTML>
<BODY>
<APPLET ALIGN="CENTER" CODE="MyButton" WIDTH="400"
HEIGHT="200"></APPLET>
</BODY>
</HTML>

Scrollbar
-

A scrollbar is represented by a "slider" widget.


The characteristics of it are specified by integer values which are being set at the
time of scrollbar construction.

Both the types of Sliders are available i.e. horizontal and vertical.

The subtraction of scrollbar width from the maximum setting gives the maximum
value of the Scrollbar.

185

In the program code, '0' is the <<<<<<< scrollbar.shtml initial value of the
scrollbar, '8' is the width of the scrollbar.

import java.awt.*;
import java.applet.Applet;
public class ScrollbarDemo extends Applet {
public void init() {
Scrollbar sb = new Scrollbar
(Scrollbar.VERTICAL, 0, 8, -100, 100);
add(sb);
}
}

TextField
-

A scrollable text display object with one row of characters is known as the
TextField.

import java.awt.*;
import java.applet.Applet;
public class TextFieldDemo extends Applet{
public void init(){
TextField tf = new TextField("Type in the box");
add(tf);
}
}

Common Component Methods


The common methods of AWT components are as follow:
1. getBounds() - This method is used to get the current bounding Rectangle of
component.
The
usage
of
the
method
is
shown
below.
Rectangle r = someComponent.getBounds();
int height = r.height;
int width = r.width;
2. getSize() - This method is used to get the current size of component, as a
Dimension.
Dimension d = someComponent.getSize();

186

int height = d.height;


int width = d.width;
Again, it is always advisable to use getWidth() and getHeight() methods to directly
access the width and height while working on Java 2 platform.
int height = someComponent.getHeight();
int width = someComponent.getWidth();
5. setBackground(Color)/setForeground(Color) - This method is used to change the
background/foreground colors of the component.
6. setFont(Font) - This method is used to change the font of text within a component.
7.setVisible(boolean) - This method is used for the visibility state of the component. The
component appears on the screen if setVisible() is set to true and if its set to false then
the component will not appear on the screen.
8. setEnabled(boolean) - This method is used to toggle the state of the component. The
component will appear if set to true and it will also react to the user. if set to false then
the component will not appear hence no user interaction will be there.
Containers
-

Container is a component that can be nested.


There is a Panel which is used for running the programs.

This Panel is known as Class Applet which is used for running the programs
within the Browser.

Common Container Methods


-

All the subclasses of the Container class inherit the behavior of more than 50
common methods of Container.
These subclasses of the container mostly override the method of component.

Some of the methods of container which are most widely used are as follow:

getComponents();
add();
getComponentCount();
getComponent(int);

187

ScrollPane
-

The ScrollPane container provides an automatic scrolling of any larger


component.

The example below shows the Scrollpane.


import java.awt.*;
import java.applet.*;
class Scrollpane extends Component {
private Image image;
public Scrollpane(Image m) {
image = m;
}
public void paint(Graphics g) {
if (image != null)
g.drawImage(image, 0, 0, this);
}
}
public class ScrollingImageDemo extends Applet {
public void init() {
setLayout(new BorderLayout());
ScrollPane SC = new ScrollPane(ScrollPane.SCROLLBARS_ALWAYS);
Image mg = getImage(getCodeBase(), "cute-puppy.gif");
SC.add(new Scrollpane(mg));
add(SC, BorderLayout.CENTER);
}
}

Different types of event in Java AWT


Introduction
-

There are many types of events that are generated by your AWT Application.
These events are used to make the application more effective and efficient.
Generally, there are twelve types of event are used in Java AWT. These are as
follows :

1.
2.
3.
4.
5.
6.
7.
8.

ActionEvent
AdjustmentEvent
ComponentEvent
ContainerEvent
FocusEvent
InputEvent
ItemEvent
KeyEvent

188

9. MouseEvent
10. PaintEvent
11. TextEvent
12. WindowEvent
These are twelve mentioned events are explained as follows :
1. ActionEvent:
-

This is the ActionEvent class extends from the AWTEvent class.


It indicates the component-defined events occurred i.e. the event generated by the
component like Button, Checkboxes etc.
The generated event is passed to every EventListener objects that receives such
types of events using the addActionListener() method of the object.

2. AdjustmentEvent:
-

This is the AdjustmentEvent class extends from the AWTEvent class. When the
Adjustable Value is changed then the event is generated.

3. ComponentEvent:
-

ComponentEvent class also extends from the AWTEvent class.


This class creates the low-level event which indicates if the object moved,
changed and it's states (visibility of the object). This class only performs the
notification about the state of the object.

3. ContainerEvent:
-

The ContainerEvent class extends from the ComponentEvent class.


This is a low-level event which is generated when container's contents changes
because of addition or removal of a components.

4. FocusEvent:
-

The FocusEvent class also extends from the ComponentEvent class.


This class indicates about the focus where the focus has gained or lost by the
object.
The generated event is passed to every objects that is registered to receive such
type of events using the addFocusListener() method of the object.

5. InputEvent:
-

The InputEvent class also extends from the ComponentEvent class.


This event class handles all the component-level input events. This class acts as a
root class for all component-level input events.

189

6. ItemEvent:
-

The ItemEvent class extends from the AWTEvent class.


The ItemEvent class handles all the indication about the selection of the object i.e.
whether selected or not. The generated event is passed to every ItemListener
objects that is registered to receive such types of event using the
addItemListener() method of the object.

7. KeyEvent:
-

KeyEvent class extends from the InputEvent class.


The KeyEvent class handles all the indication related to the key operation in the
application if you press any key for any purposes of the object then the generated
event gives the information about the pressed key.
This type of events check whether the pressed key left key or right key, 'A' or 'a'
etc.

8. MouseEvent:
-

MouseEvent class also extends from the InputEvent class.


The MouseEvent class handle all events generated during the mouse operation for
the object.
That contains the information whether mouse is clicked or not if clicked then
checks the pressed key is left or right.

9. PaintEvent:
-

PaintEvent class also extends from the ComponentEvent class.


The PaintEvent class only ensures that the paint() or update() are serialized along
with the other events delivered from the event queue.

10. TextEvent:
-

TextEvent class extends from the AWTEvent class.


TextEvent is generated when the text of the object is changed.
The generated events are passed to every TextListener object which is registered
to receive such type of events using the addTextListener() method of the object.

11. WindowEvent :
-

WindowEvent class extends from the ComponentEvent class.


If the window or the frame of your application is changed (Opened, closed,
activated, deactivated or any other events are generated), WindowEvent is
generated.

190

Events
-

Java awt. Events are the integral part of the java platform.
For any event to occur, the objects registers themselves as listeners.

No event takes place if there is no listener i.e. nothing happens when an event
takes place if there is no listener.

No matter how many listeners there are, each and every listener is capable of
processing an event.

ActionListener can be implemented by any Class including Applet.

call AWTEvent.consume() method whenever you don't want an event to be


processed further.

The step by step procedure of Event handling is as follow:

1. When anything interesting happens then the subclasses of AWTEvent are


generated by the component.
2. Any class can act like a Listener class permitted by the Event sources. For
example, addActionListener() method is used for any action to be performed,
where Action is the event type. There is another method by which you can
remove the listener class which is removeXXXListener() method, where XXX
is the event type.
3. A listener type has to be implemented for an event handling such as
ActionListener.
4. There are three methods which are required to be implemented for Key events and
to register them i.e. one for key release, key typed and one for key press. There
are some special classes as well which are known as adapters that are used to
implement the listener interfaces and stub out all the methods. these adapter
classes can be sub classed and and can override the necessary method.
AWTEvent
-

Most of the times every event-type has Listener interface as Events subclass the
AWTEvent class.
PaintEvent and InputEvent don't have the Listener interface because only the
paint() method can be overriden with PaintEvent etc.

Low-level Events

191

A low-level input or window operation is represented by the Low-level events.


Types of Low-level events are mouse movement, window opening, a key press
etc.
The different type of low-level events and operations that generate each event
are show below in the form of a table.

FocusEvent

ContainerEvent

Used for Getting/losing focus.


Used for entering, exiting, clicking, dragging, moving,
pressing, or releasing.
Used for Adding/removing component.

KeyEvent

Used for releasing, pressing, or typing (both) a key.

WindowEvent

Used for opening, deactivating,


deiconifying, really closed.

ComponentEvent

Used for moving, resizing, hiding, showing.

MouseEvent

closing,

Iconifying,

Semantic Events
-

The interaction with GUI component is represented by the Semantic events like
changing the text of a text field, selecting a button etc.

The different events generated by different components is shown below.

ItemEvent

Used for state changed.

ActionEvent

Used for do the command.

TextEvent

Used for text changed.

AdjustmentEvent

Used for value adjusted.

Event Sources
-

If a component is an event source for something then the same happens with its

subclasses.
The different event sources are represented by the following table.
Low-Level Events

192

Window
Container

Component

WindowListener
ContainerListener
ComponentListener
FocusListener
KeyListener
MouseListener
MouseMotionListener

Semantic Events
Scrollbar
TextArea
TextField
Button
List
MenuItem
TextField
Choice
Checkbox
Checkbox
CheckboxMenuItem
List

AdjustmentListener
TextListener

ActionListener

ItemListener

Event Listeners
-

Every listener interface has at least one event type.

The Listener interfaces and their methods are as follow:


Interface

WindowListener

ActionListener

Methods
windowActivated(WindowEvent e)
windowDeiconified(WindowEvent e)
windowOpened(WindowEvent e)
windowClosed(WindowEvent e)
windowClosing(WindowEvent e)
windowIconified(WindowEvent e)
windowDeactivated(WindowEvent e)
actionPerformed(ActionEvent e)

193

adjustmentValueChanged(AdjustmentEvent
e)
mouseClicked(MouseEvent e)
mouseEntered(MouseEvent e)
MouseListener
mouseExited(MouseEvent e)
mousePressed(MouseEvent e)
mouseReleased(MouseEvent e)
focusGained(FocusEvent e)
FocusListener
focusLost(FocusEvent e)
ItemListener
itemStateChanged(ItemEvent e)
KeyListener
keyReleased(KeyEvent e)
keyTyped(KeyEvent e)
keyPressed(KeyEvent e)
componentHidden(ComponentEvent e)
componentMoved(ComponentEvent e)
ComponentListener
componentShown(ComponentEvent e)
componentResized(ComponentEvent e)
MouseMotionListener mouseMoved(MouseEvent e)
mouseDragged(MouseEvent e)
TextListener
textValueChanged(TextEvent e)
ContainerListen er
componentAdded(ContainerEvent e)
componentRemoved(ContainerEvent e)
AdjustmentListener

Event Adapters
-

There are some event listeners that have multiple methods to implement.
That is some of the listener interfaces contain more than one method.

For instance, the MouseListener interface contains five methods such as


mouseClicked, mousePressed, mouseReleased etc. If you want to use only one
method out of these then also you will have to implement all of them.

Thus, the methods which you do not want to care about can have empty bodies.
To avoid such thing, we have adapter class.

Adapter classes help us in avoiding the implementation of the empty method


bodies.

Generally an adapter class is there for each listener interface having more than
one method.

194

For instance, the MouseAdapter class implements the MouseListener interface.


An adapter class can be used by creating a subclass of it and then overriding
the methods which are of use only.

Hence avoiding the implementation of all the methods of the listener interface.
The following example shows the implementation of a listener interface directly.

public class MyClass implements MouseListener {


...
someObject.addMouseListener(this);
...
/* Empty method definition. */
public void mouseEntered(MouseEvent e) {
}
/* Empty method definition. */
ublic void mouseExited(MouseEvent e) {
}
/* Empty method definition. */
public void mousePressed(MouseEvent e) {
}
}
}
Button Pressing Example
The following program demonstrates the event generated by each button.
import java.awt.*;
import java.awt.event.*;
public class ButtonPressDemo {
public static void main(String[] args){
Button b;
ActionListener a = new MyActionListener();
Frame f = new Frame("Java Applet");

195

f.add(b = new Button("Bonjour"), BorderLayout.NORTH);


b.setActionCommand("Good Morning");
b.addActionListener(a);
f.add(b = new Button("Good Day"), BorderLayout.CENTER);
b.addActionListener(a);
f.add(b = new Button("Aurevoir"), BorderLayout.SOUTH);
b.setActionCommand("Exit");
b.addActionListener(a);
f.pack();
f.show();

}
class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent ae) {
String s = ae.getActionCommand();
if (s.equals("Exit")) {
System.exit(0);
}
else if (s.equals("Bonjour")) {
System.out.println("Good Morning");
}
else {
System.out.println(s + " clicked");
}
}
}

GUI-based Applications
-

In this section you will learn about how to create a window for your application.
Define a subclass of Frame to create a window for your application.

The Frame consists of a Window with a title, menubar, and border.

One point to remember here is that Applications respond to events in the same
way as applets do.

import java.awt.*;
import java.awt.event.*;
public class ApplicationWindow extends Frame{
public ApplicationWindow(){
super("ApplicationWindow");
setSize(200, 200);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
setVisible(false); dispose();
System.exit(0);
}
});

196

public static void main(String[] args){


ApplicationWindow aw = new ApplicationWindow();
aw.setVisible(true);
}

Menus
-

As a name indicates a Menu consists of Menu objects.


These Menu objects comprise of MenuItem objects which can be selected by the
user with a click of a mouse.

A MenuItem may be a String, checkbox, separator, menu etc.

Following are the steps to add menus to any Frame:


1. You need to create a MenuBar first with the help of the following method.
MenuBar mb = new MenuBar();
2.

Then you need to create a Menu using Menu m = new Menu("File");.

3. Now the MenuItem options can be added to the Menu from top to bottom, using
the following methods.
mi.add(new MenuItem("Open"));
mi.add(new CheckboxMenuItem("Type here"));
4.

Now you can add the Menu to the MenuBar from left to right using mi.add(m);.

5. Finally, you need to add the MenuBar to the Frame by calling the setMenuBar()
method.
The program code given below, creates an application window with a menu bar.
mport java.awt.*;
import java.awt.event.*;
public class MainWindow extends Frame {
public MainWindow() {
super("Menu Window");
setSize(400, 400);

197

FileMenu fileMenu = new FileMenu(this);


HelpMenu helpMenu = new HelpMenu(this);
MenuBar mb = new MenuBar();
mb.add(fileMenu);
mb.add(helpMenu);
setMenuBar(mb);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
exit();
}
});
}
public void exit() {
setVisible(false);
dispose();
System.exit(0);
}
public static void main(String args[]) {
MainWindow w = new MainWindow();
w.setVisible(true);
}
}
class FileMenu extends Menu implements ActionListener {
MainWindow mw;
public FileMenu(MainWindow m) {
super("File");
mw = m;
MenuItem mi;
add(mi = new MenuItem("Open"));
mi.addActionListener(this);
add(mi = new MenuItem("Close"));
mi.addActionListener(this);
add(mi = new MenuItem("Exit"));
mi.addActionListener(this);
}

public void actionPerformed(ActionEvent e) {


String item = e.getActionCommand();
if (item.equals("Exit"))
mw.exit();
else
System.out.println("Selected FileMenu " + item);
}

class HelpMenu extends Menu implements ActionListener {


MainWindow mw;
public HelpMenu(MainWindow m) {
super("Help");
mw = m;
MenuItem mi;
add(mi = new MenuItem("Basics"));
mi.addActionListener(this);

198

add(mi = new MenuItem("Advanced"));


mi.addActionListener(this);
addSeparator();
add(mi = new CheckboxMenuItem("Manual"));
mi.addActionListener(this);

Menu subMenu = new Menu("Miscellaneous");


subMenu.add(mi = new MenuItem("Help"));
mi.addActionListener(this);
subMenu.add(mi = new MenuItem("Other Option"));
mi.addActionListener(this);
add(subMenu);

public void actionPerformed(ActionEvent e) {


String item = e.getActionCommand();
if (item.equals("Basics"))
System.out.println("Basics");
else if (item.equals("Help"))
System.out.println("Help");
}
}

Pop-up Menus
-

A PopupMenu is similar to a Menu as it contains MenuItem objects.


The Pop-up Menu can be popped over any component while generating the
appropriate mouse event rather than letting it appear at the top of a Frame.

Menu class can only be added to a Frame and not to the Applet.

To add it to the Applet you need to use the Swing component set.

import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
public class PopupMenuDemo extends Applet{
Button b;
TextField msg;
PopupAppMenu m;
public PopupMenuDemo(){
setSize(200, 200);
b = new Button("Pop-up Menu");
add(b, BorderLayout.NORTH);
msg = new TextField();
msg.setEditable(false);
add(msg, BorderLayout.SOUTH);
m = new PopupAppMenu(this);
add(m);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){

199

m.show(b, 20, 20);


}

});
addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
if (e.isPopupTrigger())
m.show(e.getComponent(), e.getX(), e.getY());
}
public void mouseReleased(MouseEvent e){
if (e.isPopupTrigger())
m.show(e.getComponent(), e.getX(), e.getY());
}
});
}
public static void main(String[] args){
PopupMenuDemo app = new PopupMenuDemo();
app.setVisible(true);
}
}
class PopupAppMenu extends PopupMenu
implements ActionListener{
PopupMenuDemo ref;
public PopupAppMenu(PopupMenuDemo ref){
super("File");
this.ref = ref;
MenuItem mi;
add(mi = new MenuItem("Copy"));
mi.addActionListener(this);
add(mi = new MenuItem("Open"));
mi.addActionListener(this);
add(mi = new MenuItem("Cut"));
mi.addActionListener(this);
add(mi = new MenuItem("Paste"));
mi.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
String item = e.getActionCommand();
ref.msg.setText("Option Selected: " + item);
}
}

Create a Frame in Java


Introduction
-

In the Java AWT, top-level windows are represented by the Frame class. Java
supports the look and feel and decoration for the frame.
The most common method of creating a frame is by using single argument
constructor of the Frame class that contains the single string argument which is
the title of the window or frame.

200

Then you can add user interface by constructing and adding different components
to the container one by one.

The center alignment of the label has been defined by the Label.CENTER. The
frame initially invisible, so after creating the frame it need to visualize the frame
by setVisible(true) method.

add(lbl):
- This method has been used to add the label to the frame. Method add() adds a
component to it's container.
setSize (width, height):
-

This is the method of the Frame class that sets the size of the frame or window.
This method takes two arguments width (int), height (int).

setVisible(boolean):
- This is also a method of the Frame class sets the visibility of the frame. The frame will
be invisible if you pass the boolean value false otherwise frame will be visible.
import java.awt.*;
public class AwtFrame{
public static void main(String[] args){
Frame frm = new Frame("Java AWT Frame");
Label lbl = new Label("Welcome to Tutorial.",Label.CENTER);
frm.add(lbl);
frm.setSize(400,400);
frm.setVisible(true);
}
}

Setting the Icon for the frame in Java


Introduction
-

Toolkit class has been used to get the image and then the image is used to display
as frame icon. Toolkit class is used to bind the various components to particular
native toolkit implementations.

getDefaultToolkit():
- This method returns the default toolkit.
getImage(url or filename):
- This method retrieves the pixels data of the image which can be either in format of .gif,
.jpeg or .png. If the security manager installed then the getImage() method first check

201

whether the specified file name has the permission to use and then retrieves the image in
pixels format.
Import

java.awt.*;

public class AwtSetIconOfFrame{


public static void main(String[] args){
Frame frame = new Frame("Icon setting for the Awt Frame");
Image icon = Toolkit.getDefaultToolkit().getImage("icon_confused.gif");
Label lbl = new Label("Welcome to Tutorial.",Label.CENTER);
frame.add(lbl);
frame.setSize(400,400);
frame.setIconImage(icon);
frame.setVisible(true);
}
}

Setting the close button operation for the frame in Java


Introduction
-

If you click on the close button of the frame or window that will be cancelled
automatically. The close button of the frame has to be set for the desired operation
(i.e. closing the frame).
This is done using the addWindowListener() method of the Frame class which
passes the new instance of the WindowAdapter class that uses the
windowClosing() method for receiving the WindowEvent and close the frame or
window.

addWindowListener()
:
- This is the addWindowListener() method which adds the window listener to receive the
window event from the window. This method passes the window listener.
WindowAdapter()
:
- This is the constructor of the WindowAdapter class of the java.awt.event.*; package.
This is an abstract class used for receiving window events.
windowClosing()
:
- This is the windowClosing() method of the WindowAdapter class invoked when the
frame is attempted to close from the window's system menu or close button. This method
receives the WindowEvent object.
Import java.awt.*;
import java.awt.event.*;
public class AwtCloseButtonEvent{
public static void main(String[] args){
Frame frame = new Frame("Close Operation Frame");

202

Label lbl = new Label("Welcom in Tutorial",Label.CENTER);


frame.add(lbl);
frame.setSize(400,400);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
}

Making a Frame Non Resizable in Java


import java.awt.*;
import java.awt.event.*;
public class AwtFrameNonResizable{
public static void main(String[] args){
Frame frame = new Frame("Non Resizable Frame");
Image icon = Toolkit.getDefaultToolkit().getImage("icon_confused.gif");
frame.setIconImage(icon);
Label lbl = new Label("Welcome to Tutorial.",Label.CENTER);
frame.add(lbl);
frame.setResizable(false);
frame.setSize(400,400);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
Frame frame = (Frame)we.getSource();
frame.dispose();
}
});
}
}

Create a Container in Java awt


Introduction
-

Container contains several control or tools for develop your application. All the
controls used in your application are the container for one another.
Ex: Three buttons have been added to the panel.

The panel and a text area added to the frame.

The position for the panel on the frame has been specified south of the frame by
using BorderLayout.SOUTH since the position of the text area has been
specified the center of the frame using BorderLayout.CENTER. Here, the add()

203

method has been used for both operations (add buttons to the panel and add panel
and text area to the frame).
BorderLayout
:
- BorderLayout is the class of the java.awt.*; package which is used to arranging and
resizing it's components to fit in five rigions : north, south, east, west and center.
-

Each region may contain only one component. All regions are represented by the
NORTH, SOUTH, EAST, WEST and CENTER constants of the BorderLayout
class.

import java.awt.*;
import java.awt.event.*;
public class CreateContainer{
public static void main(String[] args){
Panel panel = new Panel();
panel.add(new Button("Button 1"));
panel.add(new Button("Button 2"));
panel.add(new Button("Button 3"));
Frame frame = new Frame("Container Frame");
TextArea txtArea = new TextArea();
frame.add(txtArea, BorderLayout.CENTER);
frame.add(panel, BorderLayout.SOUTH);
frame.setSize(400,400);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
}
}

Handling Focus Changes in Java


Introduction
-

The generated focus events are performed by the FocusListener of the object used
in your application using the addFocusListener() method.
The generated event (FocusEvent) is passed to every FocusListener objects that
receives such types of events using the addFocusListener() method of the object.
The addFocusListener() method is takes the instance of MyFcousListener class.

import java.awt.*;
import java.awt.event.*;

204

public class FocusChange{


Label label;
public static void main(String[] args){
FocusChange fc = new FocusChange();
}
public FocusChange(){
Frame frame = new Frame("Welcome");
Panel panel = new Panel();
Button yes = new Button("Yes");
Button no = new Button("No");
Button cancel = new Button("Cancel");
yes.addFocusListener(new MyFocusListener());
no.addFocusListener(new MyFocusListener());
cancel.addFocusListener(new MyFocusListener());
panel.add(yes);
panel.add(no);
panel.add(cancel);
frame.add(panel,BorderLayout.NORTH);
label = new Label();
frame.add(label,BorderLayout.CENTER);
frame.setSize(400,400);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
}
public class MyFocusListener extends FocusAdapter{
public void focusGained(FocusEvent fe){
Button bt = (Button)fe.getSource();
String str = bt.getLabel();
label.setText(str);
}
}
}

Handling Mouse Clicks in Java


import java.awt.*;
import java.awt.event.*;
public class MouseClick {
Label lbl;
public static void main(String[] args) {
MouseClick MC = new MouseClick();
}
public MouseClick(){
Frame f = new Frame("Checking the mouse click");
Panel p = new Panel();
Button button = new Button("Click Me");
button.addMouseListener(new MyMouseListener());

205

p.add(button, BorderLayout.NORTH);
f.add(p,BorderLayout.NORTH);
lbl = new Label("Roseindia.net");
f.add(lbl, BorderLayout.CENTER);
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
f.setSize(400,400);
f.setVisible(true);
}

public class MyMouseListener extends MouseAdapter{


public void mouseClicked(MouseEvent me){
String str = lbl.getText();
if (str.equals("Roseindia.net")){
lbl.setText("You have clicke the button.");
}
else if (str.equals("You have clicke the button.")){
lbl.setText("Roseindia.net");
}
}
}

Event handling in Java AWT


Introduction
-

This example shows you how to handle events in java.awt.*; package. AwtEvent
is the main class of the program which extends from the Frame class implements
the ActionListener interface.
This program starts to run from the main method in which the object for the
AwtEvent class has been created.

The constructor of the AwtEvent class creates two buttons with adding the
addActionListener() method to it.

The constructor also initializes a label with text "welcome".

When you click on the button then the actionPerformed() method is called which
receives the generated event.

This method shows the text of the source of the event on the label.

Import java.awt.*;
import java.awt.event.*;
public class AwtEvent extends Frame implements ActionListener{

206

Label lbl;
public static void main(String argv[]){
AwtEvent t = new AwtEvent();
}
public AwtEvent(){
super("Event in Java awt");
setLayout(new BorderLayout());
try{
Button
button = new Button("INSERT_AN_URL_HERE");
button.addActionListener(this);
add(button, BorderLayout.NORTH);
Button button1 = new Button("INSERT_A_FILENAME_HERE");
button1.addActionListener(this);
add(button1, BorderLayout.SOUTH);
lbl = new Label("Welcome");
add(lbl, BorderLayout.CENTER);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
}
catch (Exception e){}
setSize(400,400);
setVisible(true);
}

public void actionPerformed(ActionEvent e){


Button bt = (Button)e.getSource();
String str = bt.getLabel();
lbl.setText(str);
}

Handling Key Press Event in Java


Introduction
import java.awt.*;
import java.awt.event.*;
public class KeyPress extends Frame{
Label label;
TextField txtField;
public static void main(String[] args) {
KeyPress k = new KeyPress();
}
public KeyPress(){
super("Key Press Event Frame");
Panel panel = new Panel();
label = new Label();
txtField = new TextField(20);

207

txtField.addKeyListener(new MyKeyListener());
add(label, BorderLayout.NORTH);
panel.add(txtField, BorderLayout.CENTER);
add(panel, BorderLayout.CENTER);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
setSize(400,400);
setVisible(true);
}

public class MyKeyListener extends KeyAdapter{


public void keyPressed(KeyEvent ke){
char i = ke.getKeyChar();
String str = Character.toString(i);
label.setText(str);
}
}

Item Events in Java


Introduction
-

Handling item event through the given program in which, a combo box and a text
area have been taken.
Items of the combo box are as follows : Red, Green, Blue. If you select an item
from the combo box then the message with the item name will be displayed in the
text area.

Choice()
This is the constructor of the Choice class which creates combo box.

ItemEvent :
- This is the ItemEvent class which indicates an event on selecting or deselecting items
from the item group. This event is passed by ItemListener object. The generated event is
passed to all ItemListener objects which is registered to receive such types of event. This
is done using the addItemListener() method of the object.
getItem()
:
- This is the method of the ItemEvent class which returns the value of the selected or
deselected item.
import java.awt.*;
import java.awt.event.*;
public class AwtItemEvent extends Frame{

208

TextArea txtArea;
public AwtItemEvent(String title){
super(title);
txtArea = new TextArea();
add(txtArea, BorderLayout.CENTER);
Choice choice = new Choice();
choice.addItem("red");
choice.addItem("green");
choice.addItem("blue");
choice.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent e){
txtArea.setText("This is the " + e.getItem() + " color.\n");
}
});
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
add(choice, BorderLayout.NORTH);
setSize(400,400);
setVisible(true);
setResizable(false);
}

public static void main(String[] args){


AwtItemEvent f = new AwtItemEvent("AWT Demo");
}

How to use KeyListener


import java.awt.*;
import java.awt.event.*;
public class KeyListenerTester extends Frame implements KeyListener{
TextField t1;
Label l1;
public KeyListenerTester(String s )
{
super(s);
Panel p =new Panel();
l1 = new Label ("Key Listener!" ) ;
p.add(l1);
add(p);
addKeyListener ( this ) ;
setSize ( 200,100 );
setVisible(true);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public void keyTyped ( KeyEvent e ){

209

l1.setText("Key Typed");
}
public void keyPressed ( KeyEvent e){
l1.setText ( "Key Pressed" ) ;
}
public void keyReleased ( KeyEvent e ){
l1.setText( "Key Released" ) ;
}
public static void main (String[]args ){
new KeyListenerTester ( "Key Listener Tester" ) ;
}
}

Hiding Frame in Java


Description of program:
-

In this program, program you will see that only one method of the frame is
important for the purpose.
The following program show a frame titled with "Frame Hiding". When you click
on the close button of the frame, the frame will not be closed but it will hide
certain with holding all frame data as it is.

Method's Description:
getSource(): This is the method of EventObject class. Hence, here this method is used
for the WindowEvent class so, it can return the Form's object that is done invisible by
using the setVisible() method. The getSource() method returns the source of the
generated event.
setVisible(false): This method takes a boolean valued argument which decides the form
for visible or not. If you pass the boolean value false then the form will be invisible
otherwise if you argument is true then the form object will be visible. By default Java
Awt Form is in the invisible state.
import java.awt.*;
import java.awt.event.*;
public class FrameHide{
public static void main(String[] args){
Frame fa= new Frame("Frame Hiding");
Panel p =new Panel();
Label l1=new Label("Welcome");
p.add(l1);
fa.add(p);
fa.setSize(300,200);
fa.setVisible(true);
fa.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){

210

Frame frame = (Frame)e.getSource();


frame.setVisible(false);
}
});

}
}

How to Create Button on Frame


Description of Program
The following program has used simply the Button class for creating a command button
on the frame object.
FlowLayout(): This is the constructor of FlowLayout class. This class is used for
arranging the component from left to right. Here this is used for creating the object of the
class to set the layout by passing the created object from the setLayout() method of the
Frame class.
Here is the code of this program:
import java.awt.*;
import java.awt.event.*;
public class ButtonText {
public static void main(String[] args) {
Frame frame=new Frame("Button Frame");
Button
button = new Button("Submit");
frame.add(button);
frame.setLayout(new FlowLayout());
frame.setSize(200,100);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}

How to create CheckBox On frame


Program Description:
There is class named CheckBox is used in the program for creating a checkbox
component. This class is explained as follows:

211

CheckBox(): This is the constructors for CheckBox class used for creating checkbox.
The constructor is taking here a String type parameter that is the label of checkbox.
import java.awt.*;
import java.awt.event.*;
public class CheckBoxDemo{
public static void main(String[] args){
Frame frame= new Frame("Checkbox");
Checkbox check=new Checkbox("Welcome");
Checkbox check1=new Checkbox("Roseindia");
frame.add(check);
frame.add(check1);
frame.setLayout(new FlowLayout());
frame.setSize(300,200);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}

Choice Option (Combo) In Java


import java.awt.*;
import java.awt.event.*;
public class ChoiceOptionExample{
public static void main(String[] args) {
Frame frame=new Frame("Choice");
Label label=new Label("What is your Choice:");
Choice choice=new Choice();
frame.add(label);
frame.add(choice);
choice.add("ASIA");
choice.add("INDIA");
choice.add("WELCOME");
frame.setLayout(new FlowLayout());
frame.setSize(250,150);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}

Paint an Image
- This section provides you to paint an image on the frame. Paint means draw an image
and set its on the frame to the specified location according to its x coordinate and y
coordinate.

212

All drawing process is done using the paint() method.


import java.awt.*;
import java.awt.event.*;
public class PaintIcon extends Frame{
Image image;
public static void main(String[] args) {
new PaintIcon();
}
public PaintIcon(){
setTitle("Paint an Icon example!");
setSize(200,200);
setVisible(true);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
}
public void paint(Graphics g){
Toolkit tool = Toolkit.getDefaultToolkit();
image = tool.getImage("warning.gif");
g.drawRect(20,50,100,100);
g.drawString("Draw Images:",20,40);
g.setColor(Color.yellow);
g.fillRect(20,50,100,100);
g.drawImage(image,30,85,this);
image = tool.getImage("Tom.gif");
g.drawImage(image,80,85,this);
}
}

213

Potrebbero piacerti anche