Вы находитесь на странице: 1из 382

MLR Institute of Technology,

Dundigal, Hyderabad

To understand basic concepts of object oriented programming

JAVA
PROGRAMMING

concepts.

To learn the basics of Java Programming.

UNIT - I
Objectives

To understand basic concepts of object oriented programming


concepts.

To learn the basics of Java Programming.

TOPICS
OOP Concepts: - Data abstraction, encapsulation, inheritance,
benefits of inheritance, polymorphism, classes and objects,
Procedural and object oriented programming paradigms.

Java programming - History of Java, comments, data types,


variables, constants, scope and life time of variables, operators,
operator hierarchy, expressions,type conversion and casting,
enumerated types, control flow block scope, conditional
statements, loops, break and continue statements, simple java
stand alone programs, arrays, console input and output,
formatting output, constructors, methods, , parameter passing,
static fields and methods, access control, this reference,
overloading methods and constructors, recursion, , garbage
collection, building strings,, exploring string class

INTRODUCTION
Layers of Computer Software
Since the invention of the computer, many programming approaches
have been tried. These include techniques such as modular
programming, top-down programming, bottom-up programming and
structured programming. The primary motivation in each is to
handle the complexity of programs.

INTRODUCTION
Categories of Programming Languages:
1. Monolithic Programming Language
2. Procedural Programming Language
3. Structured Programming Language
4. Object Oriented Programming Language
Monolithic Programming Language: Monolithic Programming Language
contains number of lines of Data.
It does not have subroutine concept.
The program code is duplicated each time it is to be used.
For e.g. : Assembly Language ,BASIC

Procedural Programming Language:


Emphasis on algorithm rather than Data.
Programs are organized in the form of subroutine.
Program controls are through jumps(goto) calls to subroutine
Data move freely around the system from function to function( Data Security
Problem)
It follows top down approach in program design.
For e.g.: Fortran, Cobol

INTRODUCTION
Structured Programming Language:
Programs are divided into individual Procedures that performs discrete tasks
Procedure are independent of each other
Procedures have their own local data and Logic
Introduction of user defined datatypes
Data Security was a problem
For e.g.: Pascal ,C

Object Oriented Programming Language:

Emphasis is on data rather than procedure.

Programs are divided into objects.

Functions that operate on the data of an object are tied together in the
data structure.

Data is hidden and cannot be accessed by external functions.

Objects may communicate with each other through functions.

Employs bottom-up approach in program design

New data and functions can be easily added whenever necessary.

Procedural Vs OOP
Procedure Oriented Programming
Program is divided into functions, every function has its own data and
global data.
Main program

Function-2

Function-1

Function-4

Function-6
Structure
programs

Global data

Function-3

Function-5

Function-7
of

Global data

Function-8

procedure-oriented

Function-1

Function-2

Function-3

Local data

Local data

Local data

Relationship of Data & Functions in


Procedural Programming
7

Procedural Vs OOP
Object Oriented Programming (OOP)

OOP decompose the problem into number of entities called objects and it
contains the data and functions.
Object A

Object B

Data
Methods

Data

Communication

Methods

Object C

Methods
Data
Organization of Data & Methods in
OOP

Procedural Vs OOP
Procedure Vs Object Oriented Programming

Characteristics of Structure-Oriented Programming


Emphasis is on doing things.

Large programs are divided into smaller programs known as

functions.

Most of the functions share global data.

Data move openly around the system from function to function

Functions transform data from one form to another

Employs top-down approach in program design

Procedural Vs OOP
Characteristics of Object-Oriented Programming

Emphasis is on data rather than procedure.

Programs are divided into objects.

Functions that operate on the data of an object are tied together


in the data structure.

Data is hidden and cannot be accessed by external functions.

Objects may communicate with each other through functions.

Employs bottom-up approach in program design

New data and functions can be easily added whenever necessary.

10

Procedural Vs OOP
Top Down Vs Bottom Up Approach
Top Down approach:
A Single module will be split into several smaller modules
General to Specific
Bottom Up approach:
Lot of small modules will be grouped to form a single large module
Specific to General

If the requirements are clear at the first instance, we can go for Top
Down approach.

In circumstances where the requirements may keep on adding, then


we can go for Bottom Up approach.

11

OOP CONCEPTS
Object Oriented Programming Concepts:
Classes

Objects
Data Abstraction
Encapsulation
Inheritance
Polymorphism

12

OOP CONCEPTS
Class & Object

A class is a collection of instance variables and methods.


Ex: fruit mango;
class
object
For example, mango, apple and orange are members of
the class fruit.
A class is a template or logical structure.
A class is a blue print from which individual objects are created.

Classes are user-defined data types and behave like the


built-in types of a programming language.
Objects are instances of the type class.
Objects are the basic run-time entities in an objectoriented system.

13

OOP CONCEPTS
Data Abstraction

Abstraction refers to the act of representing essential features

without including the background details or explanations.

Abstraction are of two types:

Procedure Abstraction

Data Abstraction

The access specifiers in JAVA or any OOP language, provides data


abstraction.

14

OOP CONCEPTS
Encapsulation

The wrapping up of data and methods into a single unit ( called

class) is known as encapsulation.

That is, the data and methods are given in the class definition.

Data encapsulation is the most striking features of a class.

15

OOP CONCEPTS
Inheritance

Inheritance is the process by which objects of one class acquire


the properties of another class. The concept of inheritance
provides the reusability.

A class can inherit one or more classes. Inherited class is called

as parent class or super class. Class that inherits a parent class is


called as child class or sub class.
16

OOP CONCEPTS
Benefits of Inheritance
1) Software reusability (among projects) : Functions written once can be
reused. No need to spend time in rewriting the code

2) Code sharing (within a project) : Many users and projects can use the
same classes.

3) Increased reliability (resulting from reuse and sharing of well-tested


code) : Probability of fewer bugs in already used and tested code.

4) Consistency of interface (among related objects)

:Guarantees that

interfaces to similar objects are in fact similar and the user is not

presented with a confusing collection of objects

17

OOP CONCEPTS
5) Rapid

prototyping

(quickly

assemble

from

pre-existing

components) :Software systems can be generated more quickly


and easily, leading to a style of programming known as rapid
prototyping.
6) Polymorphism

components):

and

frameworks

Polymorphism

permits

(high-level

the

reusable

programmer

to

generate high-level reusable components that can be tailored to


fit different applications by changes in their low-level parts.
7) Information

hiding

:Reduces

inter

connections

between

software system thus decreasing software complexity.


18

OOP CONCEPTS
Polymorphism

Poly Many

Morph Form

Polymorphism is the characteristic feature, that enables an entity


to co-exist in more than one form.
Ex: It allows the single method to perform different actions based
on the parameters.
Ploymorphism

Compile time
Polymorphism

Runtime
Polymorphism

JAVA supports method overloading and overriding to implement


polymorphism

19

OOP CONCEPTS
Benefits of OOP
Through inheritance, we can eliminate redundant code and extend the
use of existing classes.

The principle of data hiding helps the programmer to build secure


programs that cannot be invaded by code in the parts of the program.
It is easy to partition the work in a project based on objects.
Object oriented system easily upgraded from small to large systems.
Software complexity can be easily managed.
Applications of OOP
Real-time systems.
Object-Oriented Databases.
Neural Networks and Parallel Programming.
Decision Support and Office Automation Systems.
20

Java History
Computer language innovation and development occurs for two
fundamental reasons:
1) to adapt to changing environments and uses
2) to implement improvements in the art of programming

The development of Java was driven by both in equal measures.


Many Java features are inherited from the earlier languages:
B C C++ Java

Before Java: C
Designed by Dennis Ritchie in 1970s.
Before C: BASIC, COBOL, FORTRAN, PASCAL
C- structured, efficient, high-level language that could replace assembly
code when creating systems programs.
Designed, implemented and tested by programmers.

21

Java History
Before Java: C++
Designed by Bjarne Stroustrup in 1979.
Response to the increased complexity of programs and respective
improvements in the programming paradigms and methods:
1) assembler languages
2) high-level languages
3) structured programming
4) object-oriented programming (OOP)

OOP methodology that helps organize complex programs through the use
of inheritance, encapsulation and polymorphism.
C++ extends C by adding object-oriented features.

22

Java History
In 1990, Sun Microsystems started a project called Green.

Objective: to develop software for consumer electronics.

Project was assigned to James Gosling, a veteran of classic network


software design. Others included Patrick Naughton, ChrisWarth, Ed Frank,
and Mike Sheridan in 1991.
The team started writing programs in C++ for embedding into
toasters
washing machines
VCRs
Aim was to make these appliances more intelligent.
Hence, the team built a new programming language called Oak, which
avoided potentially dangerous constructs in C++, such as pointers, pointer
arithmetic, operator overloading etc.
It was soon realized that these design goals of consumer electronics
perfectly suited an ideal programming language for the Internet and WWW,
which should be:
object-oriented (& support GUI)
robust
architecture neutral

23

Java History
Internet programming presented a BIG business opportunity. Much
bigger than programming for consumer electronics.

Java was re-targeted for the Internet


The original motivation is not Internet: platform-independent software
embedded in consumer electronics devices.
With Internet, the urgent need appeared to break the fortified positions
of Intel, Macintosh and Unix programmer communities.
Java as an Internet version of C++? No.
Java was not designed to replace C++, but to solve a different set of
problems.
In 1994, an early web browser called WebRunner was written in Oak.
WebRunner was later renamed HotJava.
In 1995, Oak was renamed Java.

A common story is that the name Java relates to the place from where
the development team got its coffee. The name Java survived the trade
mark search.

24

Features of Java
The key considerations were summed up by the Java team in the following
list of buzzwords or features :
Simple
Secure
Portable

Object-oriented
Robust
Multithreaded

Architecture-neutral
Interpreted
High performance

Distributed
Dynamic
25

Features of Java
simple Java is designed to be easy for the professional programmer to
learn and use.
object-oriented: a clean, usable, pragmatic approach to objects, not
restricted by the need for compatibility with other languages.
Robust: restricts the programmer to find the mistakes early, performs
compile-time (strong typing) and run-time (exception-handling)
checks, manages memory automatically.
Multithreaded: supports multi-threaded programming for writing program
that perform concurrent computations.
Architecture-neutral: Java Virtual Machine provides a platform
independent environment for the execution of Java byte code
Interpreted and high-performance: Java programs are compiled into an
intermediate representation byte code:
a) can be later interpreted by any JVM
b) can be also translated into the native machine code for
efficiency.
26

Features of Java
Distributed: Java handles TCP/IP protocols, accessing a resource through
its URL much like accessing a local file.
Dynamic: substantial amounts of run-time type information to verify and
resolve access to objects at run-time.
Secure: programs are confined to the Java execution environment and
cannot access other parts of the computer.

Portability: Many types of computers and operating systems are in use


throughout the worldand many are connected to the Internet.
For programs to be dynamically downloaded to all the various types of
platforms connected to the Internet, some means of generating portable
executable code is needed. The same mechanism that helps ensure
security also helps create portability.
Indeed, Java's solution to these two problems is both elegant and efficient.

27

Data Types

28

Data Types
Java defines eight simple types:
1) byte 8-bit integer type
2) short 16-bit integer type
3) int 32-bit integer type

4) long 64-bit integer type


5) float 32-bit floating-point type
6) double 64-bit floating-point type
7) char 16-bit symbols in a character set
8)

boolean logical values true and false

29

Data Types
byte: 8-bit integer type.
Range: -128 to 127.
Example: byte b = -15;
Usage: particularly when working with data streams.
short: 16-bit integer type.
Range: -32768 to 32767.
Example: short c = 1000;
Usage: probably the least used simple type.
int: 32-bit integer type.
Range: -2147483648 to 2147483647.
Example: int b = -50000;
Usage:
1) Most common integer type.
2) Typically used to control loops and to index arrays.
3) Expressions involving the byte, short and int values are promoted
to int before calculation.

30

Data Types
long: 64-bit integer type.
Range: -9223372036854775808 to
9223372036854775807.
Example: long l = 10000000000000000;
Usage: 1) useful when int type is not large enough to hold the desired
value
float: 32-bit floating-point number.

Range: 1.4e-045 to 3.4e+038.


Example: float f = 1.5;
Usage:
1) fractional part is needed
2) large degree of precision is not required
double: 64-bit floating-point number.
Range: 4.9e-324 to 1.8e+308.
Example: double pi = 3.1416;
Usage:
1) accuracy over many iterative calculations
2) manipulation of large-valued numbers
31

Data Types
char: 16-bit data type used to store characters.
Range: 0 to 65536.
Example: char c = a;
Usage:
1) Represents both ASCII and Unicode character sets; Unicode defines a
character set with characters found in (almost) all human languages.
2) Not the same as in C/C++ where char is 8-bit and represents ASCII
only.
boolean: Two-valued type of logical values.
Range: values true and false.
Example: boolean b = (1<2);
Usage:
1) returned by relational operators, such as 1<2
2) required by branching expressions such as if or for

32

Variables and Constants


Java uses variables to store data.
To allocate memory space for a variable JVM requires:
1) to specify the data type of the variable
2) to associate an identifier with the variable
3) optionally, the variable may be assigned an initial value
All done as part of variable declaration.
Basic Variable Declaration
datatype identifier [=value];
datatype must be
A simple datatype
User defined datatype (class type)
Identifier is a recognizable name confirm to identifier rules
Value is an optional initial value.

33

Variables and Constants


We can declare several variables at the same time:
type identifier [=value][, identifier [=value] ];
Examples:
int a, b, c;
int d = 3, e, f = 5;
byte g = 22;
double pi = 3.14159;
char ch = 'x';
float val =10.1f;
In Java any value declared with decimal point is by default of type
double
Suppose we have to assign float value the we must use f ro F literal
to specify that the current value is float

34

scope and life time of variables


Scope determines the visibility of program elements with
respect to other program elements.
In Java, scope is defined separately for classes and methods:
1) variables defined by a class have a global scope
2) variables defined by a method have a local scope
A scope is defined by a block:
{

}
A variable declared inside the scope is not visible outside:
{
int n;
}
n = 1;// this is illegal
35

scope and life time of variables


Variables are created when their scope is entered by control
flow, and destroyed when their scope is left.

A variable declared in a method will not hold its value


between different invocations of this method.
A variable declared in a block looses its value when the
block is left.
Initialized in a block, a variable will be re-initialized with
every re-entry. Variables lifetime is confined to its scope!

36

Type Conversion
Size Direction of Data Type
Widening Type Conversion
Smaller Data Type Larger Data Type

Narrowing Type Conversion


Larger Data Type Smaller Data Type

Conversion done in two ways


Implicit type conversion
Carried out by compiler automatically

Explicit type conversion


Carried out by programmer using casting

37

Type Conversion
Widening Type Converstion
Implicit conversion by compiler automatically

byte -> short, int, long, float, double


short -> int, long, float, double
char -> int, long, float, double
int -> long, float, double
long -> float, double
float -> double

38

Type Conversion
Narrowing Type Conversion
Programmer should describe the conversion explicitly

byte -> char


short -> byte, char
char -> byte, short
int -> byte, short, char
long -> byte, short, char, int
float -> byte, short, char, int, long
double -> byte, short, char, int, long, float

39

Type Conversion

byte and short are always promoted to int


if one operand is long, the whole expression is promoted to long
if one operand is float, the entire expression is promoted to float
if any operand is double, the result is double

Syntax: (targetType) value


Examples:
1) integer value will be reduced module bytes range:
int i;
byte b = (byte) i;
2) floating-point value will be truncated to integer value:
float f;
int i = (int) f;

40

Operators
Java operators are used to build value expressions.
Java provides a rich set of operators:
1) assignment
2) arithmetic
3) relational
4) logical
5) bitwise
Arithmetic assignments:

+=

v += expr;

v = v + expr ;

-=

v -=expr;

v = v - expr ;

*=

v *= expr;

v = v * expr ;

/=

v /= expr;

v = v / expr ;

%=

v %= expr;

v = v % expr ;

41

Operators
Arithmetic Operators:
+

op1 + op2

ADD

op1 - op2

SUBSTRACT

op1 * op2

MULTIPLY

op1 / op2

DIVISION

op1 % op2

REMAINDER

Relational operator:
==

Equals to

Apply to any type

!=

Not equals to

Apply to any type

>

Greater than

Apply to numerical type

<

Less than

Apply to numerical type

>=

Greater than or equal

Apply to numerical type

<=

Less than or equal

Apply to numerical type


42

Operators
Logical operators:
&

op1 & op2

Logical AND

op1 | op2

Logical OR

op1 && op2

Short-circuit AND

||

op1 || op2

Short-circuit OR

! op

Logical NOT

op1 ^ op2

Logical XOR

&&

Relational operator:
~

~op

Inverts all bits

&

op1 & op2

Produces 1 bit if both operands are 1

op1 |op2

Produces 1 bit if either operand is 1

op1 ^ op2

Produces 1 bit if exactly one operand is 1

>>

op1 >> op2

Shifts all bits in op1 right by the value of op2

<<

op1 << op2

Shifts all bits in op1 left by the value of op2


43

Operators Hierarchy
Operator

Order of
evaluation

Operation

( )

left - right

parenthesis for explicit grouping

++ --

right - left

preincrement, predecrement

++ --

right - left

postincrement, postdecrement

left - right

multiplication, division, modulus

left - right

addition or String concatenation, subtraction

= += -= *= /= right - left
%=
p re ce d e n ce
le ve l
1

3
4

o p e ra to r
+
*
/
%
+
+
=

assignment

o p e ra tio n
u n a ry p lu s
u n a ry m in u s
m u ltip lica tio n
d ivis io n
re m a in d e r
a d d itio n
s u b tra ctio n
s trin g
co n ca te n a tio n
a s s ig n m e n t

a s s o cia te s
R to L

L to R

L to R
R to L

44

Expression

An expression is a construct made up of variables, operators, and


method invocations, which are constructed according to the syntax of
the language, that evaluates to a single value.

Examples of expressions are in bold below:


int number = 0;
anArray[0] = 100;
System.out.println("Element 1 at index 0: " + anArray[0]);
int result = 1 + 2; // result is now 3
if(value1 == value2)

System.out.println("value1 == value2");

45

Expression
The data type of the value returned by an expression depends on the
elements used in the expression.
The expression number = 0 returns an int because the assignment
operator returns a value of the same data type as its left-hand operand;
in this case, number is an int.
As you can see from the other expressions, an expression can return
other types of values as well, such as boolean or String.
The Java programming language allows you to construct compound
expressions from various smaller expressions as long as the data type
required by one part of the expression matches the data type of the
other.
Here's an example of a compound expression:

1*2*3

46

Enumerated type
3

47

Control Flow
Java control statements cause the flow of execution to advance and branch
based on the changes to the state of the program.
Control statements are divided into three groups:

1) Selection statements allow the program to choose different parts


of the execution based on the outcome of an expression
2) Iteration statements enable program execution to repeat one or
more statements
3) Jump statements enable your program to execute in a non-linear
fashion
Selection Statements:
Java selection statements allow to control the flow of programs execution
based upon conditions known only during run-time.
Java provides four selection statements:
1) if
2) if-else
3) if-else-if
4) switch

48

Control Flow
Iteration Statements
Java iteration statements enable repeated execution of part of a program until a certain
termination condition becomes true.
Java provides three iteration statements:
1) while
2) do-while
3) for
Jump Statements
Java jump statements enable transfer of control to other parts of program.
Java provides three jump statements:
1) break
2) continue
3) return
In addition, Java supports exception handling that can also alter the control flow of a
program.

Example Program 4: Controlstat : Ifelse , while, dowhile , For

49

Simple Java Program


A class to display a simple message:
class MyProgram
{
public static void main(String[] args)
{
System.out.println(First Java program.");
}
}
File name : MyProgram.java

Compilation : javac
Execution: java

MyProgram.java

MyProgram

50

Simple Java Program


public static void main(String[] args)
public is the visibility. This can be public, private, protected or (if you omit a
value) default.
static is a special [optional] keyword that indicates that this method can be
called without creating an instance of this class. Without it, you have to
instantiate this class and call this method from the resulting object.
void is the return type of this method, indicating that this method doesn't return
anything. Methods must have a return type.
main( ... ) is the name of this method. Methods have to be named. The
parentheses indicate that this is a method.

String[] args is a single parameter for the method. String[] is the type of the
parameter, indicating an array of Strings. args is the name of the parameter.
Parameters must be named.

51

Array
Array Creation
After declaration, no array actually exists.
In order to create an array, we use the new operator:
type array-variable[];
array-variable = new type[size];
This creates a new array to hold size elements of datatype type, which
reference will be kept in the variable array-variable.

Array Indexing :

Later we can refer to the elements of this array through their indexes:
array-variable[index]
The array index always starts with zero!
The Java run-time system makes sure that all array indexes are in the correct
range, otherwise raises a run-time error.
52

Arrays
Array Initialization:
Arrays can be initialized when they are declared:
int monthDays[] = {31,28,31,30,31,30,31,31,30,31,30,31};

Note :
1) there is no need to use the new operator
2) the array is created large enough to hold all specified elements

Multidimensional Arrays:
Multidimensional arrays are arrays of arrays:
1) declaration: int array[][];
2) creation:
int array = new int[2][3];
3) initialization
int array[][] = { {1, 2, 3}, {4, 5, 6} };

Example Program : Array

53

Console Input and Output


Console Output

System.out.print("Hello ");
System.out.println("world");

Console Input
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String text = in.readLine();
Scanner sc = new Scanner(System.in);
int pop =sc.nextInt();
String preName = sc.nextLine();
String preAddr = sc.nextLine();

54

formatting output
print and println Methods:
Invoking print or println outputs a single value after converting the value using the
appropriate toString method.
We can see this in the Root example:
public class Root
{
public static void main(String[] args)
{
int i = 2;
double r = Math.sqrt(i);
System.out.print("The square root of ");
System.out.print(i);
System.out.print(" is ");
System.out.print(r);
System.out.println(".");
i = 5;
r = Math.sqrt(i);
System.out.println("The square root of " + i + " is " + r + "."); } }
Here is the output of Root:
The square root of 2 is 1.4142135623730951.
The square root of 5 is 2.23606797749979.

55

formatting output
format Method:
The format method formats multiple arguments based on a format string. The format
string consists of static text embedded with format specifiers; except for the format
specifiers, the format string is output unchanged.

public class Root2


{
public static void main(String[] args)
{
int i = 2;
double r = Math.sqrt(i);
System.out.format("The square root of %d is %f.%n", i, r);
}
}
Here is the output:

The square root of 2 is 1.414214.

56

Class

A class is a blueprint that defines the variables and methods common to all
objects of a certain kind.
Example: your dog is a object of the class Dog.
An object holds values for the variables defines in the class.
An object is called an instance of the Class

A basis for the Java language.


Each concept we wish to describe in Java must be included inside a class.
A class defines a new data type, whose values are objects:
A class is a template for objects
An object is an instance of a class

57

Class Definition

A class contains a name, several variable declarations (instance variables) and


several method declarations. All are called members of the class.

General form of a class:


class classname {
type instance-variable-1;

type instance-variable-n;
type method-name-1(parameter-list) { }
type method-name-2(parameter-list) { }

type method-name-m(parameter-list) { }
}

58

Object

Real world objects are things that have:


1) state
2) behavior
Example: your dog:
state name, color, breed, sits?, barks?, wages tail?, runs?
behavior sitting, barking, waging tail, running
A software object is a bundle of variables (state) and methods (operations).

Object Creation:
A variable is declared to refer to the objects of type/class String:
String s;
The value of s is null; it does not yet refer to any object.
A new String object is created in memory with initial abc value:
String s = new String(abc);
Now s contains the address of this new object.

59

class Box
{
double width;
double height;
double depth;
}

Example: Class Usage

class BoxDemo
{
public static void main(String args[])
{
Box mybox = new Box();
double vol;
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
vol = mybox.width * mybox.height * mybox.depth;
System.out.println ("Volume is " + vol);
}
}

class sum
{
int a,b,sum;

void get()
{
a=10;
b=5;
}
void sum()
{

sum=a+b;
//System.out.print("sum is "+sum);
}
}
class sum1
{
public static void main(String args[])
{
sum s1=new sum();
s1.get();
s1.sum();

System.out.print("sum is" +s1.sum);

60

Constructor

A constructor initializes the instance variables of an object.

It is called immediately after the object is created but before the new operator
completes.
1) it is syntactically similar to a method:
2) it has the same name as the name of its class
3) it is written without return type; the default return type of a class

constructor is the same class

When the class has no constructor, the default constructor automatically initializes
all its instance variables with zero.

61

Example: Constructor
class Box {
double width;
double height;
double depth;
Box() {
//constructor
System.out.println("Constructing Box");
width = 10; height = 10; depth = 10;
}
double volume()
{
return width * height * depth;
}
}
62

Parameterized Constructor
class Box
{
double width;
double height;
double depth;
Box(double w, double h, double d)
{
width = w; height = h; depth = d;
}
double volume()
{ return width * height * depth; }
}
Example Program : Constructors

63

Methods

General form of a method definition:


type name(parameter-list) {
return value;

Components:
1) type - type of values returned by the method. If a method does not return
any value, its return type must be void.
2) name is the name of the method
3) parameter-list is a sequence of type-identifier lists separated by commas
4) return value indicates what value is returned by the method.

64

Example: Method

Classes declare methods to hide their internal data structures, as well as for their
own internal use: Within a class, we can refer directly to its member variables:

Eg:
class Box {
double width, height, depth;
void volume() {
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}

65

Parameterized Method

Parameters increase generality and applicability of a method:


1) method without parameters
int square() { return 10*10; }
2) method with parameters
int square(int i) { return i*i; }

Parameter: a variable receiving value at the time the method is invoked.

Argument: a value passed to the method when it is invoked.

66

Access Control

Java provides control over the visibility of variables and methods.


Helps in protecting against accidental or wrong usage.
Keeps code elegant and clean (easier to maintain)

Access Modifiers: Public, Private, Protected, Default

Public: keyword applied to a class, makes it available/visible everywhere.


Applied to a method or variable, completely visible.
Default Public keyword applied to a class, makes it available/visible
everywhere. Applied to a method or variable, completely visible.

Private fields or methods for a class only visible within that class.
Private members are not visible within subclasses, and are not inherited.
Protected members of a class are visible within the class, subclasses
and also within all classes that are in the same package as that class.

Default(No visibility modifier is specified): it behaves like public in its package


and private in other packages.

Example Program : Access Control

67

Keyword this

Keyword this allows a method to refer to the object that invoked it.
Can be used by any object to refer to itself in any class method
It can be used inside any method to refer to the current object

Box(double width, double height, double depth)


{
this.width = width;
this.height = height;
this.depth = depth;
}
Typically used to

Avoid variable name collisions


Pass the receiver as an argument
Chain constructors

Example Program : Keythis

68

Garbage Collection
Garbage collection is a mechanism to remove objects from memory when they are no
longer needed.

Garbage collection is carried out by the garbage collector:


1) The garbage collector keeps track of how many references an object has.
2) It removes an object from memory when it has no longer any references.
3) Thereafter, the memory occupied by the object can be allocated again.
4) The garbage collector invokes the finalize method .

finalize() Method
A constructor helps to initialize an object just after it has been created.
In contrast, the finalize method is invoked just before the object is destroyed:
1) implemented inside a class as:
protected void finalize() { }
2) implemented when the usual way of removing objects from memory is insufficient,
and some special actions has to be carried out

Example Program : Garbagecollection

69

Method Overloading

It is legal for a class to have two or more methods with the same name.

However, Java has to be able to uniquely associate the invocation of a method


with its definition relying on the number and types of arguments.

Therefore the same-named methods must be distinguished:


1) by the number of arguments, or
2) by the types of arguments

Overloading and inheritance are two ways to implement polymorphism.

70

Example: Overloading
class OverloadDemo
{
void test()
{ System.out.println("No parameters");

void test(int a)
{
System.out.println("a: " + a);

void test(int a, int b)


{ System.out.println("a and b: " + a + " " + b); }
double test(double a)
{ System.out.println("double a: " + a); return a*a; }

71

Constructor Overloading
class Box
{
double width, height, depth;
Box(double w, double h, double d)
{ width = w; height = h; depth = d; }
Box()
{ width = -1; height = -1; depth = -1; }
Box(double len)
{ width = height = depth = len;

double volume()
{ return width * height * depth; }
}

Example Program : ConstructorOverloading

72

Parameter Passing
Two types of variables:
1) simple types
2) class types
Two corresponding ways of how the arguments are passed to
methods:
1) by value a method receives a copy of the original
value; parameters of simple types
2) by reference a method receives the memory address of
the original value, not the value itself;
parameters of class types

73

Call by value
class CallByValue
{
public static void main(String args[])
{
Test ob = new Test();
int a = 15, b = 20;
System.out.print("a and b before call: );
System.out.println(a + " " + b);
ob.meth(a, b);
System.out.print("a and b after call: ");
System.out.println(a + " " + b);
}
}

74

Call by reference

As the parameter hold the same address as the argument, changes to the object
inside the method do affect the object used by the argument:
class CallByRef
{
public static void main(String args[])
{
Test ob = new Test(15, 20);
System.out.print("ob.a and ob.b before call: );
System.out.println(ob.a + " " + ob.b);
ob.meth(ob);
System.out.print("ob.a and ob.b after call: ");
System.out.println(ob.a + " " + ob.b);
}
}

Example Program : ParameterPassing

75

Recursion

A recursive method is a method that calls itself:

1) all method parameters and local variables are allocated on the stack
2) arguments are prepared in the corresponding parameter positions
3) the method code is executed for the new arguments
4) upon return, all parameters and variables are removed from the stack
5) the execution continues immediately after the invocation point

76

Example: Recursion
class Factorial
{
int fact(int n)
{
if (n==1) return 1;
return fact(n-1) * n;
}
}
class Recursion
{
public static void main(String args[])
{
Factorial f = new Factorial();
System.out.print("Factorial of 5 is ");
System.out.println(f.fact(5));
}
}
77

String Handling

String is probably the most commonly used class in Java's class library.
The obvious reason for this is that strings are a very important part of
programming.
The first thing to understand about strings is that every string you create is
actually an object of type String. Even string constants are actually String
objects.
For example, in the statement
System.out.println("This is a String, too");
the string "This is a String, too" is a String constant
Java defines one operator for String objects: +.
It is used to concatenate two strings. For example, this statement
String myString = "I" + " like " + "Java.";
results in myString containing "I like Java."

78

String Handling
1.
2.
3.
4.
5.

6.
7.
8.
9.

char charAt(int index)


:
Returns the character at the specified index
int compareTo(Object o)
: Compares this String to another Object.
int compareTo(String anotherString ) : Compares two string s lexicographically.
int compareToIgnoreCase(String str) :Compares two string s lexicographically,
ignoring case differences.
String concat(String str) :Concatenates the specified string to the end of this
string
boolean contentEquals(StringBuffer sb) : Returns true if and only if this String
represents the same sequence of characters as the specified StringBuffer.
static String copyValueOf(char[] data) :Returns a String that represents the
character sequence in the array specified.
static String copyValueOf(char[] data, int offset, int count):Returns a String that
represents the character sequence in the array specified.
boolean endsWith(String suffix) :Tests if this string ends with the specified
suffix.

79

String Handling
1.

boolean equals(Object anObject):Compares this string to the specified object.

2.

boolean equalsIgnoreCase(String anotherString ):Compares this String to


another String , ignoring case considerations.

3.

byte g etBytes() :Encodes this String into a sequence of bytes using the platform's
default charset, storing the result into a new byte array.

4.

byte[] g etBytes(String charsetName) :Encodes this String into a sequence of


bytes using the named charset, storing the result into a new byte array.

5.

void getChars(int srcBeg in, int srcEnd, char[] dst, int dstBeg in): Copies
characters from this string into the destination character array.

80

String Handling
1.

int hashCode() :Returns a hash code for this string .

2.

int indexOf(int ch) : Returns the index within this string of the first occurrence of
the specified character.

3.

int indexOf(int ch, int fromIndex) :Returns the index within this string of the
first occurrence of the specified character, starting the search at the specified index.

4.

int indexOf(String str): Returns the index within this string of the first occurrence
of the specified substring .

5.

int indexOf(String str, int fromIndex) :Returns the index within this string of the
first occurrence of the specified substring , starting at the specified index.

6.

String intern() :Returns a canonical representation for the string object.

7.

int lastIndexOf(int ch) :Returns the index within this string of the last occurrence
of the specified character.
81

String Handling
1. int lastIndexOf(int ch, intfromIndex) :
Returns the index within this string of the last occurrence of the specified character,
searching backward starting at the specified index.
2. int lastIndexOf(String str):
Returns the index within this string of the rightmost occurrence of the specified
substring .
3. int lastIndexOf(String str, int fromIndex) :
Returns the index within this string of the last occurrence of the specified substring ,
searching backward starting at the specified index.
4. int length() : Returns the length of this string .
5. boolean matches(String regex): Tells whether or not this string matches the g iven
regular expression.
6. boolean regionMatches(boolean ignoreCase, int offset, String other, int ooffset, int
len) : Tests if two string regions are equal.

82

String Handling
1.

boolean reg ionMatches(int toffset, String other, int ooffset, int len) : Tests if
two string regions are equal.

2.

String replace(char oldChar, char newChar): Returns a new string resulting


from replacing all occurrences of oldChar in this string with newChar.

3.

String replaceAll(String reg ex, String replacement) :


Replaces each
substring of this string that matches the given regular expression with the given
replacement.

4. String replaceFirst(String reg ex, String replacement) :


Replaces the first
substring of this string that matches the given regular expression with the given
replacement.
5. String [] split(String reg ex) : Splits this string around matches of the given regular
expression.
6. String [] split(String reg ex, int limit) : Splits this string around matches of the
given regular expression.
7. boolean startsWith(String prefix) : Tests if this string starts with the specified
83
prefix.

String Handling
boolean startsWith(String prefix, int toffset): Tests if this string starts with the
specified prefix beg inning a specified index.
CharSequence subSequence(int beg inIndex, int endIndex) :Returns a new character
sequence that is a subsequence of this sequence.
String substring (int beg inIndex):Returns a new string that is a substring of this
string .
String substring (int beg inIndex, int endIndex): Returns a new string that is a
substring of this string .
char[] toCharArray() :Converts this string to a new character array.
String toLowerCase(): Converts all of the characters in this String to lower case using
the rules of the default locale.
String toLowerCase(Locale locale) :Converts all of the characters in this String to
84
lower case using the rules of the g iven Locale.

String Handling
String toString () : This object (which is already a string !) is itself returned.
String toUpperCase() :Converts all of the characters in this String to upper case using
the rules of the default locale.

String toUpperCase(Locale locale) : Converts all of the characters in this String to


upper case using the rules of the given Locale.
String trim() :Returns a copy of the string , with leading and trailing whitespace
omitted.
static String valueOf(primitive data type x) :Returns the string representation of the
passed data type argument.

Example Program : StringFunctions

85

UNIT - II
Objectives
To understand basic concepts of inheritance, polymorphism
To know the differences in interfaces and abstract classes
To know the creation and importing packages

86

TOPICS
Inheritance Inheritance hierarchies, super and sub classes,
Member access rules, super keyword, preventing inheritance: final
classes and methods, the Object class and its methods.

Polymorphism- dynamic binding, method overriding, abstract


classes and methods.
Interfaces Interfaces vs Abstract classes, defining an interface,
implementing interfaces, accessing implementation through
interface references, extending interface.

Inner classes- Uses of inner classes, local inner classes,


anonymous inner classes, static inner classes, examples.
Packages- Defining, Creating and Accessing
Understanding CLASSPATH, importing packages.
87

Package,

Inheritance
-The mechanism of deriving a new class from an existing class is
known as inheritance.
-Existing class is known as base class or parent class or super
class and new class is known as derived class or child class or sub
class.

-In inheritance base class members are inherited to derived class


and also new members can be added to derived class

88

Inheritance
Types of Inheritances:

1.-Single Inheritance
2.Multiple Inheritance

3.Hierarchical Inheritance
4.Multilevel Inheritance

89

Inheritance
Syntax of Derived class:
class subclass-name extends superclass-name {
// body of class
}

Member Access Rules


Member access rules
A subclass includes all of the members of its super class
except private members.

Remember
A class member that has been declared as private will remain
private to its class. It is not accessible by any code outside its
class, including subclasses.

Referring to super class Object with a sub class reference


produces syntax Error. In such case we need type casting

Java Program to demonstrate

Super Keyword
super has two general forms.
The first calls the superclass constructor.
The second is used to access a member of the superclass that has been
hidden, by a member of a subclass.
Using super to Call Superclass Constructors
A subclass can call a constructor method defined by its superclass by
use of the following form of super:
super(parameter-list);
parameter-list specifies any parameters needed by the constructor in
the superclass.
super( ) must always be the first statement executed inside a
subclass constructor.

92

Java Program to demonstrate

Super Keyword
The second form of super acts somewhat like this, except that it always refers
to the superclass of the subclass in which it is used.
general form:
super.member
Here, member can be either a method or an instance variable.
This second form of super is most applicable to situations in which member
names of a subclass hide members by the same name in the superclass.

Ex:
class A {
int i;
}
class B extends A {
int i;
B(int a, int b) {
super.i = a;
i = b;
}
93

// this i hides the i in A


// i in A
// i in B
Java Program to demonstrate

Super Keyword
In a class hierarchy constructors are called in order of derivation, from
superclass to subclass.
super() must be the first statement executed in a subclass

constructor.
If super() is not used, the default constructor of each superclass will
be executed.
Implicitly default form of super ( super() ) will be invoked in each

subclass to call default constructor of superclass

94

Preventing Inheritance: Private Classes & Methods


The keyword final has three uses.
Final as constant

Final to prevent overriding

Final to prevent inheritance

95

Preventing Inheritance: Private Classes & Methods

A variable which is declared as final can not be modified latter.


This means that you must initialize a final variable when it is
declared.

Ex:final int x=10;


x=45; //error

96

Preventing Inheritance: Private Classes & Methods


A Method that is declared as final cannot be overridden in
subclass method
Methods that are declared private are implicitly final.
class A {
final void show() {
System.out.println("This is a final method.");
}
class B extends A {
void show() {
System.out.print(hai);
// ERROR! Can't override.
}
}
97

Preventing Inheritance: Private Classes & Methods


classes declared as final cannot be inherited.
Declaring a class as final implicitly declares all of its methods as final.
It is illegal to declare a class as both abstract and final, because an
abstract class is incomplete by itself and depends upon its subclasses to

provide complete implementations.


final class A {
// ...
}

// The following class is illegal.


class B extends A { // ERROR! Can't subclass A

// ...
98

Java Program to demonstrate

The Object Class & its Methods


In java, all classes use inheritance.
If no parent class is specified explicitly, the base class Object is implicitly
inherited.
All classes defined in Java, is a child of Object class, which provides minimal
functionality guaranteed to be common to all objects.
Method
Purpose
Object clone( )
Creates a new object that is the same as the object
being cloned.
boolean equals(Object object)
Determines whether one object is equal
to another.
void finalize( )
Called before an unused object is recycled.
class getClass( )
Obtains the class of an object at run time.
int hashCode( )
Returns the hash code associated with the
invoking object.
void notify( )
Resumes execution of a thread waiting on the
invoking object.
void notifyAll( )
Resumes execution of all threads waiting on
the invoking object.
String toString( )
Returns a string that describes the object.
void wait( )
Waits on another thread of execution.
void wait(long milliseconds)
void wait(long milliseconds,int nanoseconds).
99

Polymorphism
Polymorphism: to assign multiple meanings to the same method name
Implemented using late binding.
Late binding or dynamic binding (run-time binding):
Method to be executed is determined at execution time, not at compile
time.

Method Overriding
When a method in a subclass has the same
name
signature and
return type
as a method in its superclass, then the method in the subclass is
said to be overriden the method in the superclass.
When an overridden method is called from within a subclass, it will
always refer to the version of that method defined by the subclass.
The version of the method defined by the superclass will be hidden.

100

Java Program to demonstrate

Plymorphism: Dynamic Dispatch Method


Dynamic method dispatch is the mechanism by which a
call to an overridden method is resolved at run time, rather
than compile time.
When an overridden method is called through a superclass
reference, the method to execute will be based upon the type
of the object being referred to at the time the call occurs.
Not the type of the reference variable.

101

Java Program to demonstrate

Abstract class & Methods

Java allows abstract classes


use the modifier abstract on a class header to declare an abstract class
abstract class Vehicle
{ }

An abstract class is a placeholder in a class hierarchy that


represents a generic concept
An abstract class often contains abstract methods, though
it doesnt have to
Abstract methods consist of only methods declarations,
without any method body

102

Abstract class & Methods


public abstract class Vehicle
{
String name;
public String getName()
{ return name; } \\ method body

abstract public void move();


\\ no body!
}

103

Java Program to demonstrate

Abstract class & Methods


An abstract class often contains abstract methods, though it
doesnt have to
Abstract methods consist of only methods declarations, without any method
body

The non-abstract child of an abstract class must override the


abstract methods of the parent
An abstract class cannot be instantiated
(why?)

The use of abstract classes is a design decision; it helps us


establish common elements in a class that is too general to
instantiate
104

interfaces
interfaces are syntactically similar to classes, but they lack instance
variables, and their methods are declared without any body.
Any number of classes can implement an interface.
One class can implement any number of interfaces.

Defining an Interface
The general form of an interface:
access interface name {
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}

Example:
interface Callback {
void
callback(int param);
}

Contd..

Here, access is either public or not used.


Default indicates, the interface is only available to other
members of the package in which it is declared.
public indicates, the interface can be used by any other
code.

Variables can be declared inside of an interface.


They are implicitly final and static, meaning they cannot be
changed by the implementing class.
They must be initialized with a constant value
All methods and variables are implicitly public if the interface,
itself, is declared as public.

Implementing interfaces
Once an interface has been defined, one or more classes can implement that
interface.
The general form of a class that implements an interface :
access class classname [extends superclass][implements interface [,interface...]] {
// class-body
}
If a class implements more than one interface, the interfaces are separated with a
comma.
The methods that implement an interface must be declared as public.
The type signature of the implementing method must match exactly the type signature
specified in the interface definition

//Example for a class which contain both interface and non interface methods
class Client implements Callback {
// Implement Callback's interface
public void callback(int p) {
System.out.println("callback called with " + p);
}
void nonIfaceMeth() {
System.out.println(Non Interface
Method.");
}

Accessing Implementations Through Interface


References
Any instance of any class that implements the interface can be referred by an
interface variable.
When you call a method through an interface variable, the correct version
will be called based on the actual instance of the class referred by the
variable.
This is one of the key features of interfaces.

interface Callback {
param);

void callback(int

class Client implements Callback {


// Implement Callback's interface
public void callback(int p) {
System.out.println("callback called with " + p);
}
}

class TestIface {
public static void main(String args[]) {
Callback c = new Client();
c.callback(42);
//Callback cb;
//Client c=new Client();
//cb=c;
//cb.callback(42);
}
}
Output:

callback called with 42

Partial Implementations
If a class includes an interface but does not fully implement the methods defined by
that interface, then that class must be declared as abstract.
abstract class Incomplete implements Callback{
int a, b;
void show() {
System.out.println(a + " " + b);
}
// ...
}
Here, the class Incomplete does not implement callback( ) and must be
declared as abstract.
Any class that inherits Incomplete must implement callback( ) or be declared
abstract itself.

Variables in Interfaces
You can define variables in an interface but implicitly they are final variables.
That is you cant modify them.

FinalDemo.java
interface FinalDemo{
int i=100;
void show();
}

FinalTest.java
class FinalImpl implements FinalDemo{
public void show(){
System.out.println("FinalTest :Show()");
}
}
class FinalTest{
public static void main(String sree[]){
FinalImpl fi=new FinalImpl();
fi.show();
//fi.i=200; cant assign a value to variable i
System.out.println("FinalDemo Varaible i :"+fi.i);

}
}

Output:

FinalTest :Show()
FinalDemo Varaible i :100

Interfaces Can Be Extended


One interface can inherit another by use of the keyword extends.

The syntax is the same as for inheriting classes.


When a class implements an interface that inherits another interface, it must
provide implementations for all methods defined within the interface inheritance
chain.

public void meth2() {

// One interface can extend another.


interface A {
void meth1();
void meth2();
}
// B now includes meth1() and meth2() -- it adds
meth3().
interface B extends A {
void meth3();
}
// This class must implement all of A and B
class MyClass implements B {
public void meth1() {
System.out.println("Implement meth1().");
}

System.out.println("Implement
meth2().");
}
public void meth3() {
System.out.println("Implement
meth3().");

}
}
class IFExtend {
public static void main(String arg[]) {
MyClass ob = new
MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}
}

Output:
Implement meth1().
Implement meth2().
Implement meth3().

interface Callback {
void callback(int param);
}

class Client implements Callback {


// Implement Callback's interface
public void callback(int p) {
System.out.println("callback called with " + p);
}
void nonIfaceMeth() {
System.out.println(NonInterface Method.");
}
}

class TestIface2 {
public static void main(String args[]) {
Callback c = new Client();
AnotherClient ob = new AnotherClient();
c.callback(42);
c = ob; // c now refers to AnotherClient object
c.callback(42);
}
}

// Another implementation of Callback.


class AnotherClient implements Callback {
// Implement Callback's interface
public void callback(int p) {
System.out.println("Another version of callback");
System.out.println("p squared is " + (p*p));
}
}

Output:
callback called with 42
Another version of callback
p squared is 1764

Class Vs Interface
The methods of an Interface are all abstract methods. They cannot have bodies.
An interface can only define constants.
You cannot create an instance from an interface.

An interface can only be implemented by classes or extended by other interfaces.

Interfaces have no direct inherited relationship with any particular class, they are
defined independently.

Interfaces themselves have inheritance relationship among themselves.

A class can implement more than one interface. By contrast, a class can only
inherit a single superclass (abstract or otherwise).

Abstract Class Vs Interface


An abstract class is written when there are some common features shared by all the
objects.
An interface is written when all the features are implement differently in different
objects.

When an object class is written, it is the duty of the programmer to provide sub classes
to it.
An interface is written when the programmer wants to leave the implementation to the
third party vendors.

An abstract class contains some abstract methods and also some concrete methods.
An interface contains only abstract methods.

An abstract class can contain instance variables also.


An interface can not contain instance variables. It contains only constants.

All the abstract methods of the abstract class should be implemented in its sub
classes.
All the (abstract) methods of the interface should be implemented in its
implementation classes.

Abstract class is declared by using the keyword abstract.


Interface is declared using the keyword interface.

A class can implement more than one interface.


An abstract class can only inherit a single super class (abstract or otherwise).

Interfaces have no direct inherited relationship with any particular class, they are
defined independently. Interfaces themselves have inheritance relationship among
themselves.

Uses of Interface
To reveal an object's programming interface (functionality of the object) without
revealing its implementation.
This is the concept of encapsulation.
The implementation can change without affecting the caller of the
interface.

To have unrelated classes implement similar methods (behaviors).


One class is not a sub-class of another.
To model multiple inheritance.
A class can implement multiple interfaces while it can extend only one
class.

//example for multiple inheritance using interface


interface One{
void display();
}
interface Two{
void show();
}
interface Three extends One,Two{
void write();
}
class Interf implements Three{
public void display(){
System.out.println("hi");
}
public void show(){
System.out.println("hello");
}
public void write(){
System.out.println("welcome");
}
}
class infsTest{
public static void main(String args[]){
Interf a1=new Interf();
a1.display();
a1.show();
a1.write();
}
}

5A) Define an interface GeometricShape with


methods area () and perimeter () (both methods
return type and parameter list should be void and
empty respectively).
Define classes like Triangle, Rectangle and Circle
implementing the GeometricShapeInterface and
also define ExecuteMain class in which include
main method to test the above class.

import java.util.Scanner;
interface GeometricShape{
void area();
void perimeter();
}

class Triangle implements GeometricShape{


double a=1,b=2,c=1,h=4;
public void area(){
System.out.println("");
double area1=0.5*b*h;
System.out.println("Area of a Triangle: "+area1);
}
public void perimeter(){
double per=a+b+c;
System.out.println("Perimeter of a Triangle: "+per);
System.out.println("");
}
}

class Rectangle implements GeometricShape{


int length=15,width=10,per,area1;
public void area(){
area1=length*width;
System.out.println("Area of Rectangle: "+area1);
}
public void perimeter(){
per=2*length+2*width;
System.out.println("Perimeter of Rectangle: "+per);
System.out.println("");
}
}

class Circle implements GeometricShape{


int r=10;
double p=3.141,area1=0.0,per=0.0;
public void area(){
area1=p*r*r;
System.out.println("Area of Circle: "+area1);
}
public void perimeter(){
per=2*p*r;
System.out.println("Perimeter of Circle: "+per);
System.out.println("");
}
}

class ExecuteMainA{
public static void main(String args[]){
Triangle t=new Triangle();
t.area();
t.perimeter();
Circle c=new Circle();
c.area();
c.perimeter();
Rectangle r=new Rectangle();
r.area();
r.perimeter();
}
}

Inner Classes

Inner classes are classes defined within other classes

The class that includes the inner class is called the outer class
There is no particular location where the definition of the inner
class (or classes) must be place within the outer class
Placing it first or last, however, will guarantee that it is easy to find

129

Simple Uses of Inner Classes


An inner class definition is a member of the outer class in the same
way that the instance variables and methods of the outer class are
members

An inner class is local to the outer class definition


The name of an inner class may be reused for something else outside the
outer class definition
If the inner class is private, then the inner class cannot be accessed by name
outside the definition of the outer class

130

Inner/Outer Classes

public class Outer


{
private class Inner
{
// inner class instance variables
// inner class methods
} // end of inner class definition
// outer class instance variables
// outer class methods
}

131

Simple Uses of Inner Classes

There are two main advantages to inner classes

They can make the outer class more self-contained since they are
defined inside a class
Both of their methods have access to each other's private methods
and instance variables

Using an inner class as a helping class is one of the most


useful applications of inner classes

If used as a helping class, an inner class should be marked private

132

Inner and Outer Classes Have Access to


Each Other's Private Members
Within the definition of a method of an inner class:

It is legal to reference a private instance variable of the outer class


It is legal to invoke a private method of the outer class
Essentially, the inner class has a hidden reference to the outer class

Within the definition of a method of the outer class

It is legal to reference a private instance variable of the inner class on an object of


the inner class
It is legal to invoke a (nonstatic) method of the inner class as long as an object of
the inner class is used as a calling object

Within the definition of the inner or outer classes, the modifiers public and
private are equivalent

133

Class with an Inner Class

134

Class with an Inner Class

135

Class with an Inner Class

136

Referring to a Method of the Outer Class


If a method is invoked in an inner class

If the inner class has no such method, then it is assumed to be an


invocation of the method of that name in the outer class
If both the inner and outer class have a method with the same name, then
it is assumed to be an invocation of the method in the inner class
If both the inner and outer class have a method with the same name, and
the intent is to invoke the method in the outer class, then the following
invocation must be used:

OuterClassName.this.methodName()

137

Public Inner Classes


If an inner class is marked public, then it can be used
outside of the outer class
In the case of a nonstatic inner class, it must be created using
an object of the outer class

BankAccount account = new BankAccount();


BankAccount.Money amount =
account.new Money("41.99");

Note that the prefix account. must come before new


The new object amount can now invoke methods from the inner
class, but only from the inner class

138

Public Inner Classes


In the case of a static inner class, the procedure is similar to, but
simpler than, that for nonstatic inner classes

OuterClass.InnerClass innerObject =
new OuterClass.InnerClass();

Note that all of the following are acceptable

innerObject.nonstaticMethod();
innerObject.staticMethod();
OuterClass.InnerClass.staticMethod();

139

Public Money Inner Class


If the Money inner class in the BankAccount example was defined as public, we can
create and use objects of type Money outside the BankAccount class.
// this is okay in main( )
BankAccount account = new BankAccount( );
BankAccount.Money amt =
// note syntax
account.new Money( 41.99
);
System.out.println( amt.getAmount( ) );
// but NOT this why not??
System.out.println( amt.getBalance( ) );

140

Static Inner Classes


A normal inner class has a connection between its objects and the
outer class object that created the inner class object

This allows an inner class definition to reference an instance variable, or


invoke a method of the outer class

There are certain situations, however, when an inner class must be


static

If an object of the inner class is created within a static method of the outer
class
If the inner class must have static members

141

Static Inner Classes


Since a static inner class has no connection to an object of the outer
class, within an inner class method

Instance variables of the outer class cannot be referenced


Nonstatic methods of the outer class cannot be invoked

To invoke a static method or to name a static variable of a static


inner class within the outer class, preface each with the name of the
inner class and a dot

142

Multiple Inner Classes


A class can have as many inner classes as it needs.
Inner classes have access to each others private members as
long as an object of the other inner class is used as the calling
object.

143

The .class File for an Inner Class


Compiling any class in Java produces a .class file named
ClassName.class
Compiling a class with one (or more) inner classes causes both (or
more) classes to be compiled, and produces two (or more) .class
files

Such as ClassName.class and


ClassName$InnerClassName.class

144

Nesting Inner Classes

It is legal to nest inner classes within inner classes


The rules are the same as before, but the names get longer
Given class A, which has public inner class B, which has public inner class
C, then the following is valid:

A aObject = new A();


A.B bObject = aObject.new B();
A.B.C cObject = bObject.new C();

145

Inner Classes and Inheritance

Given an OuterClass that has an InnerClass


Any DerivedClass of OuterClass will automatically have
InnerClass as an inner class
In this case, the DerivedClass cannot override the InnerClass

146

An outer class can be a derived class


An inner class can be a derived class also

Anonymous Classes
If an object is to be created, but there is no need to name the object's class,
then an anonymous class definition can be used
The class definition is embedded inside the expression with the new
operator
An anonymous class is an abbreviated notation for creating a simple local
object "in-line" within any expression, simply by wrapping the desired
code in a "new" expression.
Anonymous classes are sometimes used when they are to be assigned to a
variable of another type
The other type must be such that an object of the anonymous class is also
an object of the other type
The other type is usually a Java interface
Not every inner class should be anonymous, but very simple "one-shot"
local objects are such a common case that they merit some syntactic sugar.

147

Anonymous Classes

148

Anonymous Classes

149

Anonymous Classes

150

Packages
( Putting Classes Together )

Introduction
The main feature of OOP is its ability to support the reuse of code:
Using the classes ( directly )
Extending the classes (via inheritance)
Extending interfaces

The features in basic form limited to reusing the classes within a program.

What if we need to use classes from other programs without physically copying
them into the program under development ?

In Java, this is achieved by using what is known as packages, a concept


similar to class libraries in other languages.

Defining Packages
Packages are Javas way of grouping a number of related classes and/or interfaces
together into a single unit. That means, packages act as containers for classes.

The benefits of organising classes into packages are:


The classes contained in the packages of other programs/applications can be
reused.

In packages classes can be unique compared with classes in other packages, i.e,
two classes in two different packages can have the same name. If there is a
naming clash, then classes can be accessed with their fully qualified name.

Classes in packages can be hidden if we dont want other packages to access


them ( using access specifier ).

Contd..

In general, a Java source file can contain any (or all) of the following four
internal parts:
A single package statement (optional).
Any number of import statements (optional).
A single public class declaration (required).
Any number of classes private to the package (optional).

Java packages are classified into 2 types:


1.Java API(Application Programming Interface) packages (or) Predefined
packages (or) Built-in packages.
-these packages are defined by the system.
-ex: java.io, java.utill etc..
2.User defined packages:
-these packages are defined by the user

Java Foundation Packages


Java provides a large number of classes grouped into different packages
based on their functionality.
The six foundation Java packages are:

java.lang
Contains classes for primitive types, strings, math functions,
threads, and exception
java.util
Contains classes such as vectors, hash tables, date etc.
java.io
Stream classes for I/O
java.awt
Classes for implementing GUI windows, buttons, menus etc.
java.net
Classes for networking
java.applet
Classes for creating and implementing applets

Creating Packages
To create a package is quite easy: simply include a package command as the first
statement in a Java source file.
Any classes declared within that file will belong to the specified package.
The package statement defines a name space in which classes are stored.
If you omit the package statement, the class names are put into the default
package, which has no name.

This is the general form of the package statement:


Syntax:
Example:

Java uses file system directories to store packages.

package pkgname;
package MyPackage;

package myPackage;
public class ClassA {
// class body
}
class ClassB {
// class body
}
More than one file can include the same package statement.
You can create a hierarchy of packages.
To do so, simply separate each package name from the one above it by use of a
period.
The general form of a multileveled package statement is shown here:
package pkg1[.pkg2[.pkg3]];
A package hierarchy must be reflected in the file system of your Java development
system.

Creating Sub Packages


As packages in Java are organised hierarchically, sub-packages can be
created as follows:
package myPackage.Math
package myPackage.secondPakage.thirdPackage

A package hierarchy must be reflected in the file system.

Store thirdPackage in a subdirectory named myPackage\secondPackage.


Store secondPackage and Math class in a subdirectory myPackage.

How to make a class Belong to a Package


Include a proper package statement as first line in source file
Make class S1 belongs to mypackageA

package mypackage.mypackageA;
public class S1
{
public S1( )
{
System.out.println("This is Class S1");
}
}
Name the source file as S1.java and compile it and
store the S1.class file in mypackageA directory

Make class S2 belongs to mypackageA

package mypackage.mypackageA;
public class S2
{
public S2( )
{
System.out.println("This is Class S2");
}
}
Name the source file as S2.java and compile it and
store the S2.class file in mypackageA directory

Make class A belongs to IJK

package mypackage.mypackageB.IJK;
public class A
{
public A( )
{
System.out.println("This is Class A in IJK");
}
}
Name the source file as A.java and compile it and
store the A.class file in IJK directory

<< Same Procedure For all classes>>

Accessing Classes from Packages


There are two ways of accessing the classes stored in packages:

Using fully qualified class name

java.lang.Math.sqrt(x);

Import package and use class name directly.

import java.lang.Math
Math.sqrt(x);

Selected or all classes in packages can be imported:

import
package.class;
Implicit in all programs:
import
java.lang.*;
package statement(s)import
must appear
first
package.*;

Finding Packages and CLASSPATH


How does the Java run-time system know where to look for packages that you
create?
The answer has two parts:
First, by default, the Java run-time system uses the current working directory as its
starting point. Thus, if your package is in the current directory, or a subdirectory of
the current directory, it will be found.
Second, you can specify a directory path or paths by setting the CLASSPATH
environmental variable.
For example, consider the following package specification.
package MyPack;
In order for a program to find MyPack, one of two things must be true.
Either the program is executed from a directory immediately above MyPack, or
CLASSPATH must be set to include the path to MyPack.

// A simple package
//AccountBalance.java
class AccountBalance {
package MyPack;
public static void main(String args[]) {
class Balance {
Balance current[] = new Balance[3];
String name;
current[0] = new Balance("K. J. Fielding", 123.23);
double bal;
current[1] = new Balance("Will Tell", 157.02);
current[2] = new Balance("Tom Jackson", -12.33);
Balance(String n, double b){
for(int i=0; i<3; i++)
name = n;
current[i].show();
bal = b;
}
}
}
void show() {
if(bal<0)
System.out.print("-->
");
//To compile
System.out.println(name + ":
javac AccountBalance.java
$" + bal);
}
//To run
}
java MyPack.AccountBalance
//java AccountBalance

invalid

Access Control
Java addresses four categories of visibility for class members:
Subclasses in the same package.

Non-subclasses in the same package.

Subclasses in different packages.

Classes that are neither in the same package nor subclasses.

A class has only two possible access levels: default and public.

Class Member Access

//VarProtection.java
package pack1;
public class VarProtection {
int n = 1;
private int pri = 2;
protected int pro = 3;
public int pub = 4;
public VarProtection() {
System.out.println("Individual class constructor");
System.out.println("default value is: " + n);
System.out.println("private value is: " + pri);
System.out.println("protected value is: " + pro);
System.out.println("public value is: " + pub);
}
}

To Compile:
d:\>javac d . VarProtection.java

//SameSub .java:
package pack1;
class SameSub extends VarProtection{
SameSub(){
System.out.println("subclass constructor");
System.out.println("default value is: " + n);
// System.out.println("private value is: " + pri);
System.out.println("protected value is: " + pro);
System.out.println("public value is: " + pub);
}
}

To Compile:
d:\>javac d . SameSub.java

// SameDiff.java
package pack1;
class SameDiff{
SameDiff(){
VarProtection v1 = new VarProtection();
System.out.println("Delegationclass constructor");
System.out.println("default value is: " +v1. n);
// System.out.println("private value is: " +v1. pri);
System.out.println("protected value is: " +v1. pro);
System.out.println("public value is: " + v1.pub);
}
}

To Compile:
d:\>javac d . SameDiff.java

//OtherSub.java
package pack2;
import pack1.*;
class OtherSub extends VarProtection{
OtherSub(){
System.out.println("Different Package subclass constructor");
//System.out.println("default value is: " + n);
// System.out.println("private value is: " + pri);
System.out.println("protected value is: " + pro);
System.out.println("public value is: " + pub);
}
}

To Compile:
d:\>javac d . OtherSub.java

// OtherDiff.java
package pack2;
import pack1.*;
class OtherDiff{
OtherDiff(){
VarProtection v2=new VarProtection();
System.out.println("Different Package non-subclass
constructor");
// System.out.println("default value is: " +v2. n);
// System.out.println("private value is: " + v2.pri);
// System.out.println("protected value is: " + v2.pro);
System.out.println("public value is: " + v2.pub);
}
}

To Compile:
d:\>javac d . OtherDiff.java

To Compile:
// Demo package p1.
d:\>javac d . MainTest.java
package pack1;
To Run:
class MainTest{
d:\>java pack1.MainTest
public static void main(String
args[]){
VarProtection v=new
VarProtection();
SameDiff s2=new
SameDiff();
SameSub s1=new
SameSub();
package pack2;
}
import pack1.*;
}
class OtherMainTest{
public static void main(String
args[]){
OtherSub os=new
OtherSub();
To Compile:
OtherDiff od=new
d:\>javac d . OtherMainTest.java
OtherDiff();
To Run:
}
d:\>java pack2.OtherMainTest
}

Importing Packages
There are no core Java classes in the unnamed default package; all of the standard
classes are stored in some named package.

Java includes the import statement to bring certain classes, or entire packages,
into visibility.
Once imported, a class can be referred to directly, using only its name.
In a Java source file, import statements occur immediately following the
package statement (if it exists) and before any class definitions.
This is the general form of the import statement:
import pkg1[.pkg2].(classname|*);

Here, pkg1 is the name of a top-level package, and pkg2 is the name of a
subordinate package inside the outer package separated by a dot (.).

There is no practical limit on the depth of a package hierarchy, except that


imposed by the file system.
Finally, you specify either an explicit classname or a star (*), which indicates that
the Java compiler should import the entire package.
This code fragment shows both forms in use:

import java.util.Date;
import java.io.*;

All of the standard Java classes included with Java are stored in a package called
java.
The basic language functions are stored in a package inside of the java package
called java.lang.
Normally, you have to import every package or class that you want to use, but
java.lang is implicitly imported by the compiler for all programs.
This is equivalent to the following line being at the top of all of your programs:
import java.lang.*;

When a package is imported, only those items within the package declared as public will
be available to non-subclasses in the importing code. For example, if you want the
Balance class of the package MyPack shown earlier to be available as a stand-alone
class for general use outside of MyPack, then you will need to declare it as public and
put it into its own file, as shown here:
package MyPack;
public class Balance {
String name;
double bal;
public Balance(String n, double b) {
name = n;
bal = b;
}
public void show() {
if(bal<0)
System.out.print("--> ");
System.out.println(name + ": $" + bal);
}
}

import MyPack.*;
class TestBalance {
public static void main(String args[]) {
/* Because Balance is public, you may use Balance
class and call its constructor. */
Balance test = new Balance("J. J. Jaspers", 99.88);
test.show(); // you may also call show()
}
}
As an experiment, remove the public specifier from the Balance class and then
try compiling TestBalance. As explained, errors will result.

5.Define a package with name sortapp in which declare an interface


SortInterface with method sort () whose return type and parameter type
should be void and empty.
Define subsortapp as sub package of sortapp package in which define
class SortImpl implementing SortInterface in which sort() method should
print a message Linear sort is used.
Define a package searchingapp in which declare an interface
SearchInterface with search () method whose return type and parameter list
should be void and empty respectively.
Define serachingimpl package in which define a SearchImpl class
implementing SearchInterface defined in searchingapp package in which
define a search() method which should print a message linear search is used.
Define a class ExecutePackage with main method using the above packages
(classes and its methods).

package sortapp;
public interface SortInterface{
void sort();
}

//Save file with SortInterface.java


complile:
javac d . SortInterface.java

package sortapp.subsortapp;
import sortapp.*;
public class SortImpl implements SortInterface{
public void sort(){
System.out.println("linear sort is used");
}
}

//Save file with SortImpl.java


complile:
javac d . SortImpl.java

package searchingapp;
public interface SearchInterface{
void search();
}

//Save file with SearchInterface.java


complile:
javac d . SearchInterface.java

package searchingimpl;
import searchingapp.*;
public class SearchImpl implements SearchInterface{
public void search(){
System.out.println("lenear search is used");
}
}

//Save file with SearchImpl.java


complile:
javac d . SearchImpl.java

import sortapp.subsortapp.SortImpl;
import searchingimpl.SearchImpl;
public class ExecutePackage
{
public static void main(String a[]){
SortImpl s1=new SortImpl();
s1.sort();
SearchImpl s2=new SearchImpl();
s2.search();
}
}

//Save file with ExecutePackage.java


complile: javac ExecutePackage.java
Execution: java ExecutePackage

Write a program to check whether the given string is


palindrome or not.
Write a program for sorting a given list of names in ascending
order.
1.

2.

1.Write a program to check whether the given string is palindrome or not.


import java.io.*;
import java.lang.*;
class Palindrom{
public static void main(String args[]){
int p=0;
int n=args[0].length();
for(int i=0;i<n;i++){
if(args[0].charAt(i)!=args[0].charAt(n-i-1))
p=1;
}
if(p==0)
System.out.println("The given String is a Palindrome");
else
System.out.println("The given String is not a Palindrome");
}
}

Write a program for sorting a given list of names in ascending order.


import java.io.*;
class StringSort{
public static void main(String args[]){
String name[]=new String[5];
for (int i = 0; i < args.length; i++){
name[i]=args[i];
}
int size=args.length;
System.out.println(size);
for(int i=0;i<size;i++){
for(int j=i+1;j<size;j++){
if(name[i].compareTo(name[j])>0){
String temp=name[i];
name[i]=name[j];
name[j]=temp;
}
}
}
for(int i=0;i<size;i++){
System.out.println(name[i]);
}
}
}

III UNIT
Exception handling Dealing with errors, benefits of exception
handling, the classification of exceptions- exception hierarchy,
checked exceptions and unchecked exceptions, usage of try,
catch, throw, throws and finally, re throwing exceptions, exception
specification, built in exceptions, creating own exception sub
classes.
Multithreading - Differences between multiple processes and
multiple threads, thread states, creating threads, interrupting
threads, thread priorities, synchronizing threads, inter-thread
communication, producer consumer pattern.

188

Objectives
To know what is exception and what is exception handling.
To distinguish exception types: Error (fatal) vs. Exception (nonfatal), and checked vs. uncheck exceptions.
To declare exceptions in the method header.
To throw exceptions out of a method.
To write a try-catch block to handle exceptions.
To explain how an exception is propagated.
To rethrow exceptions in a try-catch block .
To use the finally clause in a try-catch block.
To know when to use exceptions.
To know differences between multiple processes and multiple
threads
To know thread states
To know the creating threads, interrupting threads
To know thread priorities
To know the synchronizing threads
To know inter-thread communication producer consumer pattern.
189

Compile Time, Run Time, Logical Errors


Compile Time Errors: These are the errors due to wrong syntax or grammar.
These are detected by java compiler at compile time.
Run Time Errors: These are the errors due to inefficiency of computer
system to execute a statement. These errors are memory and execution of
the processor.

Logical Errors: These are the errors committed by the programmer in the
logic of the program. These errors are not detected by the compiler or
interpreter.

190

Exception
The Runtime error is called Exception.

Exception is an abnormal condition that interrupts the flow of


execution and the control comes out of the program.
Such an abnormal condition corrupts some private or confidential
files.

191

Exception Handling
During a Program execution an unexpected situation such as inability to

find a file or problem In network connectivity may arise. Such situations


are known as Exception events or Error conditions or Exceptions.
Exception Handling means to handle the exceptions by the programmer
to recover the computer from malfunction due to exception.
In java Exception handling is done using 5 keywords.
Try
Catch
Throw
Throws
finally

192

Exception Handling
In java Exceptions are objects. There is a predefined class called Exception
in java.lang package. This is the super class for all exceptions.
Ex: 1. class ExceptionDemo
2. {
3.
public static void main(String args[])
4.
{
5.
int a=5/0;
6.
System.out.println(a=+a);
7.
}
8. }

The division of any value by zero is not defined in java. So this line (5th
line)
will throw the Divide by Zero Exception.
At Line no.5 an Arithmetic Exception class object is created and thrown
out of the main method and the execution stops.
193

Benefits of Exception Handling


Exception handling mechanism can be effectively used to locate the type
and place of errors. It is used to handle exceptions.
The try-catch clauses used in Exception handling helps in seperating the
working & Functional coding from the Error handling code.
Used to grouping error types
No abnormal termination of program
When program contains any errors it will show non technical messages
with stopping execution.

194

Termination & Resumptive Models


If the invoker can continue its execution after the
exception has been handled then it may be possible for
the handler to cure the problem that caused the
exception to be raised and for the invoker to resume as
if nothing has happened
This is referred to as the resumption or notify model
The model where control is not returned to the invoker
is called termination or escape
Clearly it is possible to have a model in which the
handler can decide whether to resume the operation
which caused the exception, or to terminate the
operation; this is called the hybrid model

195

Exception Hierarchy
The Exception hierarchy consists of all possible exceptions that can occur
in a java program.
The Throwable is the super class for all exceptions and it is the subclass
of Object class.
The Throwable inturn has two subclasses Exception and Error.

196

Types of Exceptions
A. Unchecked Exceptions
All Exceptions that extend the RuntimeException or any one of its
subclass are unchecked exceptions
Unchecked Exceptions are unchecked by compiler.
Whether you catch the exception or not compiler will pass the compilation
process.
If Unchecked exception is caught then exception handling code will be
executed and programs execution continues.
If Unchecked exception is not caught then java interpreter will provide the
default handler. But in this case execution of the program will be stopped
by displaying the name of the exceptions object.

197

UncheckedExceptions Example
class Exceptiondemo1
{
public static void main(String arhs[])
throws ArithmeticException
{
int a=10;
int b= 5;
int c =5;
No Need to mention for
int x = a/(b-c);
Unchecked Exceptions
System.out.println("c="+c);
int y = a/(b+c);
System.out.println("y="+y);
Can Throw an Exception
}
} D:\java>javac Exceptiondemo1.java << Compilation Step Pass>>
D:\java>java Exceptiondemo1
Exception in thread "main"
java.lang.ArithmeticException: / by zero
at Exceptiondemo1.main(Exceptiondemo1.java:8)
199

Example 2 (Unchecked Exceptions)


class Exceptiondemo2
{
public static void main(String args[])
{
double a= Double.parseDouble(args[0]);
}
}

Can throw either


ArrayIndexOutOfBoundsException
OR
NumberFormatException

D:\java>javac Exceptiondemo2.java
D:\java>java Exceptiondemo2
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Exceptiondemo2.main(Exceptiondemo2.java:5)
D:\java>java Exceptiondemo2 pankaj
Exception in thread "main" java.lang.NumberFormatException: For input string:
"pankaj at
sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:12 24)
at java.lang.Double.parseDouble(Double.java:482)
at Exceptiondemo2.main(Exceptiondemo2.java:5)
200

Unchecked Exception
Put the Related/Dependent Statements in try block

class extest
{
public static void main(String args[])
{
try
{
int a =Integer.parseInt(args[0]);
int b = a+10;
System.out.println("b="+b);
}
catch(Exception e) {}
}
}
201

Types of Exceptions
B. checked Exceptions

All Exceptions that extends the Exception or any one its


subclass except RunTimeException class are checked
exceptions
Checked Exceptions are checked by the Java compiler.
There are two approaches that a user can follow to deal with
checked exceptions

202

Handling Checked Exceptions


Inform the compiler that a method can throw an Exception.

Catch the checked exception in try catch block


If Checked exception is caught then exception handling code
will be executed and programs execution continues.
If Checked exception is not caught then java interpreter will
provide the default handler. But in this case execution of the
program will be stopped by displaying the name of the
exceptions object.

203

Checked Exceptions

/* Program to read two integers Display their sum */


import java.io.*;
class Exceptiondemo3
{
public static void main(String args[])
{
DataInputStream in=new DataInputStream(System.in);

int a = Integer.parseInt(in.readLine());
int b = Integer.parseInt(in.readLine());
System.out.println("Sum is :"+(a+b));
}
}
Exceptiondemo3.java:9: unreported exception java.io.IOException; must be caught or declared
to be thrown
int a = Integer.parseInt(br.readLine());
^
Exceptiondemo3.java:10: unreported exception java.io.IOException; must be caugh or
declared to be thrown
int b = Integer.parseInt(br.readLine());
^
205

Ways To Handle Checked Exceptions


Method 1: << Mention thru throws clause>>
import java.io.*;
class Exceptiondemo3
{
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new inputStreamReader(System.in));

int a = Integer.parseInt(br.readLine());
int b = Integer.parseInt(br.readLine());
System.out.println("Sum is :"+(a+b));
}
}

1.throws clause is used with methods to indicate type of Exception a method can throw
2.Specifically required for Checked Exceptions [ To Pass Compilation process]. It can/may be used
for unchecked exceptions also.
3.A method can throw as many exceptions.
206

Method 2 << Put the statements in try catch block and catch >>
import java.io.*;
class Exceptiondemo3
{
public static void main(String args[])
{
DataInputStream in = new DataInputStream(System.in);

try {
int a = Integer.parseInt(in.readLine());
int b = Integer.parseInt(in.readLine());
System.out.println("Sum is :"+(a+b));
}
catch(IOException e) { }
}
}

207

Exception Handling
Exception Handling Requires the Following four steps
1.Finding the problem (Identify the statements whose execution
may result in Exception. Put all those statements in a try{..}
block)
2.Inform that an exception is thrown (Throw the Exception)
3.Receive the exception ( Catch the exception using catch{..}
block)
4.Provide exception handling code in catch block.

208

Exception Hadling Syntax


try
{
<statements that can throw exceptions>
}
catch(ExceptionType<1> e1) {.}
catch(ExceptionType<2> e2) {.}
catch(ExceptionType<3> e3) {.}
..
catch(ExceptionType<N> e4) {.}

Important Points :
1.try {} block may have one or multiple
statements.
2. try{} block may throw a single type of
Exception or multiple exceptions. But at a
time it can throw only single type of
exception.
3. There can be multiple catch() { .. } blocks
associated with single try{} block.
4. If try{} block can throw multiple exceptions
then user should catch all exceptions. (one
catch block for each type of exception)

209

Catching an Exception
class Exceptiondemo1
{
public static void main(String args[])
{
int a=10;
int b= 5;
int c =5;
try
{
int x = a/(b-c);
D:\java>java Exceptiondemo1
System.out.println("c="+c);
java.lang.ArithmeticException: / by zero
}
y=1
catch(ArithmeticException e)
{
System.out.println(e.toString());
}
int y = a/(b+c);
System.out.println("y="+y);
}
}

210

Catching Multiple Exceptions


class Exceptiondemo4
{
public static void
main(String args[])
{
int a[]= {5,10};
try
{
int b=
Integer.parseInt(args[0]);
int x = a[b]/(b-a[1]);
System.out.println("x="+x);
}

catch(ArithmeticException e)
{
System.out.println(e.toString());
}
catch(NumberFormatException e)
{
System.out.println(e.toString());
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e.toString());
}
System.out.println("Hello This is Exception Test");
} // End of main() method
}// End of class Exceptiondemo4

211

OUTPUT
What will be o/p if you execute it like
1.Java Exceptiondemo4
2.java Exceptiondemo4 1
3.3. java exceptiondemo4 oop

NO COMMAND LINE ARGUMENTS

COMMAND LINE ARGUMENTS


PASSED AS 1
COMMAND LINE ARGUMENT
PASSED oop

212

Nested Try Statements


Try{ } statements can be nested. One try block may contain another try
block
In case of nested try blocks, context of that exception is pushed onto stack.
Inner try block may/or may not have catch statements associated with it.
If an exception is thrown from inner try block then first inner catch
statements are matched (if present) . If no match is found then outer try
block are matched. If there also no match found then default handler will be
invoked.
However, if outer try block throws the exception then only outer try blocks
are matched.

213

Syntax for Nested try Statements


try
{
Statement A;
Statement B;
try
{
Statement C;
Statement D;
}
catch(CException e) { . }
catch(DException e) { . }
}
catch(AException e) { . }
catch(BException e) { . }

or

try
{
Statement A;
Statement B;
try
{
Statement C;
Statement D;
}
}
catch(AException e) {
catch(BException e) {
catch(CException e) {
catch(DException e) {

.
.
.
.

}
}
}
}

214

class nestedtry
{
public static void main(String args[])
{
int a[] = { 2,5,6};
try // outer try
{
int b = Integer.parseInt(args[0]);
try // inner try
{
int c[] = { 4,5,6};
int d = c[b]/(c[b]-4);
} // End of inner try
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Exception : "+ e.toString());
System.out.println("By Inner try");
}
catch(ArithmeticException e)
{
System.out.println("Exception : "+ e.toString());
System.out.println("By Inner try");
}
} // End of outer try

215

// Catch Blocks for outer try


catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Exception : "+
e.toString());
System.out.println("By Outr try");
}
catch(NumberFormatException e)
{
System.out.println("Exception : "+
e.toString());
System.out.println("By Outer try");
}
} // End of main
} // End of class

D:\java>java nestedtry
Exception :
java.lang.ArrayIndexOutOfBoundsException: 0
By Outer try
D:\java>java nestedtry 4
Exception : java.lang.ArrayIndexOutOfBoundsException: 4
By Inner try

216

Writing Your Own Exceptions


Programmers Can write their own Exception classes apart from javas library
Exceptions.
Programmer can write either checked Exception OR Unchecked Exception.
To make a checked exception , make your exception class a subclass of
Exception OR any one of its subclass EXCEPT RunTimeException.

class AException extends Exception { }


Checked Exception
class BException extends IOException { ..} Checked Exception

To make a Unchecked exception , make your exception class a subclass of


RunTimeException OR any one of its subclass .
class
class
class
class

XException
YException
ZException
ZException

extends
extends
extends
extends

RunTimeException { }
AritmeticException { }
ArrayIndexOutOfException { }
IndexOutOfBoundsException { }

217

Throwing Unchecked Exception


1.Create an InvalidBOXException which will be thrown
by the constructor of the BOX class whenever an
attempt will be made to create an invalid BOX object.
(Any Dimension = 0 or < 0).
2.Create an InvalidTriangleException which will be
thrown whenever an attempt will be made to create
an invalid Triangle object. (In Triangle sum of two
sides must be > third side).

218

EXAMPLE 1:
class InvalidBOXException extends RuntimeException
{
InvalidBOXException(String msg)
{
super(msg);
System.out.println("An attempt is made to create an Invalid BOx object ");
}
}
class BOX
Optional as InvalidBOXException is
{
Unchecked
private double length;
private double width;
private double height;
BOX(double l, double w, double h) throws InvalidBOXException
{
if( l <=0 || w <= 0 || h <= 0)
throw new InvalidBOXException("Invalid BOX Object creation");
length = l;
width = w;
height = h;
}
219

double getLength() { return length; }


double getWidth() { return width; }
double getHeight() { return height; }
double Area() { return 2*(length*width + width*height + height*length); }
double Volume() { return length*width*height ; }
}
class exceptiontest1
{
public static void main(String args[])
{

BOX b1 = new BOX(0,0,0);


BOX b2 = new BOX(10,4,5);

System.out.println(Area of b2:+b2.Area());
}
}
D:\java\bin>java exceptiontest1
An attempt is made to create an Invalid BOx object
Exception in thread "main" InvalidBOXException: Inavlid BOX Object
creation
at BOX.<init>(exceptiontest1.java:18)
at exceptiontest1.main(exceptiontest1.java:35)

220

Change of main method No 1


class exceptiontest1
{
public static void main(String args[])
{
try {
BOX b1 = new BOX(0,0,0);
System.out.println("Area of b1"+b1.Area());
}
// catch(InvalidBOXException e) { }
If these statements are out
catch(Exception e) { };
side try block?
try {
BOX b2 = new BOX(10,4,5);
System.out.println("Area of b2:"+b2.Area());
}
// catch(InvalidBOXException e) { }
catch(Exception e) {}; D:\java\bin>java exceptiontest1
}}
An attempt is made to create an Invalid BOx

object
Area of b2:220.0

221

Change of Main Method No 2


class exceptiontest1
{
public static void main(String args[])
{
BOX b1;
System.out.println(b1.Area());
}
}
class exceptiontest1
{
public static void main(String args[])
{
BOX b1 = null;
System.out.println(b1.Area());
}
}

<Compile Time Error>


D:\java\bin>javac exceptiontest1.java
exceptiontest1.java:36: variable b1 might
not have been initialized
System.out.println(b1.Area());
^
1 error

<RUNTIME Error>
D:\java\bin>java exceptiontest1
Exception in thread "main"
java.lang.NullPointerException
at
exceptiontest1.main(exceptiontest1.java:3
6)
222

Checked Exceptions
Make your exception class extends Exception class or any one of its
subclass except RumtimeException.
Checked Exceptions needs to either caught or informed by use of throws
clause
Note down that throw clause is used to throw the exception where as
throws clause is used to inform that an exception is thrown by the method.
Throw clause is used inside method body where as throws clause is used
with first line of the method.
Throws clause can be used to inform both type of exceptions. But in case a
method is throwing a unchecked exception then it is not compulsory to
inform.
In case a method is throwing a checked Exception, then it has either to
caught the exception or informs by using throws clause or it can do both.

223

EXAMPLE 1:
class InvalidBOXException extends Exception
Checked Exception
{
InvalidBOXException(String msg)
{
super(msg);
System.out.println("An attempt is made to create an Invalid BOx object ");
}
}
class BOX
{
Any Method or constructor which throws an
private double length;
checked Type Exception must inform it thru
private double width;
throws clause
private double height;
BOX(double l, double w, double h)
{
if( l <=0 || w <= 0 || h <= 0)
throw new InvalidBOXException("Inavlid BOX Object creation");
length = l;
width = w;
height = h;
}
224

double getLength() { return length; }


double getWidth() { return width; }
double getHeight() { return height; }
double Area() { return 2*(length*width + width*height + height*length); }
double Volume() { return length*width*height ; }
}
class exceptiontest1
{
public static void main(String args[])
{
BOX b1 = new BOX(0,0,0);
BOX b2 = new BOX(10,4,5);
System.out.println(Area of b2:+b2.Area());
}
}

D:\java\bin>javac exceptiontest1.java < Compile Time Error>


exceptiontest1.java:18: unreported exception InvalidBOXException; must be
caught or declared to be thrown throw new InvalidBOXException("Inavlid BOX
Object creation");
^
1 error
225

EXAMPLE 1:
class InvalidBOXException extends Exception
{
InvalidBOXException(String msg)
{
super(msg);
System.out.println("An attempt is made to create an Invalid BOx object ");
}
}

class BOX
{
private double length;
private double width;
private double height;
BOX(double l, double w, double h) throws InvalidBOXException
{
if( l <=0 || w <= 0 || h <= 0)
throw new InvalidBOXException("Inavlid BOX Object creation");
length = l;
width = w;
height = h;
}

226

double getLength() { return length; }


double getWidth() { return width; }
double getHeight() { return height; }
double Area() { return 2*(length*width + width*height + height*length); }
double Volume() { return length*width*height ; }
}
class exceptiontest1
{
public static void main(String args[]) throws InvalidBOXException
{
BOX b1 = new BOX(0,0,0);
BOX b2 = new BOX(10,4,5);
System.out.println(Area of b2:+b2.Area());
}
}

D:\java\bin>java exceptiontest1
An attempt is made to create an Invalid BOx object
Exception in thread "main" InvalidBOXException: Inavlid BOX Object creation
at BOX.<init>(exceptiontest1.java:18)
at exceptiontest1.main(exceptiontest1.java:36)
227

Use of finally Clause


finally statement can be used to handle an exception that is not caught by
previous statements.
finally block may be added immediately after try block or after the last catch
block.
finally block in general used to perform house keeping operations such as
closing files or releasing system resources.
Finally block when present is guaranteed to execute regardless of whether
an exception is thrown or not.
If you want then finally block can be used to handle any exception generated
within a try block.

228

finally clause Syntax


try
{
..
..
.
}
finally
{
..
..
.
}

try
{
..
..
.
}
catch(.)
{ . }
catch(..)
{ . }
..
..
finally
{
..
..
}
229

Example(finally clause)
class ex10
{
public static void main(String args[])
{
int a=10;
int b = 20;
try
{
int b1=Integer.parseInt(args[0]);
int x = a/(a-b1);
try
{
int y = b/(b-b1);
}
finally
{
System.out.println("Inner Block executed");
finally
}
{
}
System.out.println("Outer Block executed");
}
}
230
}

Output
D:\java\bin>java ex10
Outer Block executed
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at ex10.main(ex10.java:9)
D:\java\bin>java ex10 45
Inner Block executed
Outer Block executed
D:\java\bin>java ex10 10
Outer Block executed
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ex10.main(ex10.java:10)

D:\java\bin>java ex10 20
Inner Block executed
Outer Block executed
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ex10.main(ex10.java:13)

231

Difference between multithreading


and multitasking
Multiprocessing

Multithreading

More than one process running simultaneously.


More than one thread running simultaneously.
A multi-processing Operating System can run In a multithreaded application, there are several
several processes at the same time.
points of execution within the same memory
Each process has its own address/memory space space.
The OS's scheduler decides when each process is Each point of execution is called a thread.
executed Only one process is actually executing at hreads share access to memory
any given time.
However, the system appears to be running
several programs simultaneously
Separate processes to not have access to each
other's memory space

Its part of a program

Its part of a program

Its a heavy wait process

Its a light wait process

Process is divided into Threads

Threads are divided into sub threads

There is no communication between processors Within the process threads are communicated
directly
232

Why use Multithreading?


In a single threaded application, one thread of
execution must do everything
If an application has several tasks to perform, those tasks will be performed
when the thread can get to them.
A single task which requires a lot of processing can make the entire application
appear to be "sluggish" or unresponsive.

In a multithreaded application, each task can be


performed by a separate thread
If one thread is executing a long process, it does not make the entire application
wait for it to finish.

If a multithreaded application is being executed on a


system that has multiple processors, the OS may
execute separate threads simultaneously on separate
233
processors.

Thread Support in Java


Few programming languages directly support
threading
Although many have add-on thread support
Add on thread support is often quite cumbersome to use

The Java Virtual machine has its own runtime threads


Used for garbage collection

Threads are represented by a Thread class


A thread object maintains the state of the thread
It provides control methods such as interrupt, start, sleep, yield, wait

When an application executes, the main method is


executed by a single thread.
If the application requires more threads, the application must create them.

234

Thread Life Cycle


The life cycle of a thread contains several states .
Threads can be in one of four states
Created, Running, Blocked, and Dead

A thread's state changes based on:


Control methods such as start, sleep, yield, wait, notify
Termination of the run method

Thread()

Created

start()

notify()

Runnable

Blocked
sleep()
wait()

run() method terminates

Dead
235

How does a Thread run?


The thread class has a run() method
run() is executed when the thread's start() method is invoked

The thread terminates if the run method terminates


To prevent a thread from terminating, the run method must not end
run methods often have an endless loop to prevent thread termination

One thread starts another by calling its start method


The sequence of events can be confusing to those more familiar with a single threaded model.

Thread1

start()

Thread2

Thread Object
run()

236

Thread Life Cycle


The life cycle of a thread contains several states .
Threads can be in one of four states
Created, Running, Blocked, and Dead

A thread's state changes based on:


Control methods such as start, sleep, yield, wait, notify
Termination of the run method

Thread()

Created

start()

notify()

Runnable

Blocked
sleep()
wait()

run() method terminates

Dead
237

Creating Threads
Thread class constructors:
1.Thread ()
2.Thread (String Threadname )
3.Thread (Runnable obj)
4.Thread (Runnable obj, String name )
5.Thread (ThreadGroup tg,String Threadname )
Methods :
1. String getName (): It obtains the name of the thread .
2. Void setName (String str): It sets the name of the thread .
3. Int getPriority (): It obtains the priority of the thread .
4. Void set Priority(int ) : It sets the priority of the thread
5. Boolean is Alive( ): Determines if a thread is still running or not .It returns
true if the thread upon which it is called is still running ,else false.

238

Creating Threads
Thread class constructors:
1.Thread ()
2.Thread (String Threadname )
3.Thread (Runnable obj)
4.Thread (Runnable obj, String name )
5.Thread (ThreadGroup tg,String Threadname )
Methods :
1. String getName (): It obtains the name of the thread .
2. Void setName (String str): It sets the name of the thread .
3. Int getPriority (): It obtains the priority of the thread .
4. Void set Priority(int ) : It sets the priority of the thread
5. Boolean is Alive( ): Determines if a thread is still running or not .It returns
true if the thread upon which it is called is still running ,else false.

239

Creating Threads
Thread class constructors:
1.Thread ()
2.Thread (String Threadname )
3.Thread (Runnable obj)
4.Thread (Runnable obj, String name )
5.Thread (ThreadGroup tg,String Threadname )
Methods :
1. String getName (): It obtains the name of the thread .
2. Void setName (String str): It sets the name of the thread .
3. Int getPriority (): It obtains the priority of the thread .
4. Void set Priority(int ) : It sets the priority of the thread
5. Boolean is Alive( ): Determines if a thread is still running or not .It returns
true if the thread upon which it is called is still running ,else false.

240

Creating a New Thread


We can create a thread by instantiating an object of type Thread.
Java defines two ways in which this can be accomplished:
1. can implement the Runnable interface.
2. can extend the Thread class, itself.
1.Implementing Runnable
The easiest way to create a thread is to create a class that implements the Runnable
interface.
Runnable abstracts a unit of executable code.
You can construct a thread on any object that implements Runnable.
To implement Runnable, a class need only implement a single method called run( ),
Syntax:
public void run( )
Inside run( ), you will define the code that constitutes the new thread.
run( ) can call other methods, use other classes, and declare variables, just like the main
thread can.
The only difference is that run( ) establishes the entry point for another, concurrent thread
of execution within your program. This thread will end when run( ) returns.
Unit-6 JAVA Example program No. 1 Main Thread

241

After you create a class that implements Runnable, you will instantiate an object of
type Thread from within that class.
Thread constructors:
Thread(Runnable threadOb, String threadName)
After the new thread is created, it will not start running until you call its start( ) method,
which is declared within Thread.
start( ) executes a call to run( ).
Syntax:
void start()

Thread1

start()

Thread2

Thread Object

Runnable Object

run()

run()

Unit-6 JAVA Example program No. 2 NewThread

242

Threads
Extending Threads class:
The second way to create a thread is to create a new class that extends Thread, and then to
create an instance of that class.
The extending class must override the run( ) method, which is the entry point for the new
thread. It must also call start( ) to begin execution of the new thread.
Notice the call to super( ) inside NewThread. This invokes the following form of the
Thread constructor:
public Thread(String threadName)
Here, threadName specifies the name of the thread.

Unit-6 JAVA Example program No. 3 ExtendThread

243

Multiple Threads
Creating Multiple Threads
We can create as many threads as needed .

Unit-6 JAVA Example program No. 4 MultipleThread

244

Thread Priorities
Thread priorities are used by the thread scheduler to decide when each thread should be
allowed to run. In theory, higher-priority threads get more CPU time than lower-priority
threads.
It is possible to set priority to each thread b the user, by using the setPriority( ) method,
which is a member of Thread.
Syntax:
final void setPriority(int level)
level : System defined thread priorities :
Thread.MIN_PRIORITY
1
Thread.MAX_PRIORITY
10
Thread.NORM_PRIORITY
5
The default priority is Thread.NORM_PRIORITY
These Priorities are defined as static final variables within Thread .

Unit- 6 JAVA Example program No.5

PriorityThread
245

Synchronizing Threads
When two or more threads need access to a shared resource, they need some
way to ensure that the resource will be used by only one thread at a time. The
process by which this is achieved is called synchronization.
In Java, every object has a lock.
To obtain the lock, you must synchronize with the object.
The simplest way to use synchronization is by declaring one or more methods to
be synchronized
When a synchronized method is invoked, the calling thread attempts to obtain the
lock on the object.
if it cannot obtain the lock, the thread goes to sleep until the lock becomes
available
Once the lock is obtained, no other thread can obtain the lock until it is released.
ie, the synchronized method terminates
When a thread is within a synchronized method, it knows that no other
synchronized method can be invoked by any other thread
Therefore, it is within synchronized methods that critical data is updated
246

Interthread Communication producer consumer pattern


Consider the classic queuing problem, where one thread is producing some data and
another is consuming it. To make the problem more interesting, suppose that the producer
has to wait until the consumer is finished before it generates more data.
In a polling system, the consumer would waste many CPU cycles while it waited for the
producer to produce. Once the producer was finished, it would start polling, wasting more
CPU cycles waiting for the consumer to finish, and so on. Clearly, this situation is
undesirable.
To avoid polling, Java includes an elegant interprocess communication mechanism via the
following methods:
All three methods can be called only from within a synchronized context.
wait( ): This method tells the calling thread to give up the monitor and go to sleep until
some other thread enters the same monitor and calls notify( ).
notify( ): This method wakes up the first thread that called wait( ) on the same object.

notifyAll( ): This method wakes up all the threads that called wait( ) on the same object.c
The highest priority thread will run first.
247

Thread Groups

Thread groups allow collections of threads to be grouped together and manipulated as a


group rather than as individuals.
Thread groups also provide a means of restricting who does what to which thread.
Every thread in Java is a member of a thread group.
There is a default group associated with the main program, all created threads are placed in
this group (by default).
Thread Group is the class which supports the thread groups in Java.
When a thread creates a new thread group, it does so from within a thread group.
the new thread group is a child of the current thread group unless a different thread
group is passed as a parameter to the constructor.
Using the constructor methods in the ThreadGroup class allows hierarchies of thread
groups to be created.
Requests to destroy a thread group will be applied to all threads in the group.

248

Thread Groups
Methods that Operate on the ThreadGroup

getMaxPriority(), setMaxPriority(int)
getName() // name of the thread
getParent()
parentOf(ThreadGroup) // boolean
toString()
activeCount(),
activeGroupCount() // # of active descendent threads, and groups
suspend(); //deprecated; suspend all threads in this group.
resume();
stop();

Unit-6 JAVA Example program No.8 Thread Groups

249

Daemon Thread
Daemon thread in Java :
Are those thread which runs in background and mostly created by JVM for
performing background task like Garbage collection
Difference between Daemon and Non Daemon(User Threads)
In one line main difference between daemon thread and user thread is that as
soon as all user thread finish execution java program or JVM terminates itself,
JVM doesn't wait for daemon thread to finish there execution.

As soon as last non daemon thread finished JVM terminates no matter how
many Daemon thread exists or running inside JVM.
Daemon Thread are treated differently than User Thread when JVM terminates,
finally blocks are not called, and JVM just exits.

Unit-6 JAVA Example program No.9 DaemonThread

250

Unit-4

Collection Framework in Java


Introduction to Java Collection
Overview of Java collection Framework
Generics
Commonly used collection classes
ArrayList
Vector
Hashtable
Stack
Enumeration
Iterator
String Tokenizer
Random
Scanner
Calender and Properties

Introduction to Java Collection


A Collection is a container that groups similar elements into
an entity.
Examples would include a list of bank accounts, set of
students, group of telephone numbers.
The Collections framework in Java offers a unified approach to
store, retrieve and manipulate a group of data
Javas Collection framework has an intuitive approach when
compared to other complex frameworks such as C++

Introduction to Java Collection


The Java language API provides many of the data structures
from this class for you.
It defines a collection as an object that represents a group
of objects.
It defines a collections framework as a unified architecture
for representing and manipulating collections, allowing them
to be manipulated independent of the details of their
representation.
The Collections Framework provides a well-designed set of
interfaces and classes for storing and manipulating groups of
data as a single unit, a collection. -java.sun.com

The framework provides a convenient API to many of the


abstract data types familiar to computer science: maps, sets,
lists, trees, arrays, hashtables and other collections.

Introduction to Java Collection

Collection Interfaces - Represent different types of collections, such as sets, lists


and maps. These interfaces form the basis of the framework.

General-purpose Implementations - Primary implementations of the collection


interfaces.

Legacy Implementations - The collection classes from earlier releases, Vector and
Hashtable, have been retrofitted to implement the collection interfaces.

Wrapper Implementations - Add functionality, such as synchronization, to other


implementations.

Convenience Implementations - High-performance "mini-implementations" of the


collection interfaces.

Abstract Implementations - Partial implementations of the collection interfaces to


facilitate custom implementations.

Algorithms - Static methods that perform useful functions on collections, such as


sorting a list.

Infrastructure - Interfaces that provide essential support for the collection


interfaces.

Array Utilities - Utility functions for arrays of primitives and reference objects. Not,
strictly speaking, a part of the Collections Framework, this functionality is being
added to the Java platform at the same time and relies on some of the same
infrastructure.

Benefits
Helpful to developers by providing all standard data structures
algorithms to let the developer concentrate more on
functionality rather than the lower level details

Faster execution: with a range of options available for choice


of implementation. The framework aids in improving the
quality and performance of Java applications.
Code to interface: Since the collections framework is coded on
the principles of Code to Interface, it aids in inter-operability
between APIs that are not directly related.
Learning Curve: Easy to learn and start using Collections due
to the Code to Interface principles.

Core Collections Framework


The Collection framework forms a suitable
hierarchy:

Collection

Set

SortedSet

List

Map

Queue

SortedMap

Core Collections Framework


The java.util package also contains one of Javas most powerful
subsystems
The Collections Framework is a sophisticated hierarchy of interfaces
and classes that provide state-of-the-art technology for managing
groups of objects.
The core Collections framework is very generic in nature and
provides a standard interface to all operations that can be
performed.
For example the root interface Collection is declared as public
interface Collection <E>
E represents a generic object.

Collection: This interface is pretty much used in declarations


and method signatures so any type of Collections can be
passed around.

Core Collections Framework


list of its classes

AbstractCollection
AbstractList
AbstractMap
AbstractQueue
AbstractSequential
AbstractSet
ArrayDeque
ArrayList
Arrays Linked
BitSet Linked
Calendar
Collections
Currency
Date
Dictionary
EnumMap
EnumSet
EventListenerProxy

EventObject
FormattableFlags
Formatter
GregorianCalendar
List HashMap
HashSet
Hashtable
IdentityHash
HashMap
HashSet
LinkedList
ListResourceBundle
Locale
Observab
PriorityQueue
Properties
PropertyPermission
PropertyResourceBundle

Random
ResourceBundle
Scanner
ServiceLoader
SimpleTimeZone
Stack
StringTokenizer
Map Timer
TimerTask
TimeZone
TreeMap
TreeSet
UUID
Vector
WeakHashMap

The interfaces defined by java.util

Collection
List Queue
Comparator
ListIterator
RandomAccess
Deque (Added by Java SE 6.)
Map Set
Enumeration
Map.Entry
SortedMap
EventListener
NavigableMap (Added by Java SE 6.)
SortedSet
Formattable
NavigableSet (Added by Java SE 6.)
Iterator
Observer

ArrayList
ArrayList Class:
ArrayList Implements a dynamic array by extending AbstractList.

The ArrayList class extends AbstractList and implements the List interface.
ArrayList is a generic class that has this declaration:

class ArrayList<E>
Here, E specifies the type of objects that the list will hold.

ArrayList supports dynamic arrays that can grow as needed.


An ArrayList is a variable-length array of object references.
An ArrayList can dynamically increase or decrease in size.
Array lists are created with an initial size. When this size is exceeded, the
collection is automatically enlarged.
When objects are removed, the array can be shrunk.

ArrayList
ArrayList has the constructors shown here:
ArrayList( )
ArrayList(Collection<? extends E> c)
ArrayList(int capacity)
The first constructor builds an empty array list.
The second constructor builds an array list that is
initialized with the elements of the collection c.
The third constructor builds an array list that has the
specified initial capacity.
The capacity is the size of the underlying array that is
used to store the elements.
The capacity grows automatically as elements are
added to an array list.

// Demonstrate ArrayList.

ArrayList

import java.util.*;
class ArrayListDemo {
public static void main(String args[]) {
// Create an array list.
ArrayList<String> al = new ArrayList<String>();
System.out.println("Initial size of al: " +al.size());
// Add elements to the array list.
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions: " +al.size());
// Display the array list.
System.out.println("Contents of al: " + al);
// Remove elements from the array list.
al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: " +al.size());
System.out.println("Contents of al: " + al);
}
}

ArrayList
The output from this program
Initial size of al: 0
Size of al after additions: 7
Contents of al: [C, A2, A, E, B, D, F]
Size of al after deletions: 5
Contents of al: [C, A2, E, B, D]

Vector
Vector implements a dynamic array.
It is similar to ArrayList, but with two differences:
Vector is synchronized, and it contains many legacy methods
that are not part of the Collections.
Framework.
Vector was reengineered to extend AbstractList and to
implement the List interface.
A Vector can have its contents iterated by the enhanced for
loop.

Vector is declared like this:


class Vector<E>
Here, E specifies the type of element that will be stored.

Vector constructors:
Vector( )
Vector(int size)
Vector(int size, int incr)
Vector(Collection<? extends E> c)
The first form creates a default vector, which has an initial size of 10.
The second form creates a vector whose initial capacity is specified by
size.
The third form creates a vector whose initial capacity is specified by
size and whose increment is specified by incr.
The increment specifies the number of elements to allocate each time
that a vector is resized upward.
The fourth form creates a vector that contains the elements of
collection c.

Vector defines these protected data members:

int capacityIncrement;
int elementCount;
Object[ ] elementData;
The increment value is stored in capacityIncrement.
The number of elements currently in the vector is stored in
elementCount.
The array that holds the vector is stored in elementData.

Methods Defined by Vector


void addElement(E element) : The object specified by
element is added to the vector.
int capacity( ) : Returns the capacity of the vector.
Object clone( ) : Returns a duplicate of the invoking vector.
boolean contains(Object element) : Returns true if element is
contained by the vector,
and returns false if it is not.
Etc.

// Demonstrate various Vector operations.


import java.util.*;
class VectorDemo {
public static void main(String args[]) {
// initial size is 3, increment is 2
Vector<Integer> v = new Vector<Integer>(3, 2);
System.out.println("Initial size: " + v.size());
System.out.println("Initial capacity: " +v.capacity());
v.addElement(1);
v.addElement(2);
v.addElement(3);
v.addElement(4);
System.out.println("Capacity after four additions: " +v.capacity());
v.addElement(5);
System.out.println("Current capacity: " +v.capacity());
v.addElement(6);

v.addElement(7);
System.out.println("Current capacity: " +v.capacity());
v.addElement(9);
v.addElement(10);
System.out.println("Current capacity: " +v.capacity());
v.addElement(11);
v.addElement(12);
System.out.println("First element: " + v.firstElement());
System.out.println("Last element: " + v.lastElement());
if(v.contains(3))
System.out.println("Vector contains 3.");
// Enumerate the elements in the vector.
// Use an enhanced for loop to display contents.
System.out.println("\nElements in vector:");
for(int i : v)
System.out.print(i + " ");
System.out.println();
}

Output:
Initial size: 0
Initial capacity: 3
Capacity after four additions: 5
Current capacity: 5
Current capacity: 7
Current capacity: 9
First element: 1
Last element: 12
Vector contains 3

Elements in vector:
1 2 3 4 5 6 7 9 10 11 12

UNIT-5

272

Events
An event is an Object that describes a state change in a Source.
Some of the activities that causes event to be generated are :
*Pressing a Button.
*Entering a character through Key Board.
*Selecting an item form a list etc.
Events may also occur that are not directly caused by interactions with
a user interface.
For example:
* An event may be generated when a timer expires
* A counter exceeds a value

273

Event Sources
A Source is an object that generates an event.
Some general Event Sources are:
Button
CheckBox
List
MenuItem
Window
TextItems,etc

274

Event Sources
A source must register listeners in order for the listeners to
receive notifications about a specific type of event. Each type
of event has its own registration method.
For implementing event listener we have to import the following
Statement:
import java.awt.event.*;

275

Event Sources
Here is a general form for adding a listener to an event source :
Public void assTyprListener(TypeEvent e)
* Type is the name of the event.
* e is the reference of the event listener.

Some sources may allow only one listener to register. The general form of such
a method is :
public void addTypeListener(TypeListener el)throws
java.util.TooManyListenersException

276

Event Sources
Some of the user interface components that can generate the events.
Event

Source Description

Button

Generates action events when the button is pressed.

Check box

Generates item events when the check box is selected or deselected

Choice

Generates item events when the choice is changed

List

Generates action events when an item is double-clicked; generates item


events when an item is selected or deselected.

Menu

Item Generates action events when a menu item is selected; generates item events
when a checkable menu item is selected or deselected.

Scroll bar

Generates adjustment events when the scroll bar is manipulated.

Text
components
Window

Generates text events when the user enters a character.


Generates window events when a window is activated, closed,
deactivated,deiconified, iconified, opened, or quit.

277

Event Classes
There are a number of event classes provided by
java.But we will discuss only some AWT event classes
here.
At the root of the Java event class hierarchy is
EventObject, which is in java.util. It is the
superclass for all events. Its one constructor is shown
here:
EventObject(Object src)
Here, src is the object that generates this event.

278

Event Classes
EventObject contains two methods:
getSource( )
toString( )
getSource( ): Returns the source of the event. Its
general form is shown here:

Object getSource( )
toString( ): Returns the string equivalent of the event.
Its general form is shown here:

String toString()

279

Event Classes
EventObject is a superclass of all events.
AWTEvent is a superclass of all AWT events that are
handled by the delegation event model.

getID( ) method can be used to determine the type of


the event. The signature of this method is shown
here:
int getID( )

280

Event Classes
Some AWT Event classes are listed below.
Event

Class Description

ActionEvent

Generated when a button is pressed, a list item is double-clicked, or a menu


item is selected

AdjustmentEvent

Generated when a scroll bar is manipulated

ComponentEvent

Generated when a component is hidden, moved, resized, or becomes visible

ContainerEvent

Generated when a component is added to or removed from a container.

FocusEvent

Generated when a component gains or loses keyboard focus

InputEvent

Abstract superclass for all component input event classes

ItemEvent

Generated when a check box or list item is clicked; also occurs when a choice selection is
made or a checkable menu item is selected or deselected.

KeyEvent

Generated when input is received from the keyboard

MouseEvent

Generated when the mouse is dragged, moved, clicked, pressed, or released;also generated
when the mouse enters or exits a component.

MouseWheelEvent

Generated when the mouse wheel is moved.

TextEvent.

Generated when the value of a text area or text field is changed

WindowEvent

Generated when a window is activated, closed, deactivated, deiconified,


iconified, opened, or quit

281

Event Listeners
A Listener is an object that is notified when an event
occurs.
It has two major requirements.
First, it must have been registered with one or more
sources to receive notifications about specific types of
events.
Second, it must implement methods to receive and
process these notifications.
For example:
MouseMotionListener Interface define two events:
*. When mouse is dragged.
* When mouse is moved.
282

Event Listeners
Interface
ActionListener
AdjustmentListener
ComponentListener
ContainerListener
FocusListener
ItemListener
KeyListener
MouseListener

MouseMotionListener
MouseWheelListener
TextListener
WindowFocusListener
WindowListener

Description
Defines one method to receive action events
Defines one method to receive adjustment events
Defines four methods to recognize when a component is hidden,
moved, resized, or shown.
Defines two methods to recognize when a component is added to
or removed from a container
Defines two methods to recognize when a component gains or loses
keyboard focus.
Defines one method to recognize when the state of an item changes
Defines three methods to recognize when a key is pressed, released,
or typed.
Defines five methods to recognize when the mouse is clicked, enters
a component, exits a component, is pressed, or is released.
Defines two methods to recognize when the mouse is dragged or
moved.
Defines one method to recognize when the mouse wheel is moved.
Defines one method to recognize when a text value changes.
Defines two methods to recognize when a window gains or loses
input focus.
Defines seven methods to recognize when a window is activated,
closed, deactivated, deiconified, iconified, opened, or quit.

283

Delegation Event Model


Event Delegation Model is based on four concepts:
* The Event Classes
* The Event Listeners
* Explicit Event Enabling
* Adapters
The modern approach to handling events is based on the
delegation event model, which defines standard and consistent mechanisms
to generate and process events. Its concept is quite simple: a source
generates an event and sends it to one or more listeners. In this scheme, the
listener simply waits until it receives an event. Once received, the listener
processes the event and then returns.
The advantage of this design is that the application logic that
processes events is cleanly separated from the user interface logic that
generates those events. A user interface element is able to "delegate the
processing of an event to a separate piece of code.
284

Delegation Event Model

285

Let us discuss about some Event classes which are useful.

ActionEvent Class: An ActionEvent is generated when a button is pressed,


a list item is double-clicked, or a menu item is selected.

The ActionEvent class defines four integer constants that can be


used to identify any modifiers associated with an action event:
ALT_MASK
CTRL_MASK,
META_MASK
SHIFT_MASK.
In addition, there is an integer constant, ACTION_PERFORMED,
which can be used to identify action events.

286

ActionEvent has these three constructors:


ActionEvent(Object src, int type, String cmd)
ActionEvent(Object src, int type, String cmd, int modifiers)
ActionEvent(Object src, int type, String cmd, long when, int modifiers)
*
*
*
*

src ----reference to the object that generated this event.


type---type of the event is specified
cmd--- its command string
modifiers----- modifier keys(ALT, CTRL, META, and/or SHIFT)
were pressed when the event was generated.
* when----Specifies when the event occurred

287

Methods present in ActionEvent Class:


String getActionCommand( )------ obtain the command name for
the invoking ActionEvent object
int getModifiers( )--------- returns a value that indicates which
modifier keys (ALT, CTRL,META, and/or SHIFT) were pressed when
the event was generated.
long getWhen( )---------- returns the time at which the event took
place

288

Action listeners are probably the easiest and most common


event handlers to implement.
To write an Action Listener follow the steps given below:

Declare an event handler class and specifyt that the class


either implements an ActionListener interface or extends the
a class that implements an ActionListener interface.
For ex:
public void Myclass implements ActionListener
{
}

289

Register an instance of the event handler class as a listener on


one or more components.

For ex:
Somecomponent.addActionListener(instance of myclasss);
Include code that implements the methods in listener interface.
For ex:
public void actionPerformed(ActionEvent e)
{
//code that reacts to the action
}

290

AdjustmentEvent Class: An AdjustmentEvent is generated by a


scroll bar.

The AdjustmentEvent class defines integer constants.


BLOCK_DECREMENT--- The user clicked inside the scroll bar to
decrease its value.
BLOCK_INCREMENT---- The user clicked inside the scroll bar to
increase its value.
TRACK
----The slider was dragged.
UNIT_DECREMENT ----The button at the end of the scroll bar was
clicked to decrease its value.
UNIT_INCREMENT------ The button at the end of the scroll bar was
clicked to increase its value.

291

AdjustmentEvent has one constructors:

AdjustmentEvent(Adjustable src, int id, int type, int data)


* src ----reference to the object that generated this event.
* id ----specifies the event.
* type---type of adjustment is specified
* data ----its associated data

292

Methods present in AdjustmentEvent Class:


Adjustable getAdjustable( ):returns the object that generated
the event
int getAdjustmentType( ) :returns type of the adjustment

event(any of its constants)


int getValue( ) :amount of the adjustment can be obtained

293

ComponentEvent Class: A ComponentEvent is generated when the


size, position, or visibility of a component is changed

The ComponentEvent class defines four integer constants.


COMPONENT_HIDDEN ---The component was hidden.
COMPONENT_MOVED ----The component was moved.
COMPONENT_RESIZED---- The component was resized.
COMPONENT_SHOWN----- The component became visible.

294

ComponentEvent has one constructors:

ComponentEvent(Component src, int type)


* src ----reference to the object that generated this event.
* type---type of the event is specified

ComponentEvent is the superclass either directly or indirectly of


ContainerEvent,FocusEvent, KeyEvent, MouseEvent, and
WindowEvent

295

Methods present in ComponentEvent Class:


Component getComponent( )---returns the component that
generated the event

296

ContainerEvent Class: A ContainerEvent is generated when a


component is added to or removed from a container.

The ContainerEvent class defines two integer constants.


COMPONENT_ADDED ---indicates that component has been added
COMPONENT_REMOVED--- indicates that component has been
removed

297

ContainerEvent has one constructors:

ContainerEvent(Component src, int type, Component comp)

* src ----reference to the object that generated this event.


* type---type of the event is specified
* comp---- component that has been added to or removed from the
container

298

Methods present in ComponentEvent Class:


Container getContainer( )-- obtains a reference to the
container that generated this event
Component getChild( )---- returns a reference to the
component that was added to or
removed from the container.

299

FocusEvent Class: A FocusEvent is generated when a component


gains or loses input focus.

The FocusEvent class defines two integer constants.


FOCUS_GAINED ---indicates that focus has been gained
FOCUS_LOST
--- indicates that focus has been lost

300

ContainerEvent has three constructors:

FocusEvent(Component src, int type)


FocusEvent(Component src, int type, boolean temporaryFlag)
FocusEvent(Component src, int type, boolean temporaryFlag,
Component other)
* src ----reference to the object that generated this event.
* type---type of the event is specified
* Temporaryvalue ---- is set to true if the focus event is temporary.
Otherwise, it is set to false.
* other--- the opposite component, is passed in other.
If a FOCUS_GAINED event occurred, other will refer to the component
that lost focus.
Conversely, if a FOCUS_LOST event occurred, other will refer to the
component
that gains focus
301

Methods present in FocusEvent Class:


Component getOppositeComponent( )--- The opposite
component is returned

boolean isTemporary( )---- The method returns true if the


change is temporary. Otherwise, it
returns false.

302

InputEvent Class:
The abstract class InputEvent is a subclass of ComponentEvent
and is the superclass for component input events. Its subclasses are
KeyEvent and MouseEvent.
The InputEvent class defines several integer constants.
Actual Modifiers:
ALT_MASK
BUTTON2_MASK
META_MASK
ALT_GRAPH_MASK
BUTTON3_MASK
SHIFT_MASK
BUTTON1_MASK
CTRL_MASK
Extended Modifiers:
ALT_DOWN_MASK
BUTTON2_DOWN_MASK
META_DOWN_MASK
ALT_GRAPH_DOWN_MASK
BUTTON3_DOWN_MASK
SHIFT_DOWN_MASK
BUTTON1_DOWN_MASK
CTRL_DOWN_MASK
303

Methods present in FocusEvent Class:


int getModifiers( )--- value that contains all of the original
modifier flags
int getModifiersEx( )--- obtain the extended modifiers

To test if a modifier was pressed at the time an event is


generated use the following methods:
boolean isAltDown( )
boolean isAltGraphDown( )
boolean isControlDown( )
boolean isMetaDown( )
boolean isShiftDown( )

304

ItemEvent Class: An ItemEvent is generated when a check box or a


list item is clicked or when a checkable menu item is selected or
deselected
The ItemEvent class defines two integer constants.
DESELECTED--- user deselected an item.
SELECTED ---- user selected an item

305

ItemEvent has one constructor:

ItemEvent(ItemSelectable src, int type, Object entry, int state)


* src ----reference to the componet that generated this event.
* type---type of the event is specified
* entry --- The specific item that generated the item event
* state---The current state of the event

306

Methods present in ItemEvent Class:


Object getItem( )--- obtains a reference to the item that
generated an event.
ItemSelectable getItemSelectable( )--- obtain a reference to
the ItemSelectable object
that generated an event
int getStateChange( )---- returns the state change (that is,
SELECTED or DESELECTED) for
the event

307

KeyEvent Class: AKeyEvent is generated when keyboard input occurs.


KeyEvent class has three main integer constants:
KEY_PRESSED---- when any key is pressed
KEY_RELEASED---- when key is released.
KEY_TYPED---- when a character is generated.

There are many other integer constants that are defined by KeyEvent.
For example, VK_0 through VK_9 and
VK_A through VK_Z define the ASCII equivalents of the
numbers and letters.
Here are some others: (Vk-Virtual Key)
VK_ALT
VK_DOWN
VK_LEFT
VK_RIGHT
VK_CANCEL
VK_ENTER
VK_PAGE_DOWN
VK_SHIFT
VK_CONTROL
VK_ESCAPE VK_PAGE_UP
VK_UP
308

KeyEvent is a subclass of InputEvent.


Here is one of its constructors:
KeyEvent(Component src, int type, long when, int modifiers, int code, char ch)
src -----reference to the component that generated the event
type--- The type of the event is specified
when ----The system time at which the key was pressed is passed
modifiers--- which modifiers were pressed when this key event occurred.
code---The virtual key code, such as VK_UP, VK_A
ch-- The character equivalent(if one exists)
If no valid character exists, then ch contains CHAR_UNDEFINED.
For KEY_TYPED events, code will contain VK_UNDEFINED.

309

Methods present in KeyEvent class are:


char getKeyChar( )----returns the character that was entered,
int getKeyCode( )------returns the key code
If no valid character is available, then getKeyChar( ) returns
CHAR_UNDEFINED.
When a KEY_TYPED event occurs, getKeyCode( ) returns
VK_UNDEFINED.

310

There are eight types of mouse events. The MouseEvent class defines
the following integer constants that can be used to identify them:

MOUSE_CLICKED
MOUSE_DRAGGED
MOUSE_ENTERED
MOUSE_EXITED
MOUSE_MOVED
MOUSE_PRESSED
MOUSE_RELEASED
MOUSE_WHEEL

----The user clicked the mouse.


----The user dragged the mouse.
-----The mouse entered a component.
------The mouse exited from a component.
-----The mouse moved.
-----The mouse was pressed.
-------The mouse was released.
-----The mouse wheel was moved.

311

MouseEvent is a subclass of InputEvent. Here is one of its


constructors:
MouseEvent(Component src, int type, long when, int modifiers,
int x, int y, int clicks, boolean triggersPopup)
src ---a reference to the component that generated the event
type--type of the event
when--- system time at which the mouse event occurred is passed
modifiers--- which modifiers were pressed when a mouse event occurred.
x and y. ---The coordinates of the mouse are passed
clicks--- The click count
triggersPopup ---- indicates if this event causes a pop-up menu to appear
on this platform.

312

Methods present in MouseEvent class are:

int getX( )---return X coordinate


int getY( )----return Y coordinate
Point getPoint( )-----returns a Point object that contains the X,Y coordinates
void translatePoint(int x, int y)----changes the location of the event.
Here, the arguments x and y are added to the coordinates of the event.
int getClickCount( )---obtains the number of mouse clicks for the event.
boolean isPopupTrigger( )---tests if this event causes a pop-up menu to appear
on this platform.
int getButton( )---returns a value that represents the button that caused
the event.

313

It is a subclass of MouseEvent.
Not all mice have wheels. Mouse wheels are used for scrolling.
MouseWheelEvent defines these two integer constants:

WHEEL_BLOCK_SCROLL ---A page-up or page-down scroll event


occurred.
WHEEL_UNIT_SCROLL ----A line-up or line-down scroll event occurred.

Here is one of its constructors:

314

Here is one of its constructors:


MouseWheelEvent(Component src, int type, long when, int modifiers,
int x, int y, int clicks, boolean triggersPopup,
int scrollHow, int amount, int count)

src ----- reference to the object that generated the event


type--- type of the event
when ---- system time at which the mouse event occurred
modifiers--- which modifiers were pressed when the event occurred
x and y---- coordinates of the mouse
clicks--- number of clicks the wheel has rotated is passed in clicks
triggersPopup ---indicates if this event causes a pop-up menu to appear on
this platform.
scrollHow --- must be either WHEEL_UNIT_SCROLL or
WHEEL_BLOCK_SCROLL.
amount--- number of units to scroll
count ----- number of rotational units that the wheel moved.
315

Methods present in MouseWheelEvent class are:

int getWheelRotation( )--- returns the number of rotational units


int getScrollType( )---- returns the type of scroll
int getScrollAmount( )---- obtain the number of units to scroll

316

TextEvent Class: A TextEvent is generated by text fields and text


areas when characters are entered by a user or program.is generated
when a check box or a list item is clicked or when a checkable
menu item is selected or deselected

The TextEvent class define one integer constants.


TEXT_VALUE_CHANGED---indicates that the text value has
changed

317

TextEvent has one constructor:

TextEvent(Object src, int type)


* src ----reference to the object that generated this event.
type---type of the event is specified

318

WindowEvent Class: WindowEvent is a subclass of ComponentEvent.


It deals with the windows.
WindowEvent defines ten integer constants.

WINDOW_ACTIVATED ---The window was activated.


WINDOW_CLOSED---- The window has been closed.
WINDOW_CLOSING--- The user requested that the window be closed.
WINDOW_DEACTIVATED ---The window was deactivated.
WINDOW_DEICONIFIED ---The window was deiconified.
WINDOW_GAINED_FOCUS--- The window gained input focus.
WINDOW_ICONIFIED ----The window was iconified.
WINDOW_LOST_FOCUS--- The window lost input focus.
WINDOW_OPENED ----The window was opened.
WINDOW_STATE_CHANGED ----The state of the window changed.

319

WindowEvent has four constructors:

WindowEvent(Window src, int type)


WindowEvent(Window src, int type, Window other)
WindowEvent(Window src, int type, int fromState, int toState)
WindowEvent(Window src, int type, Window other, int fromState, int toState)
* src ----reference to the object that generated this event.
* type---type of the event is specified
* other--- specifies the opposite window when a focus or activation event occurs
* fromState---- specifies the prior state of the window,
* toState--- specifies the new state that the window

320

Methods present in WindowEvent Class:

Window getWindow( )-- returns the Window object that


generated the event
Window getOppositeWindow( )returns the opposite
window object
int getOldState( )----returns the old state of the window
int getNewState( )--- returns the new state of the window

321

The delegation event model has two parts: sources and


listeners.
Listeners are created by implementing one or more of the
interfaces defined by the java.awt.event package.
When an event occurs, the event source invokes the appropriate
method defined by the listener and provides an event object as its
argument

322

ActionListener Interface:
This interface defines the actionPerformed( ) method
that is invoked when an action event
occurs.
Synatx:
void actionPerformed(ActionEvent ae)

AdjustmentListener Interface:
This interface defines the adjustmentValueChanged( )
method that is invoked when an adjustment event occurs.
Syntax:
void adjustmentValueChanged(AdjustmentEvent ae)

323

ComponentListener Interface:
This interface defines four methods that are invoked when a
component is resized, moved,
shown, or hidden.
Synatx:
void componentResized(ComponentEvent ce)
void componentMoved(ComponentEvent ce)
void componentShown(ComponentEvent ce)
void componentHidden(ComponentEvent ce)

ContainerListener Interface:
This interface contains two methods. When a component is
added/removed to a container.
Syntax:
void componentAdded(ContainerEvent ce)
void componentRemoved(ContainerEvent ce)

324

FocusListener Interface:

This interface defines two methods. When a component


obtains/loses keyboard focus.
Syntax:
void focusGained(FocusEvent fe)
void focusLost(FocusEvent fe)
ItemListener Interface:
This interface defines the itemStateChanged( ) method that
is invoked when the state of an item changes.
Synatx:

void itemStateChanged(ItemEvent ie)

325

KeyListener Interface:
This interface defines three methods. The methods are
invoked when a key is pressed and released or typed.

Synatx:
void keyPressed(KeyEvent ke)
void keyReleased(KeyEvent ke)
void keyTyped(KeyEvent ke)

MouseListener Interface:
This interface defines five methods. If the mouse is pressed
and released or When the mouse enters a component or
When it leaves.
Synatx:
void mouseClicked(MouseEvent me)
void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)

326

MouseMotionListener Interface:
This interface defines two methods. These methods called
when mouse is dragged or when the mouse is moved multiple

Syntax:
void mouseDragged(MouseEvent me)
void mouseMoved(MouseEvent me)
MouseWheelListener Interface:
This interface defines the mouseWheelMoved( ) method that
is invoked when the mouse wheel is moved.
Syntax:
void mouseWheelMoved(MouseWheelEvent mwe)

327

TextListener Interface:

This interface defines the textChanged( ) method that is


invoked when a change occurs in a text area or text field.
Syntax:
void textChanged(TextEvent te)
WindowFocusListener Interface:
This interface defines two methods: These are called when a
window gains or loses input focus.
Syntax:

void windowGainedFocus(WindowEvent we)


void windowLostFocus(WindowEvent we)

328

WindowListener Interface:
This interface defines seven methods. These methods are
invoked when a window is activated or deactivated or iconified
or deiconified,or window is opened or closed.
Syntax:
void windowActivated(WindowEvent we)
void windowClosed(WindowEvent we)
void windowClosing(WindowEvent we)
void windowDeactivated(WindowEvent we)
void windowDeiconified(WindowEvent we)
void windowIconified(WindowEvent we)
void windowOpened(WindowEvent we)

329

Follow two steps:


1. Implement the appropriate interface in the listener so that it
will receive the type of event desired.
2. Implement code to register and unregister (if necessary)
the listener as a recipient for the event notifications.
Remember that a source may generate several types of
events. Each event must be registered separately. Also, an
object may register to receive several types of events, but it
must implement all of the interfaces that are required to
receive these events.

330

To handle mouse events, you must implement the


MouseListener and the MouseMotionListener interfaces.

Consider Program MouseEvents.java


It displays the current coordinates of the mouse in the applets status
window.
Each time a button is pressed, the word Down
is displayed at the location of the mouse pointer. Each time the button is
released, the word Up is shown.
If a button is clicked, the message Mouse clicked is displayed in the
upperleft corner of the applet display area.
The two variables, mouseX and mouseY, store the location of the mouse
when a mouse pressed, released, or dragged event occurs. These
coordinates are then used by paint( ) to display output at the point of
these occurrences.

331

The MouseEvents class extends Applet and implements both the


MouseListener and MouseMotionListener interfaces. These two
interfaces contain methods that receive and process the various types of
mouse events.
The Applet is both the source and the listener for these events. This works
because Component, which supplies the addMouseListener( ) and
addMouseMotionListener( ) methods, is a superclass of Applet.
Being both the source and the listener for events is a common situation for
applets.
Inside init( ), the applet registers itself as a listener for mouse events. This
is done by using addMouseListener( ) and addMouseMotionListener( ),
which, as mentioned, are members of Component.
They are shown here:
void addMouseListener(MouseListener ml)
void addMouseMotionListener(MouseMotionListener mml)

332

To handle key events, you must implement the KeyListener


interface.

When a key is pressed, a KEY_PRESSED event is generated.


This results in a call to the keyPressed( ) event handler.
When the key is released, a KEY_RELEASED event is
generated and the keyReleased( ) handler is executed.
If a character is generated by the keystroke, then a
KEY_TYPED event is sent and the keyTyped( ) handler is
invoked.
Thus, each time the user presses a key, at least two and often
three events are generated.

333

Consider Program SimpleKey.java


It shows the pressed/released status of each key in the status
window.
If you want to handle the special keys, such as the arrow or
function keys, you need to respond to them within the
keyPressed( ) handler. They are not available through
keyTyped( ).
To identify the keys, we need to use the virtual key codes.

334

Java provides a special feature, called an adapter class,


that can simplify the creation of event handlers in certain
situations.
An adapter class provides an empty implementation of all
methods in an event listener interface. Adapter classes are
useful when we want to receive and process only some of
the events that are handled by a particular event listener
interface.
We can define a new class to act as an event listener by
extending one of the adapter classes and implementing
only those events in which we are interested.

335

Consider the example AdapterDemo.java


It displays a message in the status bar of an applet
viewer or browser when the mouse is clicked or
dragged. However, all other mouse events are
silently ignored.
The program has three classes.
AdapterDemo extends Applet. Its init( ) method
creates an instance of MyMouseAdapter and
registers that object to receive notifications of mouse
events. It also creates an instance of
MyMouseMotionAdapter and registers that object
to receive notifications of mouse motion events

336

MyMouseAdapter extends MouseAdapter and


overrides the mouseClicked( ) method. The other
mouse events are silently ignored by code inherited from
the MouseAdapter class.
MyMouseMotionAdapter extends
MouseMotionAdapter and overrides the
mouseDragged( ) method. The other mouse motion
event is silently ignored by code inherited from the
MouseMotionAdapter class.

337

Various adapter classes present in java are listed below.


Adapter Class

Listener Interface

ComponentAdapter

ComponentListener

ContainerAdapter

ContainerListener

FocusAdapter

FocusListener

KeyAdapter

KeyListener

MouseAdapter

MouseListener

MouseMotionAdapter

MouseMotionListener

WindowAdapter

WindowListener

338

Difference between applets and


application
Application :

Applets:

Application Programs are those programs


normally created ,compiled and executed
as similar to the other languages.

Applet programs are small programs that


are primarily used in internet
programming .

Each Application program contains one


main() method .

Each Applet program contains one


init () method .

Programs are created in a local computer.

These programs are either developed in


local system or in remote system.

Programs are compiled with javac


compiler and executed with java
interpreter.

Applet Programs executed by either a java


compatible Web Browser or
appletviewer.

Application are stand-alone programs.

Applet programs are used over the


Network.
339

Life Cycle of an Applet


Every java applet inherits a set of defaults from Applet class defined in java.applet
package.
When an applet is loaded ,it undergoes a series of chnages in its states .
All but the most trivial applets override a set of methods that provides the basic
mechanism by which the browser or applet viewer interfaces to the applet and
controls its execution.
When an applet begins, the following methods are called, in this sequence:
1. init( )
2. start( )
3. paint( )
When an applet is terminated, the following sequence of method calls takes place:
1. stop( )
2. destroy( )

340

Life Cycle of an Applet


init( ) :
The init( ) method is the first method to be called. This is where you should initialize variables.
This method is called only once during the run time of your applet.
Syntax: public void init()
{ --- }
Start( ):
The start( ) method is called after init( ). It is also called to restart an applet after it has been
stopped. Whereas init( ) is called oncethe first time an applet is loadedstart( ) is called
each time an applets HTML document is displayed onscreen. So, if a user leaves a web page
and comes back, the applet resumes execution at start( ).
Syntax: public void start()
{ -----}
paint( ):
The paint( ) method is called each time your applets output must be redrawn.
For example, the window in which the applet is running may be overwritten by another window and then
uncovered. Or the applet window may be minimized and then restored.
paint( ) is also called when the applet begins execution.
whenever the applet must redraw its output, paint( ) is called.
The paint( ) method has one parameter of type Graphics.
This parameter will contain the graphics context, which describes the graphics environment in which the
applet is running. This context is used whenever output to the applet is required.
Syntax: public void stop()
{--------}
341

Life Cycle of an Applet


stop( ):
method is called when a web browser leaves the HTML document containing the
appletwhen it goes to another page.
for example.
When stop( ) is called, the applet is probably running.
You should use stop( ) to suspend threads that dont need to run when the
applet is not visible.
You can restart them when start( ) is called if the user returns to the page.
Syntax: public void stop()
{--------}
destroy( ):
The destroy( ) method is called when the environment determines that your applet
needs to be removed completely from memory. At this point, you should free up any
resources the applet may be using.
The stop( ) method is always called before destroy( ).
Syntax : public void destroy() {------}
342

Life Cycle of an Applet


Note :
1. All the methods are automatically called when any applet begins
execution.
2. In every applet it doesnt need to place all the methods.
3. Class hierarchy of the applet is
java.lang.Object
java.awt .Container
java .awt.Panel
java.applt.Applet

Unit -7 Applet Program 1: AppletSkel

343

Applet
Simple Applet Display Methods:
drawString( ): to output a string to an applet, which is a member of the Graphics class.
Typically, it is called from within either update( ) or paint( ).
Syntax:
void drawString(String message, int x, int y)
Here, message is the string to be output beginning at x,y.
void setBackground(Color newColor)
void setForeground(Color newColor)
newColor:
Color.black
Color.gray
Color.blue
Color.cyan
Color.darkGray
Color.green
Color.lightGray

Color.magenta
Color.white
Color.orange
Color.pink
Color.red
Color.yellow
344

Applet
Color getBackground( )
Color getForeground( )

void repaint( ) :This version causes the entire window to be repainted.


void repaint(int left, int top, int width, int height):
Here, the coordinates of the upper-left corner of the region are specified by left and
top, and the width and height of the region are passed in width and height. These
dimensions are
specified in pixels.

Unit -7 Applet Program 2: AppletDemo


345

Types of Applet
Two varieties of applets.
1. Applet : These applets use the Abstract Window Toolkit (AWT) to provide the
graphic user interface (or use no GUI at all). This style of applet has been
available since Java was first created.
2.

JApplet. Are based on the Swing class Japplet.Swing applets use the Swing
classes to provide the GUI. Swing offers a richer and often easier-to-use
user interface than does the AWT.

346

Creating Applet
To use an applet, it is specified in an HTMLfile.
One way to do this is by using the APPLET tag.
(The OBJECT tag can also be used, but Sun currently recommends the APPLET tag )
The applet will be executed by a Java-enabled web browser when it encounters the
APPLET tag within the HTMLfile.
To view and test an applet more conveniently, simply include a comment
at the head of your Java source code file that contains the APPLET tag.
This way, your code is documented with the necessary HTML statements
needed by your applet,
Test the compiled applet by starting the applet viewer with your Java source code
file specified as the target.
Example :
/*
<applet code=MyAppletwidth=200 height=60>
</applet>
*/
This comment contains an APPLET tag that will run an applet called MyApplet in a
window that is 200 pixels wide and 60 pixels high.
Because the inclusion of an APPLET command makes testing applets easier.
347

Applet
The Applet Class:
Applet provides all necessary support for applet execution, such as
starting and stopping.
It also provides methods that load and display images, and methods
that load and play audio clips.
Applet extends the AWT class Panel. In turn, Panel extends Container,
which extends Component.
These classes provide support for Javas window-based, graphical
interface.
Applet provides all of the necessary support for window-based
activities.

348

Applet
void destroy( ) :Called by the browser just before an applet is terminated.
Your applet will override this method if it needs to perform any cleanup prior to its
destruction.
AccessibleContext getAccessibleContext( ) :Returns the accessibility context for the
invoking object.
AppletContext getAppletContext( ): Returns the context associated with the applet.
String getAppletInfo( ) :Returns a string that describes the applet.
AudioClip getAudioClip(URL url) :Returns an AudioClip object that encapsulates the
audio clip found at the location specified by url.
AudioClip getAudioClip(URL url, String clipName):Returns an AudioClip object that
encapsulates the audio clip found at the location specified by url and having the name
specified by clipName.
URL getCodeBase( ) :Returns the URL associated with the invoking applet.
URL getDocumentBase( ) :Returns the URL of the HTML document that invokes the applet.
Image getImage(URL url) :Returns an Image object that encapsulates the image found at the
location specified by url.
349

Applet
Image getImage(URL url,String imageName):Returns an Image object that encapsulates
the image found at the location specified by url and having the name specified by imageName.

Locale getLocale( ) :Returns a Locale object that is used by various localesensitive


classes and methods.

String getParameter(String paramName): Returns the parameter associated with


paramName. null is returned if the specified parameter is not found.
String[ ] [ ] getParameterInfo( ) :Returns a String table that describes the parameters
recognized by the applet. Each entry in the table must consist of three strings that
contain the name of the parameter, a description of its type and/or range, and
an explanation of its purpose.

350

Applet
void init( ) : Called when an applet begins execution. It is the first method called for
any applet.
boolean isActive( ): Returns true if the applet has been started. It returns false if the
applet has been stopped.
static final AudioClip newAudioClip(URL url) :Returns an AudioClip object that
encapsulates the audio clip found at the location specified by url. This method is
similar to getAudioClip( ) except that it is static and can be executed without the
need for an Applet object.

351

Applet
void play(URL url): If an audio clip is found at the location specified by url, the clip is
played.
void play(URL url, String clipName): If an audio clip is found at the location specified
by url with the name specified by clipName, the clip is played.
void resize(Dimension dim) :Resizes the applet according to the dimensions
specified by dim. Dimension is a class stored inside java.awt. It contains two integer
fields: width and height.
void resize(int width, int height) :Resizes the applet according to the dimensions
specified by width and height.
final void setStub(AppletStub stubObj) :Makes stubObj the stub for the applet. This
method is used by the run-time system and is not usually called by your applet. A
stub is a small piece of code that provides the linkage between your applet and the
browser.

352

Applet
Passing Parameter to Applets:
It is also possible to supply user defined parameters to An applet using
<PARAM> tags.
Each <PARAM> tag has a name attribute and a value attribute .Inside
the applet code .
The applet can refer to that parameter by name to find its value .
To retrieve the Parameter ,use the method
getParameter(): returns the value of the specified parameter in the
form of a String Object

Unit -7 Applet Program 3: AppletParameter


353

Swings
Introduction :
Limitation of AWT:
MVC Architecture:
Component
Containers:
JApplet:
JFrame:
JComponent:
Icons& Labels:
TextField

354

Swings
Buttons:
JButton class
Checkboxes
RadioButtons
Combo boxes
Tabbed Panes
ScrollPanes
Trees
Tables
355

Swings
Introduction : AWT
The AWT defines a basic set of controls, windows, and dialog boxes
that support a usable, but limited graphical interface.
First, because of variations between operating systems, a
component might look, or even act, differently on different
platforms.
This potential variability threatened the overarching philosophy of
Java: write once, run anywhere.
Second, the look and feel of each component was fixed (because it
is defined by the platform) and could not be (easily) changed.
That the look and feel of a component is defined by the
platform, not by Java.
Third, the use of heavyweight components caused some frustrating
restrictions. Because the AWT components use native code
resources, they are referred to as heavyweight. For example, a
heavyweight component is always rectangular and opaque.
356

Swings
Swings:
Swing eliminates a number of the limitations inherent in the AWT, Swing does
not replace it.
Swing is built on the foundation of the AWT.
Swing was created to address the limitations present in the AWT.
It does this through two key features: lightweight components and a
pluggable look and feel.
Swing Components Are Lightweight
They are written entirely in Java and do not map directly to platformspecific peers.
More efficient and more flexible.
Lightweight components do not translate into native peers, the look and
feel of each component is determined by Swing, not by the underlying
operating system.
Each component will work in a consistent manner across all platforms. 357

Swings
Swing Supports a Pluggable Look and Feel
Swing supports a pluggable look and feel (PLAF).
Each Swing component is rendered by Java code rather than by native
peers, the look and feel of a component is under the control of Swing.
Separate the look and feel of a component from the logic of the
component, and this is what Swing does.

358

Swings
MVC Connection:
A visual component is a composite of three distinct aspects:
The way that the component looks when rendered on the screen
The way that the component reacts to the user
The state informati on associated with the component
No matter what architecture is used to implement a component, it must implicitly contain
these three parts
The MVC architecture has successful because each piece of the design corresponds to an
aspect of a component.
In MVC terminology, the model corresponds to the state information
associated with the component.
For example, in the case of a check box, the model contains
a field that indicates if the box is checked or unchecked.
The view determines how the component is displayed on the screen, including any aspects
of the view that are affected by the current state of the model.
The controller determines how the component reacts to the
user. For example, when the user clicks a check box, the controller reacts by changing the
model to reflect the users choice (checked or unchecked). This then results in the view
being updated.
359

Swings
By separating a component into a model, a view, and a controller, the
specific implementation of each can be changed without affecting the
other two.
For instance, different view implementations can render the same
component in different ways without affecting the model or the
controller.
Swings pluggable look and feel is made possible by its Model-Delegate
architecture.
Because the view (look) and controller (feel) are separate from the
model, the look and feel can be changed without affecting how the
component is used within a program.

360

Swings
Components and Containers:
A component is an independent visual control, such as a push button or
slider.
JComponent provides the functionality that is common to all
components. For example, JComponent supports the pluggable look and
feel.
JComponent inherits the AWT classes Container and Component.
A Swing component is built on and compatible with an AWT component.
Swings components defined within the package javax.swing.

361

Swings
Components and Containers:
JApplet JButton
JCheckBox
JCheckBoxMenuItem
JColorChooser
JComboBox
JComponent JDesktopPane
JDialog
JEditorPane
JFileChooser
JFormattedTextField JFrame
JInternalFrame
JLabel JLayeredPane JList Jmenu
JMenuBar
JMenuItem
JOptionPane
JPanel
JPasswordField
JPopupMenu
JProgressBar
JRadioButton
JRadioButtonMenuItem
JRootPane
JScrollBar
JScrollPane
JSeparator
Jslider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
Jtogglebutton
JToolBar
JToolTip
Jtree
Jviewport
JWindow
362

Swings
Containers:
A container holds a group of components.
Thus, a container is a special type of component that is designed to hold
other components.
Swing defines two types of containers.
The first are top-level containers:
JFrame, JApplet, JWindow, and JDialog (holds all the
component).
The second type of containers supported by Swing are lightweight
containers is JPanel.

363

Swings
FlowLayout
FlowLayout is the simplest of all layouts, and is the default
LayoutManager of the JPanel.
In FlowLayout, widgets are placed one after another going left to right.
This occurs until the end of the JPanel is reached, then a new row is
started.
Constructors for the FlowLayout.
FlowLayout();
FlowLayout(int alignment);
FlowLayout(int alignment, int horizontalSpace, int verticalSpace);
The first constructor is the default. By default, the spacing between
these widgets is about 5 pixels and the alignment is
364
FlowLayout.CENTER.

Swings
Swing Packages :
Swing is a very large subsystem and makes use of many packages.
javax.swing
javax.swing.colorchooser
javax.swing.filechooser
javax.swing.plaf.basic
javax.swing.plaf.multi
javax.swing.table
javax.swing.text.html
javax.swing.text.rtf
javax.swing.undo

javax.swing.border
javax.swing.event
javax.swing.plaf
javax.swing.plaf.metal
javax.swing.plaf.synth
javax.swing.text
javax.swing.text.html.parser
javax.swing.tree

365

Swings
Exploring Swing:ImageIcon:
Icons are specified by objects of type Icon, which is an interface defined by Swing.
The easiest way to obtain an icon is to use the ImageIcon class.

ImageIcon implements Icon and encapsulates an image. Thus, an object of type Image Icon can be passed as an
argument to the Icon parameter of JLabels constructor.
There are several ways to provide the image, including reading it from a file or downloading it from a URL.

ImageIcon constructor:

ImageIcon(String filename)
It obtains the image in the file named filename.

Methods:
Icon getIcon( )
String getText( )
void setIcon(Icon icon)
void setText(String str) : to change the text inside a label during program execution
Here, icon and str are the icon and text, respectively. JLabel
366

Swings
JLabel:
JLabel can be used to display text and/or an icon.
JLabel defines constructors.
JLabel(Icon icon)
JLabel(String str)
JLabel(String str, Icon icon, int align)
align can be one of the constant :
LEFT, RIGHT, CENTER, LEADING, or TRAILING.

Unit -8 Program No:1

JLabelDemo

367

Swings
JTextField: JTextField allows you to edit one line of text.
JTextFields constructors:
JTextField(int cols)
JTextField(String str, int cols)
JTextField(String str)

Unit -8 Program No:2

JTextFieldDemo

368

Swings
JButtons:
Swing defines four types of buttons:
JButton, JToggleButton, JCheckBox, and JRadioButton.
All are subclasses of the AbstractButton class, which extends
JComponent.
JButton class provides the functionality of a push button.JButton
allows an icon, a string, or both to be associated with the push button.
Jbuttons constructors
JButton(Icon icon)
JButton(String str)
JButton(String str, Icon icon)
Here, str and icon are the string and icon used for the button.
ActionEvent is generated
Unit -8 Program No:3

JButtonDemo

369

Swings
JCheck Boxes: JCheckBox class provides the functionality of a check box.
JCheckBox constructors:
JCheckBox(String str)
It creates a check box that has the text specified by str as a label.
When the user selects or deselects a check box, an ItemEvent is
generated.

Unit -8 Program No:4

JCheckBoxDemo

370

Swings
Radio Buttons:
Radio buttons are a group of mutually exclusive
buttons, in which only one button can be selected at
any one time. They are supported by the JRadioButton class.
JRadioButton provides several constructors.
JRadioButton(Icon i)
JRadioButton(Icon i ,boolean state)
JRadioButton(String str)
JRadioButton(String str, boolean state)
JRadioButton(String str,Icon i)
JRadioButton(String str, Icon i,boolean state)
371

Swings
A button group is created by the ButtonGroup class.
Its default constructor is invoked for this purpose.
Elements are then added to the button group via the following method:
void add(AbstractButton ab)
Here, ab is a reference to the button to be added to the group.

A JRadioButton generates action events, item events, and change


events each time the button selection changes.

Unit -8 Program No:5

JRadioButtonDemo

372

Swings
JComboBox:Swing provides a combo box (a combination of a text field
and a drop-down list) through
the JComboBox class. A combo box normally displays one entry, but it
will also display a drop-down list that allows a user to select a different
entry.
JComboBox constructor
JComboBox(Object[ ] items)
Here, items is an array that initializes the combo box.
Methods:
void addItem(Object obj)
Here, obj is the object to be added to the combo box.
Object getSelectedItem( )
You will need to cast the returned value into the type of object stored in
373
the list.
Unit -8 Program No:8 JComboBoxDemo

Swings
JTabbedPane:
JTabbedPane encapsulates a tabbed pane. It manages a set of components
by linking them with tabs. Selecting a tab causes the component associated
with that tab to come to the forefront.
JTabbedPane defines constructor
JTabbedPane()
The general procedure to use a tabbed pane is outlined here:
1. Create an instance of JTabbedPane.
2. Add each tab by calling addTab( ).
3. Add the tabbed pane to the content pane.

Tabs are added by calling addTab( ).


void addTab(String name, Component comp)
Here, name is the name for the tab, and comp is the component that should be
added to the tab. Unit -8 Program No:6 JTabbedPaneDemo
374

Swings
JScrollPane
JScrollPane is a lightweight container that automatically handles the
scrolling of Pane another component. The component being scrolled can
either be an individual component, such as a table, or a group of
components contained within another lightweight container, such as a
JPanel.
JScrollPane defines constructors.
JScrollPane(Component comp)
The component to be scrolled is specified by comp. Scroll bars are
automatically displayed when the content of the pane exceeds the
dimensions of the viewport.
Here are the steps to follow to use a scroll pane:
1. Create the component to be scrolled.
2. Create an instance of JScrollPane, passing to it the object to scroll.
3. Add the scroll pane to the content pane.
Unit -8 Program No:7

JScrollPane

375

Swings
Trees: A tree is a component that presents a hierarchical view of data.
The user has the ability to expand or collapse individual subtrees in this
display. Trees are implemented in Swing by the JTree class.
Constructors:
JTree(Object obj[ ])
JTree(Vector<?> v)
JTree(TreeNode tn)

376

Swings
JTree relies on two models: TreeModel and TreeSelectionModel.
A JTree generates a variety of events, but three relate specifically to trees:
TreeExpansionEvent,
TreeSelectionEvent,
TreeModelEvent.
A TreeExpansionEvent events occur when a node is expanded or collapsed.
A TreeSelectionEvent is generated when the user selects or deselects a node
within the tree.
A TreeModelEvent is fired when the data or structure of the tree changes.
The listeners for these events are
TreeExpansionListener
TreeSelectionListener
TreeModelListener
The tree event classes and listener interfaces are packaged in
377
javax.swing.event.

Swings
The DefaultMutableTreeNode class implements the MutableTreeNode
interface.
It represents a node in a tree. One of its constructors is shown here:
DefaultMutableTreeNode(Object obj)
Here, obj is the object to be enclosed in this tree node. The new tree
node doesnt have a parent or children.
To create a hierarchy of tree nodes, the add( ) method of
DefaultMutableTreeNode can be used.
Its signature is shown here:
void add(MutableTreeNode child)
Here, child is a mutable tree node that is to be added as a child to the
current node
378

Swings
JTree does not provide any scrolling capabilities of its own. Instead, a
JTree is typically placed within a JScrollPane. This way, a large tree can
be scrolled through a smaller viewport.
Here are the steps to follow to use a tree:
1. Create an instance of JTree.
2. Create a JScrollPane and specify the tree as the object to be scrolled.
3. Add the tree to the scroll pane.
4. Add the scroll pane to the content pane.

Unit -8 Program No: 9 JTreeDemo

379

Swings
JTable :
JTable is a component that displays rows and columns of data. You can drag the
cursor on column boundaries to resize columns. You can also drag a column to
a new position.
Depending on its configuration, it is also possible to select a row, column, or
cell within the table, and to change the data within a cell.
JTable does not provide any scrolling capabilities of its own. Instead, you will
normally wrap a JTable inside a JScrollPane.

JTable constructor:
JTable(Object data[ ][ ], Object colHeads[ ])
Here, data is a two-dimensional array of the information to be presented, and
colHeads is a one-dimensional array with the column headings.
380

Swings
JTable relies on three models.
1. The first is the table model, which is defined by the TableModel
interface. This model defines those things related to displaying data
in a two-dimensional format.
2. The second is the table column model, which is represented by
TableColumnModel. JTable is defined in terms of columns, and it
is TableColumnModel that specifies the characteristics of a
column. These two models are packaged in javax.swing.table.
3. The third model determines how items are selected, and it is
specified by the ListSelectionModel,
381

Swings
A JTable can generate several different events. The two most
fundamental to a tables operation are
1. ListSelectionEvent
2. TableModelEvent.
Here are the steps required to set up a simple JTable that can be used to
display data:
1. Create an instance of JTable.
2. Create a JScrollPane object, specifying the table as the object to scroll.
3. Add the table to the scroll pane.
4. Add the scroll pane to the content pane.

Unit -8 Program No:10 JTableDemo

382

Вам также может понравиться