Java

Download as pdf or txt
Download as pdf or txt
You are on page 1of 191

qwertyuiopasdfghjklzxcvbnmqwer

tyuiopasdfghjklzxcvbnmqwertyuio
pasdfghjklzxcvbnmqwertyuiopasd
Object Oriented
fghjklzxcvbnmqwertyuiopasdfghjkl
Programing
zxcvbnmqwertyuiopasdfghjklzxcv
T J
HROUGH AVA

bnmqwertyuiopasdfghjklzxcvbnm
qwertyuiopasdfghjklzxcvbnmqwer
UNIT - 1

tyuiopasdfghjklzxcvbnmqwertyuio
pasdfghjklzxcvbnmqwertyuiopasd
fghjklzxcvbnmqwertyuiopasdfghjkl
zxcvbnmqwertyuiopasdfghjklzxcv
bnmqwertyuiopasdfghjklzxcvbnm
qwertyuiopasdfghjklzxcvbnmqwer
tyuiopasdfghjklzxcvbnmqwertyuio
pasdfghjklzxcvbnmqwertyuiopasd
fghjklzxcvbnmrtyuiopasdfghjklzxcv
2 Object Oriented Programing

DIFFERENCE BETWEEN PROCEDURE ORIENTED AND OBJECT ORIENTED


PROGRAMMING
No. POP OOP
1. In POP programming is divided into small In OOP program is divided into small parts called
parts called functions objects
2. POP follows top–down approach OOP follows bottom-up approach

3. POP doesn’t have any proper hiding of OOP provides data hiding, so OOP having more
data, so it is less secure security
4. In POP importance is not given to data, In OOP importance is given to the data rather
it gives importance to functions than functions.
5. POP doesn’t have any access specifiers OOP has access specifiers like public, private, and
protected.
6. in POP data can move freely from one in OOP objects can move and communicate with
function to another function each other through member function
7. POP is simple to implement OOP is complex to implement

8. In POP most functions uses global data In OOP data cannot move easily from function to
for sharing that can be accessed freely function, it can be kept public, private and
from function to function protected.so we can control access of data.
9. In POP overloading is not possible in OOP overloading is possible

10. To add new data and functions in POP is OOP provides an easy way to add new data and
not so easy functions
11. Modification of a completed program is modification are easy as objects independent to
very difficult and it may affect the whole declare and define
program e.g.:-java, C++, VB.NET and C#.NET
e.g.:- C language, Pascal, Fortran.

OBJECT ORIENTED PROGRAMMING FEATURES:-


The following are the object oriented features:-
1) Object
2) Class
3) Messages and methods
4) Inheritance
5) Polymorphism

Object
*Object is real word entity, runtime entity,
Object is an instance of a class, objects are run-time entity of the object oriented program.
Objects communicate with each other using messages, while communicating with each other it is

2
3 Object Oriented Programing

not necessary to know the details of communicating object. Thus the internal details of each
object can be hidden from another object.

An object has three characteristics


State: - represents data of an object
Behavior: - Represents the functionality of an object
Identity: - Object identity is typically implemented using a unique ID

Class
A class can be defined as a template or blue print that describes the behavior of the object
A class is a group of objects which have common properties .it is a logical entity, it cannot be in a
physical existence.
The class is declared using the keyword class.
A class can contain fields, methods, constructors, blocks, nested class and interface
Syntax:-
Class <class_name >
{
Fields
Methods
}

Ex:-
1) class student
{
Public static void main(String[] args)
{
System.out.println(“good student’);
}
}

DIFFERNCE BETWEEN OBJECT AND CLASS:-


OBJECT CLASS
1)object is instance of a class 1) A class can be defined as a template or blue print that
describes the behavior of the object

3
4 Object Oriented Programing

2)object is a real world entity 2) class is a logical entity


3) Object is created through new 3)class is declared using class keyword
keyword.
Student s=new student();
4)object is created many times 4)class is declared once
as per required
5)objects allocates memory 5) Class does not allocate memory when it is created.
when it is created

MESSAGES AND METHODS:-


An object provides some services. A message for an object is a request made for execution of
method for obtaining the source.
Another object containing the method, execute that method and then responds back by passing
the message. Thus action is initialized in object oriented programming by the transmission of a
message to the object responsible for the action.

Sending Receiving

Object Object

sending
response
request

Data Abstraction:-
Data abstraction means representing only essential features by hiding all the implementation
details (inner details).In java, class is entity used for data abstraction purpose. The methods are
defined in the class from the main function using objects. Thus only abstract representation of data
is possible by using class

Encapsulation:-
Encapsulation means the detailed implementation of a component which can be hidden from the
rest of the system.
Encapsulation means binding of data and methods together in a single entity called class. The
data inside the class is accessible by the function is the same class .it is normally not accessible
from the outside of the component.

4
5 Object Oriented Programing

HISTORY OF JAVA:-
In 1990, sun microsystem has conceived a project to develop software for consumer electronic
devices that could be controlled by a remote .This project was called stealth project. Later its
name was changed into green project.in 1991 James Gosling, Mike Sheridan, Patrick Naughton, Bill
joy focus on business development and began working on graphic system and was identified the
proper programming language for the project. Gosling thought c and c+ could be system
dependent languages. He introduced a new programming language which was completely
system independent .This language was initially called oak. Later it was changed to java.

EXPLAIN FEATURES OF JAVA:-


There are many features of java, also called as java BUZZ words. They are
1) Simple
2) Platform independent
3) Object oriented
4) Robust
5) Secured
6) Portable
7) High performance
8) Distributed
9) Multi-threaded.
10) Interpreted
11) Architecture Neutral

1) Simple:-
Java is simple programming language because it follows same syntax, which is in c and c++
It omitted the difficult concept of c and c++, i.e., pointer concept, because pointer crash
programs easily, it leads to confusion for a programmer.
2) Platform Independent:-

5
6 Object Oriented Programing

A platform is a hardware or software environment in which a program runs .there are two types
of platforms software based platform .java code can be run on multiple platforms .e.g.:- windows
,Linux, Mac OS, Solaris .
Java code is compiled and converted into byte code .this byte code is a platform independent
code because it can be run on multiple platforms i.e., write once run anywhere (WORA)
3) Object Oriented:-
Java programming all OOPs features except multiple inheritance .object oriented programming
is a methodology that simplify software development and maintenance by providing some rules.
Basic concept of OOPs are:-
1) object
2) class
3) Messages and methods
4) Inheritance
5) Polymorphism
6) Data abstraction
7) Encapsulation
4) Robust:-
Robust means strong .java programs are strong and they do not crash easily like c and c++
programs .java has excellent in build exception handling features.java is good memory
management feature.
5) Secure:-
Java programs are very secure because it has no explicit pointers, java programs runs inside
virtual machine. In java virus threads can be eliminated or minimized by using java on internet.

6) Portable:-
Java is portable, we may carry the java byte code to any platform.
7) High Performance:-
The problem with interpreter inside the JVM is very slow ,because of this java programs used to
run slow ,to overcome this problem .along with the interpreter , java soft people have introduced
JIT(just in time) which enhances the speed of execution.
8) Distributed:-
We can create distributed application in java RML and URL are used for creating distributed
application .we may access files by calling the methods from any machine on the internet.
9) Multi-Threaded:-

6
7 Object Oriented Programing

A thread represents an individual process to execute a group of process .JVM uses several
threads to execute different blocks of codes, creating multiple threads is called multiple threaded.
10) Interpreted:-
Java programs are compiled to generate the byte code .This byte code can be downloaded
and interpreted in JVM .if we take any other language only an interpreter or a compiler is used to
execute the program .but in java we use both compiler and interpreter for the execution.
11) Architecture Neutral:-
There is no implementation dependent features i.e. size of primitive types is fixed .in c programming
int data type occupies 2 bytes of memory for 32 bit and 4 bytes no of memory for 64 bit. But in java
it occupies 4 bytes of memory for 32 and 64 bit of architecture.
VARIABLES IN JAVA:-
Variable is name reserved area allocated in memory. In other words ,it is a name of memory
location .In other words ,it is a name of memory location it is a combination of ‘vary + able’ that
means its value can be changed. There are three types of variables in java.

Local Variable:-
A variable which is declared inside the method is called local variable

Instance Variable:-
A variable which is declared inside the class, but outside the method is called instance variable

Static Variable:-
A variable that is declare as static variable .it cannot be local variable

E.g.:
Public class variable
{
int x=20; //instance
static int y=30; //static
void main()
{
int a=10;
}
}

Data Types :-
Data types represents the different values to be stored in the variables
In java there are two different types of data. They are
1) Primitive data type

7
8 Object Oriented Programing

2) Non primitive data type.

. data type

. primitive
non
primitive

string and
. boolean numeric
array

.. numeric

.. integral character

.. int,long,short byte ,double char

DATA TYPE SIZE


BOOLEAN 1 BYTE
CHAR 2 BYTES
SHORT 2 BYTES
INT 4 BYTES

8
9 Object Oriented Programing

LONG 8 BYTES
FLOAT 4 BYTES
DOUBLE 8 BYTES
BYTE 8 BYTE

Comments in Java:-
Java comments are statements that are not executed by the compiler and interpreted
.explanation about the variable, method, and program. There are 3 types of comments in java.
Single line comment - //
Multiple comment- /* */
Documentation comment- /** */

Operators
An operator is a symbol that performs an operation .an operator acts on some variables called
operands to get the desired result. Java language supports a rich set of operators
1) Arithmetic operators( +, - , * , / , % )
2) Unary operators( ++,--)
There is no difference between post increment and pre increment but the difference when we
assign to another variable the values will be changed.
e.g.:-
int a=10;
a++;
b=a++;
System.out.println(+a);
a=11
b=12

Relational operators:-
These are used to specify the relation between two operands .if relation operator is true .it gives
‘1’.if the relation is false it gives ‘0’
Operators:-
>, < , >= , <= , == , !=
Bit wise operator:-
Bit wise operator works on bits and performs, bit by bit operations.

9
10 Object Oriented Programing

Operators (&, \, ~, ^)

Assignment operators
This is used to assign, write side value to left, we cannot assign a variable to constant and constant
to constant.

Logical operator
These are used to perform logical operators to construct compound conditions (multiple
condition)
Operators
(&&,||,!)

Shift operators
Shift operators are used to perform shifting the bits in data .there are three types of shift operators
in java.
1) left shift (<<)
2) right shift (>>)
3) Zero fill right shift operator (>>>)

Left shift
This operator shifts the bits of the number towards left specified no of position. The symbol
for this operator is ‘<< ‘
E.g.;-
Public class shift
{
int x=10;
System.out.println(x<<2);
}
Output:-
40(10*2*2)

10
11 Object Oriented Programing

Right shift operator


This operator shifts the bits of the number towards right a specified no of positions .the
symbol for this is ‘>>’.right shift operators also preserves the sign bit ,which is MSB(most significant
bit) sign bit represents sign of the number .sign bit ‘0’ represents a positive no and ‘1’ represents a
negative number
E.g.:-
Public class shift
{
int x=10;
System.out.println(x>>2);
}
Output:-
2 (10 /2*2)
Bit wise zero fill right shift operator:-
This operator also shifts the bits of the number towards right a specified number of position, but it
stores ‘0’ in sign bit. The symbol is ‘>>>’.it is called zero fill right shift operator.

Ternary Operator:-
This operator is called ternary operator (? :) because it requires or performs three variables .this is
also called conditional operator.
Syntax:-
Exp 1? exp 2: exp 3
New operator:-
New operator is used to create an object to class. We know that objects are created by heap
memory by JVM dynamically.
Syntax:-
Class_name obj=new class_name();
Instance operator:-
This operator is used to test if an object belongs to a class or not. Hence instance means object
.this operator can also be used to check if object belongs to interface or not.
Member operator :-
Member operator is also called as dot operator .this operator tells about the member of a
package or class.

11
12 Object Oriented Programing

Syntax:-
Classname.Variablename;
Object.Variablename;
Package.variablename;

JVM Architecture:-
JVM means Java Virtual Machine, it is a set of software and program components .it is a virtual
computer that resides in the real computer.
Java can achieve its platform independent features using java virtual machine.
Before understanding the concept JVM. The following structure will give explanation of JVM

When we want to write a java program, we write the source code and store it in a file with
extension .java. This .java file is compiled using java compiled and a class file gets created.
This class file is actually a byte code. The name byte code is given because of the instructions of
java program.
The jvm takes byte code as input, reads it, interprets the code and executes the code.
The JVM can generate an output corresponding to the relevant operating system. This allows any
java program to execute on any platform. Hence java is known as platform independent
language.

12
13 Object Oriented Programing

Arrays
An array is indexed collection fixed size of homogenous data elements using a single memory
location. (OR)
An array is a collection of similar data type using array elements, data type of same elements can
be grouped together.
If we use bunch of variables instead of arrays ,then we have to use large no of variables
Declaring and handling of large no of variables is very inconvenient for developers
Note:-
Variable can store only one variable at a time in a single memory location.
Arrays can store multiple values sharing a single memory location.
There are 3 types of arrays in java
1) Single dimensional array
2) Two dimensional array
3) Multi-dimensional array.

1) Single Dimensional Array:-


The list of items can be given one variable name using only one substitute operator and such
variable is called single subscribed variable or one dimensional array.
Syntax:-
datatype arrayname[];
datatype[] arrayname;
datatype []arrayname;
E.g.;-
int a[5];
The first element of array is stored at zero index and last element of the array is n-1.where n is the
array size. Arrays are created on dynamic memory by JVM .there is no question of static memory in
java.
In array initialization:-
Int a[5] = {10, 20, 30, 40, 50}
e.g.:-
public class Arrayexample
{
public static void main(String[] args)

13
14 Object Oriented Programing

{
int I;
int a[5]= {10, 20, 30, 40, 50}
For (i=0; i<a.length; i++)
{
System.out.println(a[i]);
}
}
}

2) Two Dimensional Array:-


A two dimensional array represents several rows and columns of data. It is easy to create two
dimensional array like one dimensional array. In this we used to subscript operator which indicates
rows and columns.
Syntax:-
Datatype arrayname[ ][ ]
E.g.:-
int a[3][3];
int student[ ][ ]={{1, 2},{3, 4}};
//program
public class Arrayexample
{
public static void main(String[ ] args)
{
int a[ ][ ]={{1, 2},{3, 4}};
for(int i=0; i<3; i++)
{
for( j=0;j<3;j++)
{
System.out.println(a[i][j]);
}
System.out.println(“ “);
}
}

14
15 Object Oriented Programing

}
//Addition Of Two Matrices
Public class AdditionOfMatrices
{
Public static void main(String [ ] args)
{
int a[ ][ ]={{1,2,3},{4,5,6},{7,8,9}};
int b[ ] [ ]={{1,5,9},{4,6,7},{7,9,6}};
int c[ ][ ]=new int[3][2];
for(int i=0;i<3;i++)
{
for (int j=0;j<3;j++)
{
C[i][j]=a[i][j]+b[i][j];
System.out.println(c[i][j]);
}
System.out.println(“ “);
}
}

Disadvantages of Array:-
The memory size will be fixed, we cannot increase or decrease the size of the array.
In array we can store only homogeneous elements.
If you want to insert delete an element from array it is an expensive operation.

Advantages of Arrays:-
Multiple values are stored in a single memory location
Data will be stored sequentially, so that we can retrieve the data directly using array index
numbers or position.

15
16 Object Oriented Programing

Inheritance and Its Types:-


Inheritance in java is a mechanism in which one object or class acquires all the properties and
behavior of the parent, object or class .it is also called “IS A RELATIONSHIP”.
The idea behind inheritance in java is that we can create new classes that are build upon existing
classes.
When we inherited from an existing class we can reuse methods
And fields of the parent class, and you can add new methods and fields also
A class which is inherited is called parent or super or base class and new class is class child or sub or
derived class
With the use of inheritance the information is made and manageable in a hierarchical order.
Inheritance is a compile time mechanism, a super class or parent class can have any no of sub
classes, but a sub class can have only one super class because java doesn’t support multiple
inheritance.
The derived class inherits all the members and methods that are declared as public or protected, if
class declared as private it cannot be inherited because the private members can be accessed
only by its own class.
The main objective of the inheritance is code reusability i.e., when we want to create a new class
and there already a class that includes sum of the code.
For method overriding, the runtime polymorphism can be achieved by using inheritance.

Disadvantages of Inheritance
The two classes gets tightly coupled this means that we change code of parent class because
child class cannot be independent of each other.
TYPES OF INHERITANCE:-
SINGLE INHERITANCE
MULTI LEVEL INHERITANCE
MULTIPLE INHERITANCE
HYBRID INHERITANCE

Single Inheritance:-
In single inheritance there is one parent per child class .this is most common form of
inheritance.

16
17 Object Oriented Programing

E.g. program;-
Public class A
{
void m1()
{
System.out.println(“this is super class”);
}
}
Class B extends A
{
Void m2()
{
System.out.println(“this is child class “);
}
}
class mainclass
{
Public static void main(String[] args);
{
A a=new A();
B b= new B();
a.m1();
b.m2();
}
}

17
18 Object Oriented Programing

2) Multi Level Inheritance:-


Multilevel inheritance refers to mechanism in object oriented technology, where one can inherit
from derived class, thereby making this derived class, the bass class for the new class.

B is child class of class A as well as it is a base class of class C .This type of inheritance is called
multilevel inheritance.
E.g.:-
Public class A
{
void m1()
{
int a=10;
System.out.println(“grand parent class”);
}
}
Class B extends A
{
Void m2()
{
int b=20;

System.out.println(“parent class”);
}
}

18
19 Object Oriented Programing

Class C extends B
{
Void m3()
{
int c=30;
System.out.println(“child class’’);
}
}
Class main
{
Public static void main(String[ ] args)
{
A a=new A( );
B b=new B( );
C c=new c( );
b.m1( );
b.m2();
c.m1();
c.m2();
}
}

3) Multiple Inheritance:-
Multiple inheritance refers to the concept of one class extending or inherits more than one base
class .the inheritance the concept of one base class, the problem with multiple inheritance is that
the derived class will have to manage the dependency on two base classes

19
20 Object Oriented Programing

Note:-
Multiple inheritance is very rarely used in software projects
Using multiple inheritance leads to problems in the hierarchy .to reduce the complexity and
simplicity of language, multiple inheritance is not supported in java language.
E.g.:-
Public class A
{
void display()
{
System.out.println(“A class”);
}
}
Public class B
{
void display()
{
System.out.println(“class B”);
}
}
Class c extends A,B
{
public static void main(String[] args)

20
21 Object Oriented Programing

{
c obj=new c();
obj.display();
}
}

Hybrid Inheritance:-
Hybrid inheritance is a combination of single and multiple inheritance. A hybrid inheritance can
be achieved in java in same way as multiple inheritance.

Access Modifiers:
There are four types of access modifiers:
i) private (visible to class only).
ii) default (visible to package).
iii) protected (visible to package and subclasses).
iv) public (visible to world).
The access modifiers in Java specifies the accessibility or scope of a data member, method,
constructor, class.

21
22 Object Oriented Programing

Constructors.
Ans. It is a special type of method that is used to initialize the object.
Once we create an object it is mandatory that we should perform initialization then only that
object is in a position to respond properly. Java constructor is invoked at the time of object
creation. It constructs the values that is provides data for the object.
Rules for creating a constructor:
The constructor name and classname should be same and the constructor name should end with
a pair of simple braces. Constructor is executed automatically at the time of object creation so
that no return type is required for constructor even void also. There are two types of constructors:
Default constructor (or) no argument constructor
Parameterized constructor
Default constructor:-If a constructor doesn’t have any parameters it is called default
constructor.The JVM compiler generates a default constructor i.e. no argument
NOTE:-Every no argument constructor is not a default constructor.
Parameterized constructor:-If a constructor has one or more parameters it is called parameterized
constructor.
A constructor doesn’t have any return value.
A constructor is called and executed only once per object. This means that when we create an
object the constructor is called. When we create second object the constructor is again called
second time.
Example of default constructor:
class Student
{
int stuid;
string stuname;
double stufee;
public static void main(String[] args)
{
Student s=new Student();
System.out.println(stuid);
System.out.println(stuname);
System.out.println(stufee);
}
}

22
23 Object Oriented Programing

O/P:
0
Null
0

Example of parameterized constructor:


class Student
{intstuid;
String stuname;
double stufee;
Student(int x, string y, double d)
{
stuid=x;
stuname=”y”;
stufee=d;
}
public static void main(String[] args)
{
Student s=new Student(10,”RAJU”,2000.09);
System.out.println(“Student no:”+stuid);
System.out.println(“Student name:”+stuname);
System.out.println(“Student fee:”+stufee);
}
}
O/P:
Student no:10
Student name:RAJU
Student fee:2000.09
Q. Explain this keyword.
Ans. This keyword is used to refer to current class instance variable or global variable.
This keyword invokes current class method implicitly.
This keyword can be used to invoke current class constructor.

23
24 Object Oriented Programing

This keyword can be passed as an argument to another method.

Usage of This Keyword


This keyword can be used to refer to current class instance variable. This can be passed as an
argument in the method call. This can be passed as an argument in constructor call.
This keyword can also be used to return the current class instance.
EXAMPLE WITHOUT USING THIS KEYWORD:
class Student
{
Int id;
String name;
Student(intid,String name)
{id=id;
name=name;
}
void display()
{ System.out.println(id+” “+name);
}
public static void main(String args[])
{Student s1=new Student(10,”Ramu”);
Student s2=new Student(20,”Raju”);
s1.display();
s2.display();
}
}
O/P:
0 null
null

Example with Using This Keyword:


class Student
{
Int id;
String name;

24
25 Object Oriented Programing

Student(intid,String name)
{this.id=id;
this.name=name;
}
void display()
{ System.out.println(id+” “+name);
}
public static void main(String args[])
{Student s1=new Student(10,”Ramu”);
Student s2=new Student(20,”Raju”);
s1.display();
s2.display();
}
}
O/P: 10 Ramu
20 Raju

Super keyword.
Ans.
Super keyword is a reference variable used to refer to immediate parent class object.
If you create an object for superclass we can only access the superclass members but not the
subclass members but if we create subclass object all the members of the super and sub class are
available to it.This is the reason we always create child class object in inheritance.
Sometimes the superclass members and the subclass members may have the same name .In that
case by default only subclass members are accessible.
USES OF SUPER KEYWORD:
Super is used to invoke immediate parent class object.
Super is used to invoke immediate parent class method.
Super is used to invoke immediate parent class variable.
EXAMPLE WITHOUT SUPER KEYWORD:
class Parent
{ int x=20;
void m1()

25
26 Object Oriented Programing

{ System.out.println(“parent class value”+x);


}
}
class child extends Parent
{ int x=50;
void display
{System.out.println(“child class value”+x);
}
}
class Supertest
{ public static void main(String args[])
{
child c=new child();
c.display();
}
}
O/P:
child class value50
EXAMPLE WITH THIS KEYWORD:
class Parent
{ int x=20;
}
class child extends Parent
{ int x=50;
void display
{System.out.println(“child class value”+x);
System.out.println(“parent class value”+super.x);
}
}
class Supertest
{ public static void main(String args[])
{

26
27 Object Oriented Programing

child c=new child();


c.display();
}
}
O/P:
child class value50
parent class value 20
POLYMORPHISM:
Polymorphism is derived from a Greek word “poly” meaning many and “morphs” meaning forms.
Polymorphism is the ability of an object to take on many forms. The most common use of
polymorphism in OOP occurs “when a parent class reference is used to refer to a child class
object”.
Ex:-Parent p=new child();
It is important to know that only possible way to access an object is through a reference variable.
A reference variable can be of only one type. Once it is declared the type of reference variable
cannot be changed. Polymorphism is extensively used in implementing inheritance.
There are two types of polymorphism in JAVA:
i)Compile time polymorphism
ii)Run time polymorphism

Compile Time Polymorphism:


Compile time polymorphism is nothing but method overloading or early binding in Java.We can
say that “a class can have more than one methods with same name but with different types of
arguments or datatype elements”.
Ex:
class A
{int sum;
void print(inta,int b)
{ sum=a+b;
System.out.println(“sum of a,b =” +sum);
}
void print(inta,intb,intc)
{sum=a+b+c;
System.out.println(“sum of a,b,c = ”+sum);
}

27
28 Object Oriented Programing

public static void main(String[] args)


{ A a=new A(10,20);
A a1=new A(10,20,30);
}
}
O/P: sum of a,b=30
Sum of a,b,c=60
NOTE:Definition of method overloading : writing two or more methods in the same class with same
name of methods but with different method signature is called method overloading. The method
signature represents the method name alongwith method parameters.

Run Time Polymorphism:


Runtime polymorphism is also called as dynamic method dispatch. It is executed at run time so
that it is called as dynamic polymorphism .This means when a method is called , the method call is
bound to method body at the time of running the program dynamically.Only JVM knows which
method is executed . This is also called late binding.Method overriding is a perfect example of
runtime polymorphism.
EX:
class parent
{
void property()
{ System.out.println(“parent class”);
}
}
class child extends parent
{
void property()
{ System.out.println(“child class”);
}
public static void main(String[] args )
{
parent p=new child();
p.property();

28
29 Object Oriented Programing

}
}
O/P:child class
NOTE: Definition of method over riding: Method overriding is a mechanism in which a subclass
inherits the methods of a superclass and sometimes the subclass modifies the implementation of
method defined in superclass.

Difference between method overloading and method


overriding.
Ans.
No. Method Overloading Method Overriding
1) Method overloading is used to increase the Method overriding is used to provide the
readability of the program. specific implementation of the method that is
already provided by its super class.
2) Method overloading is performed within Method overriding occurs in two classes that
class. have IS-A (inheritance) relationship.
3) In case of method overloading, parameter In case of method overriding, parameter must
must be different. be same.
4) Method overloading is the example Method overriding is the example of run time
of compile time polymorphism. polymorphism.
5) In java, method overloading can't be Return type must be same or covariant in
performed by changing return type of the method overriding.
method only. Return type can be same or
different in method overloading. But you
must have to change the parameter.
6) Private, static and final methods can be Private, static and final methods
Overloaded Cannot be overridden.

7) This is also called as compile-time This is also called run-time polymorphism or


Polymorphism or static polymorphism dynamic Polymorphism or late binding or
Dynamic method dispatch.

8) JVM decides which method is to be called JVM decides which method is called
depending on the difference in the method depending on the datatype of the
signatures. object used to call the method.

Abstract class: Any class that contains any abstract method is declared as abstract class.An
abstract class is never instantiated. That is we cannot create objects for an abstract class.
Any class that has at least one abstract method has to be compulsorily declared as an abstract
class. Abstract class can contain both abstract and non-abstract methods (concrete methods).

29
30 Object Oriented Programing

Definition of abstract method: An abstract method is a method without method body.The method
will be defined or implemented by its subclass.Abstract method can never be final or static.An
abstract method is written when the same method has to perform different task depending on the
object calling it. The child class needs to override the definition of all abstract methods.
EXAMPLE 1:
abstract class parent
{ abstract void m1();
void m2()
{
System.out.println(“Parent class”);
}
}
class child extends parent
{
void m1()
{System.out.println(“child class”);
}
}
class test
{public static void main(String args[])
{
child c= new child();
c.m1();
c.m2();
}
}
O/P:child class
parent class

EXAMPLE 2:
abstract class parent
{ abstract void speed();
}
class child extends parent
{

30
31 Object Oriented Programing

void speed()
{System.out.println(“speedlimit 40”);
}
public static void main(String args[])
{
child c= new child();
c.speed();
}
}
O/p: speedlimit 40

INTERFACE
Ans. An interface in Java is a blueprint of class. It has only abstract methods. The interface in Java
is a mechanism to achieve full abstraction. By using interface we can achieve multiple inheritance
in Java. Here we use interface keyword. An interface contains only abstract methods which are all
incomplete methods. So it is not possible to create object to an interface. In this case separate
classes are created where we can implement all these methods of the interface. These classes are
known as implementation classes. An interface is a specification of method prototype. All the
methods of interface are public and abstract methods only.
Interface is implicitly abstract. You need not use abstract keyword while declaring an interface.
Interface methods are public because they should be available to third party vendor for providing
implementation. They are abstract because their implementation is left to third party vendors.

EXAMPLE:
interface it
{
void m1();
void m2();
}
class test implements it //here implements is keyword same like extends
{ void m1()
{System.out.println(“1st method class”);
}
void m2()
{System.out.println(“2nd method class”);
}
public static void main(String args[])
{
test t= new test();

31
32 Object Oriented Programing

t.m1();
t.m2();
}
}

O/P:
1st method class
2nd method class

Multiple Inheritance using interface.


Ans. In multiple inheritance subclasses are derived from multiple super classes. If two super classes
have same name for their members (methods and variables) then which member is inherited into
the subclass is main confusion in multiple inheritance. This is the reason Java doesn’t support
concept of multiple inheritance.
This problem is reduced by using interfaces so that by using interfaces we can achieve multiple
inheritance.

EXAMPLE:
interface it1
{
void m1();
int x=20;
}
interface it2
{ void m1();
int x=30;
}
class test implements it1,it2
{
void m1()
{ System.out.println(“child class”);
System.out.println(it1.x);
System.out.println(it2.x);
}
public static void main(String[] args)
{test t=new test();
t.m1();
}
}
O/P:
child class
20
30

32
33 Object Oriented Programing

NOTE:
1. We cannot implement one interface from another because implementing an interface
means writing body for another methods. This cannot be done again in an interface.
Since one of the methods of the interface can have body.
2. We can write class within an interface because class can have method’s body.

Difference between abstract class and interface.


Abstract class Interface
1) Abstract class can have abstract and non- Interface can have only abstract methods.
abstract methods. Since Java 8, it can have default and static
methods also.
2) Abstract class doesn't support multiple Interface supports multiple inheritance.
inheritance.
3) Abstract class can have final, non-final, static Interface has only static and final variables.
and non-static variables.
4) Abstract class can provide the implementation Interface can't provide the implementation of
of interface. abstract class.
5) The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.
6) Inside abstract class we can declare Inside interface we cannot declare a
constructor which is executed at the time of child constructor.
class object creation.

7) An abstract class is written when there are An interface is written when all the features are
some common features shared by all the objects implemented differently in different objects.
8) When an abstract class is written it is the An interface is written when the programmer
responsibility of the programmer to provide its wants to leave the implementation to third
subclass. party vendor.
9) Example: Example:
public interface Drawable{
public abstract class Shape{ void draw();
public abstract void draw(); }
}

CONTROL STATEMENTS:
Control statements are the statements which are the flow of execution and provide better control
to the programmer on the flow of execution. They are useful to write better and complex
programs. The following control statements are available in Java:

33
34 Object Oriented Programing

1. if statement
2. if else statement
3. switch statement
4. while loop
5. do-while loop
6. for loop
7. break statement
8. continue statement

if statement:An if statement contains a Boolean expression and a block of statements which


are enclosed within braces.

Syntax:
1. if(condition)
statement;
2. if(condition)
{
block of statements;
}

If condition is true the immediate statement of if will be executed.

EXAMPLE:int a=10;
if(a<10)
System.out.println(“hello”);
System.out.println(“hai”);

O/P:hai
EXAMPLE:int a=20;
if(a<10)
{System.out.println(“hello”);
System.out.println(“hai”);
}

O/P:no output
EXAMPLE:int a=8;
if(a<10)
{System.out.println(“hello”);
System.out.println(“hai”);
}

34
35 Object Oriented Programing

O/P:hello
hai

if-else statement:Java if else statement is also known as testing conditional statement.If


statement block with else statement is known as if else statement . It executes if block when the
condition is true otherwise it executes else block.

SYNTAX:
1. if(condition)

statement;
else
statement 1;
2. if(condition)

{block of statements;
}
else
{ block of statements;
}

EXAMPLE:
i) int a=10;
if(a<10)
System.out.println(“hello”);
else
System.out.println(“hai”);
O/P: hai
ii) int a=10;
if(a<10)
{ System.out.println(“hello”);
System.out.println(“hai”);
}
else
System.out.prinln(“welcome”);
O/P:welcome
iii) int a=7;
if(a%2==0)
System.out.println(“even no.”);
else
System.out.println(“odd no.”);
O/P: odd no.

35
36 Object Oriented Programing

Nested if-else statement: When a program is having multiple if statements and else
statements it is called nested if-else statements.

SYNTAX:
if (condition)
if(condition1)
statement1;
else
statement 2;

EXAMPLE:
if(grade>40&&grade<=50)
System.out.println(“third class”);
if(garde>50&&garde<=70);
System.out.pritnln(“second class”);
if(grade>70)
System.out.println(“first class”);

Switch statement: A switch statement is used instead of nested if-else statement. It is like if-
else-if ladder statement. It is multi-branch decision statement. A switch statement tests a variable
with list of values for equivalent and each value is called a case. The case value must be a
constant. By using switch statement we can create a selection statement in multiple choices. For
this we use switch keyword. The expression of switch statement is an integer type.

SYNTAX:
switch(exp)
{ case lable1: statement;
break;
case label 2: statement ;
break;
:
:
:

36
37 Object Oriented Programing

:
default: statement ;
break;
}

EXAMPLE:
int a=10,b=20,c;
char ch;
switch(ch)
{ case 1: c=a+b;
System.out.println(c);
break;
case 2: c=a-b;
Sytem.out.println(c);
break;
default:System.out.println(“invalid choice”);
}

While loop: When we are working with while loop always prechecking will be occurred i.e. if
the condition is true only the statement block will be executed.If the condition is false it exits the
loop .”while” is a keyword.

EXAMPLE:
class WHILE
{
public static void main(String args[])
{
inti=1;
while(i<5)
{
System.out.print(“ ”+i);
i++;

37
38 Object Oriented Programing

}
}
}

O/P:1 2 3 4
inti=0;
while(i<=10)
{ if(i%2==0)
System.out.print(“ ”+i);
i++;
}
System.out.println(“”);
i=1;
while(i<10)
{ if(i%2!=0)
System.out.print(“ “+i);
i++;
}

O/P:0 2 4 6 8 10
13579

DO-WHILE LOOP: The do-while loop is like while loop but here the condition is tested at the
end of the loop. If the condition is false also at least once the statements will be executed . This is
also called exit conditional loop statement.

SYNTAX:
do
{ statement;
increment/decrement statement;
}while(statement);

EXAMPLE:
intnum=1;
do
{ System.out.println(num);
num++;

38
39 Object Oriented Programing

}while(num<5);

O/P:1 2 3 4
intnum=6;
do
{ System.out.println(num);
num++;
}while(num<5);

O/P:6

FOR LOOP:Java for loop is used to repeat execution of statements until a certain condition is
true.

SYNTAX:for(initialization; condition ; increment/decrement)


{
body of statements;
}

EXAMPLE:for(intnum=2; num<6; num++)


System.out.println(num);

O/P:2 3 4 5

Strings
String is a class in java.lang package .But In java all classes are also considered as data
types.so,we can take ‘String’ as a data type also string is an object of strig class
In java we got character arrays also,but strings are given a different treatment because of their
extensive use on internet.

Example:
=>String s = “Hello”;
Here s is a variable of the data type string

Creating Strings:
There are 3 ways to create a string in java.

39
40 Object Oriented Programing

1)We can create a string just by assigning a group of chars to a string type variable.
Example:
String s;
S=”Java”;
2)We can create an object to string class by allocating memory using new operator this is just like
creating an object to any class.

Example:
String s=s String(“Java programming”);
Here we are doing 2 things,first we are creating objects using new operator then we are storing the
string into the object.
3)Creating the string is by converting the character arrays into string

Example:
Char arr[]={‘h’,’e’,’l’,’l’,’o’};
String s=new String(arr);
In above statement all characters of an array are copied into string.If we don’t want all the
characters of an array into the string then we can also mention which class we need.

Example:
String s=new String(arr,2,3);

String Methods:
There are different kinds of string class methods used to perform on strings

1)Concat:This method concatenates(joints) two strings and returns a 3rd string as a result.
Example:
String s1=”cse”;
String s2=”2c”;
String s3=s1+s2=”cse2c”;

2)Length:This method returns the length or number of characters of a string.


Example:
String s1=”cse”;
S1.length;
This gives the number of characters in the above string i.e. 3.

3)Replace:This method replaces all the occurance of characters c1 by a new char c2.
Example:

40
41 Object Oriented Programing

String s1+”cse”;
S1.replace(‘s’,’y’);
This gives the output as cye

4)toUppercase():This is used to convert the string into upper case letter.


Example:
String s=”sachin”;
System.out.println(s.toUppercase());
This gives the output as SACHIN

5)toLowercase():This is used to convert the string into lower case letter.


Example:
String s=” SACHIN”;
System.out.println(s.toLowercase());
This gives the output as sachin

6)CharAt():This method returns a character at a specified index.


Example:
String s=”India”;
System.out.println(s.CharAt(0));
This gives the output as I

7)ValueOf():The string ValueOf() converts given type such as int,float,long,double,Boolean,char


into a string.

Example:
Int a=10;
String s=String.ValueOf(a);
System.out.println(s+10);
This gives the output as 1010

8)trim():This method eliminates white spaces before and after string.


Example:
String s=” hello ”;
System.out.println(s);

41
42 Object Oriented Programing

This gives the output as ‘hello’

Java String Buffer class:


Java String Buffer class is used to create mutable string (modifiable).The String Buffer class in java is
same as string class except it is mutable i.e. it can be changed.

Note:
Java String Buffer class is a thread safe i.e. multiple threads cannot access simultaneously.

String Buffer class methods:


Same as in string class method.

1) append(): It is used to append the specified string. The append method is overloaded like
append(char),append (Boolean) etc.

2) capacity():it is used to return the current capacity of a string.


Note:
Mutable string means the string that can be modified or changed .String Buffer and String Builder
classes are used for creating mutable string.

Forms of Inheritance:
3. Java supports different forms of inheritance they are
1) Specialisation
2) Specification
3) Construction
4) Extension
5) Limitation

1) Specialisation:It is the most common form of inheritance is for specialization.


In sub classing for specialization the child class Id’s a special case of the parent class. In other
words the child class is the subtype of the parent class.
In this form of the principle of optimality is given a more importance.
Specialisation along with subclassing for specification provides most form of inheritance.

Example:
Java hierarchy of graphical component in AWT.
->component
*label
*Button

42
43 Object Oriented Programing

*Text component
-Text area
-Text field
*Check box
*Scroll bar
Each child class overrides as method inherited from a parent in order to specialize the class.

2) Specification:Another frequent use of inheritance is specification. The parent class defines


behavior that is implemented in the child but not in the parent class
This is actually a special case of subclassing for specialization. The incomplete abstract in the
parent class is known as abstract specification class.

3) Construction:If a parent class is used as a source for behavior, but the child has no
“IsARelationship” to the parent then we say the child class is using inheritance for construction
Example: List class

4)Extension:If a child class is generalized or extends parent class by providing more functionality
but dosent override any method , we call it inheritance for generalization.

Example:Java properties inheriting from hash table.


5) Limitation:If a child class overrides a method inherited from the parent in a way that makes it
unusable, then we call it inherityance for limitatiom.

Example:An existing list data type that allows items to be inserted either the end and you override
the methods allowing insertion at one end inorder to create a stack.

Java Scanner Class:


There are various ways to read input from the keyboard. One of the way is using Scanner class. The
scanner class is in Java.Util package. The Java scanner class breaks the input into tokens using a
delimeter that is white space by default. Java scanner class is used to parse text for string and the
primitive types using regular expression.
Java scanner class extends object class and implement iterator and closes interface.

Method description:
1)nextInt():It scans the next token as integer value.
2)nextDopuble():It reads as double value.
3)next():It reads as string value.
4)nextByte():It reads as a byte value.
5)nextLong():It reads a long value.

43
44 Object Oriented Programing

Program using Scanner class:


Import.Java.Util.*
class Scanner
{
public static void main(String[] args)
{
int a;
String name;
double d;
Scanner sc=new Scanner(System.in);
System.out.println(“Enter rollno,name,fees”);
a=sc.nextInt();
name=sc.next();
d=sc.nextDouble();
}
}
Output:
Enter rollno,name,fees
10
Ashish
9899.9

44
45 Object Oriented Programing

Unit 2 - Packages

45
46 Object Oriented Programing

Explain about packages.


Ans. Packages is a mechanism in which variety of classes and interfaces can be grouped together.
The package statement defines a nameplace in which classes are stored. Packages in Java are
used to prevent naming conflicts to control the access of data. If you omit the package
statement, the classname are put into default package. The packages are like directories in file
system.

SYNTAX:
package packagename;
1. package mypack;
2. package cse2c;
In above statements mypack and cse2c are package names.

ADVANTAGES OF PACKAGES:

1. The classes defined in the packages of other program can be easily reused.
2. Java package is used to characterize the classes and interfaces so that they can be easily
maintained.
3. Java package provides access protection.
4. Two classes from two different packages can have same name. By using the package
name the particular class can be referred.
5. Packages provide the complete separation between the two phases design and coding.
6. Packages hide the classes and interfaces in a separate sub-directory so that accidental
deletion of classes and interfaces will not take place.
7. A group of packages in called a library. The classes and interfaces of a package are like
books in a library and can be reused several times.

EXAMPLE:
package mypack;
public class pack1
{
int a=10,b=20;
void m1()
{ System.out.println(“sum:”+(a+b));}
}
import mypack.*;
class packtest
{ public static void main(String args[])
{ pack1 p=new pack1();
p.m1();

46
47 Object Oriented Programing

}
}
O/P:
sum:30
NOTE: Java package provide access protection, and removes naming collision.

Java API package.


Ans. Java API package is a collection of various packages in which several classes and methods
are grouped together according to their functionality.

API (Application Programming Interface)

JAVA API

applet awt util lang io net sql security

java.applet: This package is for creating and implementing applet.


java.awt: This package is for graphical user interface (GUI). Using the classes and methods of this
package, various components like button, textbox, radio buttons, can be used.
java.lang: This package supports the use of strings, math functions, threads and exception. This
package is always imported by default.
java.util: Various utility classes such as vectors, date, and random numbers are used by using this
package.
java.io: This package is used for supporting input and output operations in Java programming.

47
48 Object Oriented Programing

TYPES OF PACKAGES:
Q. Explain different types of packages in Java.
Ans. There are two different types of packages in Java. They are:
I. Built-in packages/predefined packages
II. User defined packages

Built-In packages: These are the packages which are already available in java language. These
packages provide almost all necessary classes, interfaces and methods for the programmer to
perform any task in his program.
ex: java.lang,java.util,java.io,java.awt,java.swing,java.net,java.applet,java.text,java.sql,
java.times.

User-defined packages: It is like built-in packages the users of Java language can also create
their own packages. They are called user-defined packages. User-defined packages can also be
imported into other classes and used exactly in the same way as built-in packages.
ex: package packagename;

import keyword.
Ans. If a class wants to use another class in the same package, the package name need not be
used.
Classes in the same package find each other without any special syntax using import keyword. A
class file can contain any number of import statements. The import statement must appear after
the package statement and before the class declaration.
Import keyword is used to import built-in packages and user-defined packages into your Java
source file.

Explain classpath.
Ans. Class path is a parameter in the JVM or the compiler that specifies the location of
user-defined classes and packages. The parameter may be set either on the
command line or through an environment variable. It is an environment variable which
contains the path for the default working directory. The specific location that Java
compiler will consider, as the route of any package hierarchy is controlled by
classpath.

Stream
Ans. A stream is basically a channel on which the data flows from sender to receiver. Different
streams are needed to send or receive data through different sources such as to receive data
from keyboard we need a stream and to send data to a file we need another stream. Without
streams it is not possible to move data in Java .An input object that reads the stream of data from

48
49 Object Oriented Programing

file is called input stream. The output object that writes the stream of data to a file is called output
stream.
In java, 3 streams are created for us automatically. All these streams are attached with console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream

Types Of Streams :
I) Byte stream
II) Character stream.

Bytestream: The bytestream is used to input or output the bytes. There are two superclasses in
bytestream. Those are:
i) InputStream
ii) OutputStream
From which most of other classes are derived. There are two important methods such as read() and
write(). There are different input stream classes:

InputStream
Java application uses an input stream to read data from a source, it may be a file, an array,
peripheral device or socket.

InputStream class
InputStream class is an abstract class. It is the super class of all classes representing an input stream
of bytes.

49
50 Object Oriented Programing

Useful methods of InputStream


Method Description
1) public abstract int reads the next byte of data from the input stream.
read()throws IOException It returns -1 at the end of file.
2) public int available()throws returns an estimate of the number of bytes that
IOException can be read from the current input stream.
3) public void close()throws is used to close the current input stream.
IOException

Java FileInputStream Class


Java FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented data
(streams of raw bytes) such as image data, audio, video etc. You can also read character-stream
data. But, for reading streams of characters, it is recommended to use FileReader class.

Declaration
Let's see the declaration for java.io.FileInputStream class:
public class FileInputStream extends InputStream

Methods
Method Description
int available() It is used to return the estimated number of bytes that can
be read from the input stream.
int read() It is used to read the byte of data from the input stream.

int read(byte[] b) It is used to read up to b.length bytes of data from the


input stream.
int read(byte[] b, int It is used to read up to len bytes of data from the input
off, int len) stream.
long skip(long x) It is used to skip over and discards x bytes of data from the
input stream.
FileChannel It is used to return the unique FileChannel object associated
getChannel() with the file input stream.
FileDescriptor getFD() It is used to return the FileDescriptor object.

protected void It is used to ensure that the close method is call when there
finalize() is no more reference to the file input stream.
void close() It is used to closes the stream.

Example: Reading single character


import java.io.FileInputStream;

50
51 Object Oriented Programing

public class DataStreamExample {


public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=fin.read();
System.out.print((char)i);

fin.close();
}catch(Exception e){System.out.println(e);}
}
}
Note: Before running the code, a text file named as "testout.txt" is required to be created. In this file,
we are having following content:
Welcome to java.
After executing the above program, you will get a single character from the file which is 87 (in byte
form). To see the text, you need to convert it into character.
Output:
W
Example 2: Reading all characters
import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=0;
while((i=fin.read())!=-1){
System.out.print((char)i);
}
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
Output:

51
52 Object Oriented Programing

Welcome to java

Java DataInputStream Class


Java DataInputStream class allows an application to read primitive data from the input stream in a
machine-independent way.
Java application generally uses the data output stream to write data that can later be read by a
data input stream.

Declaration
Let's see the declaration for java.io.DataInputStream class:
public class DataInputStream extends FilterInputStream implements DataInput

Methods
Method Description
int read(byte[] b) It is used to read the number of bytes from the input
stream.
int read(byte[] b, int off, int It is used to read len bytes of data from the input
len) stream.
int readInt() It is used to read input bytes and return an int value.

byte readByte() It is used to read and return the one input byte.

char readChar() It is used to read two input bytes and returns a char
value.
double readDouble() It is used to read eight input bytes and returns a
double value.
boolean readBoolean() It is used to read one input byte and return true if
byte is non zero, false if byte is zero.
int skipBytes(int x) It is used to skip over x bytes of data from the input
stream.
String readUTF() It is used to read a string that has been encoded
using the UTF-8 format.
void readFully(byte[] b) It is used to read bytes from the input stream and
store them into the buffer array.
void readFully(byte[] b, int It is used to read len bytes from the input stream.
off, int len)

Example
In this example, we are reading the data from the file testout.txt file.
import java.io.*;

public class DataStreamExample {

52
53 Object Oriented Programing

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

InputStream input = new FileInputStream("D:\\testout.txt");


DataInputStream inst = new DataInputStream(input);
int count = input.available();

byte[] ary = new byte[count];

inst.read(ary);
for (byte bt : ary) {

char k = (char) bt;

System.out.print(k+"-");
}
}
}
Here, we are assuming that you have following data in "testout.txt" file:
JAVA
Output:
J-A-V-A

OutputStream
Java application uses an output stream to write data to a destination, it may be a file, an array,
peripheral device or socket.

53
54 Object Oriented Programing

OutputStream class
OutputStream class is an abstract class. It is the super class of all classes representing an output
stream of bytes. An output stream accepts output bytes and sends them to some sink.

Useful methods of OutputStream


Method Description
1)public void write(int) throws Is used to write a byte to the current output
IOException stream.
2)public void write(byte[]) Is used to write an array of byte to the current
throws IOException output stream.
3)public void flush() throws Flushes the current output stream.
IOException
4)public void close() throws Is used to close the current output stream.
IOException

Java FileOutputStream Class


Java FileOutputStream is an output stream used for writing data to a file.
If you have to write primitive values into a file, use FileOutputStream class. You can write byte-
oriented as well as character-oriented data through FileOutputStream class. But, for character-
oriented data, it is preferred to use FileWriter than FileOutputStream.

Declaration
Let's see the declaration for Java.io.FileOutputStream class:
1. public class FileOutputStream extends OutputStream

Methods
Method Description
protected void finalize() It is sued to clean up the connection with the file output
stream.
void write(byte[] ary) It is used to write ary.length bytes from the byte array
to the file output stream.
void write(byte[] ary, int It is used to write len bytes from the byte array starting
off, int len) at offset off to the file output stream.
void write(int b) It is used to write the specified byte to the file output
stream.
FileChannel It is used to return the file channel object associated with
getChannel() the file output stream.
FileDescriptor getFD() It is used to return the file descriptor associated with the
stream.

54
55 Object Oriented Programing

void close() It is used to closes the file output stream.

Example 1: write byte


import java.io.FileOutputStream;

public class FileOutputStreamExample {

public static void main(String args[]){

try{

FileOutputStream fout=new FileOutputStream("D:\\testout.txt");


fout.write(65);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}
Output:
Success...
The content of a text file testout.txt is set with the data
A.

testout.txt
A

Example 2: write string


import java.io.FileOutputStream;

public class FileOutputStreamExample {

public static void main(String args[]){

try{

FileOutputStream fout=new FileOutputStream("D:\\testout.txt");


String s="Welcome to java.";
byte b[]=s.getBytes();//converting string into byte array

fout.write(b);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}

55
56 Object Oriented Programing

}
Output:
Success...
The content of a text file testout.txt is set with the data
Welcome to java.

testout.txt
Welcome to java.

Java DataOutputStream Class


Java DataOutputStream class allows an application to write primitive Java data types to the
output stream in a machine-independent way.
Java application generally uses the data output stream to write data that can later be read by a
data input stream.

Declaration
Let's see the declaration for java.io.DataOutputStream class:
public class DataOutputStream extends FilterOutputStream implements DataOutput

Methods
Method Description
int size() It is used to return the number of bytes written to the
data output stream.
void write(int b) It is used to write the specified byte to the underlying
output stream.
void write(byte[] b, int off, It is used to write len bytes of data to the output
int len) stream.
void writeBoolean(boolean v) It is used to write Boolean to the output stream as a
1-byte value.
void writeChar(int v) It is used to write char to the output stream as a 2-
byte value.
void writeChars(String s) It is used to write string to the output stream as a
sequence of characters.
void writeByte(int v) It is used to write a byte to the output stream as a 1-
byte value.
void writeBytes(String s) It is used to write string to the output stream as a
sequence of bytes.
void writeInt(int v) It is used to write an int to the output stream

void writeShort(int v) It is used to write a short to the output stream.

56
57 Object Oriented Programing

void writeShort(int v) It is used to write a short to the output stream.

void writeLong(long v) It is used to write a long to the output stream.

void writeUTF(String str) It is used to write a string to the output stream using
UTF-8 encoding in portable manner.
void flush() It is used to flushes the data output stream.

Example
In this example, we are writing the data to a text file testout.txt using DataOutputStream class.
import java.io.*;

public class OutputExample {

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

FileOutputStream file = new FileOutputStream(D:\\testout.txt);


DataOutputStream data = new DataOutputStream(file);
data.writeInt(65);
data.flush();
data.close();
System.out.println("Succcess...");
}
}
Output:
Succcess...
testout.txt:
A

57
58 Object Oriented Programing

Difference between Byte stream and Character stream.


Ans.
Byte Stream Character Stream
Byte stream is used for inputting and The character stream is used for inputting
outputting bytes. and outputting the characters.

There are two super classes used in Byte There are two super classes used in
stream those are InputStream and Character Stream those are Reader and
OutputStream. Writer.

It never supports Unicode character. It supports Unicode characters.

Console input and output statements in java.


Ans. The only way to perform console input was to use a Bytestream and older code that uses this
approach. Java doesn’t have a generalized console input method that parallels the standard C
function scanf or C++ input operators. When we want to read some characters from the console
we should make use of System.in . The Character stream class is BufferedReader. BufferedReader
supports a BufferedInputStream infact we should pass the variable or Sytem.in to BufferedReader
object. Alongwith this we should also mention the abstract class of BufferedReader class which is
InputStreamReader .

Syntax:
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
The InputStreamReader converts bytes into characters.
READING CHARACTERS:
To read a character from BufferedReader use read() method. Each time the read is called it reads
a character from the input stream and returns it as an integer value. It return -1 when the end of
stream is encountered it can throw an IOException .

READING STRING:
The readline() method is used to read strings from BufferedReader class.
file input stream and output stream.

Serialization in Java.
Ans. The process of converting an object from normal Java support form into file supported form or
network supported form is called serialization.
The process of saving state of object into file is called serialization.

58
59 Object Oriented Programing

SERIALIZATION

Java
support File/network
form support form

Deserialization: The process of reading an object from file is called deserialization or the process
of converting file or network support form into Java support form is called deserialization.
For serialization we use FileOutputStream class and ObjectOutputStream class.
For deserialization we use FileInputStream class and ObjectInputStream class.
Create ObjectOutputStream class is used to writeObject method. It takes object and converts it
into binary data.
Create ObjectInputStream is used to readObject method. It takes object from file.
Ex: class Student
{
int i=10;
int j=20;
}
class Serialization
{ public static void main(String args[])
{ Student s=new Student ();
FileOutputStream fos=new FileOutputStream(“abc.txt”);
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(s);
FileIntputStream fis=new FileInputStream(“abc.txt”);
ObjectInputStream ois=new ObjectInputStream(fis);
Student s2= ( Student).ois.readObject();
System.out.println(s2.i);
System.out.println(s2.j);

59
60 Object Oriented Programing

}
}

SERIALIZATION
i=10
File/network
j=20 support
form

i=10

j=20 DESERIALIZATION

Q. Explain enum.
Ans. An enumeration is a list of named constants under a singlename. Enumeration defines
classtype. By making enumerations into classes, the capabilities of enumeration are greatly
expanded. An enumeration is created using enum keyword.
NOTE: If you want to represent a group of named constants then we should go for enum, to define
our own datatypes we use enumerated datatypes.
Enum is a part of every programming language but it is in Java programming language because it
allows constants,variables and methods, constructors.
ex:
i)enum Day
{ Sunday,Monday,Tuesday
}
ii) enum color
{ red,white ,blue
}
In above syntax red,white,blue are identifiers which are called enumeration constants. Each one is
declared as public static and final member of color. Once defined enumeration we can create a
variable of that type however eventhough enumerations define a class type , you don’t instantiate
enum using new. Instead we declare and use enum variable in the same way as we do one of the
primitive types
Day d;
color cr;
Here d,cr variables of enumeration type Day,color.

60
61 Object Oriented Programing

example 1:
class Color
{ red,blue, white
}
class EnumDemo
{ public static void main(String args[])
{ Color cr;
cr=Color.blue;
System.out.println(cr);
}
}
O/P: blue
Values() and ValueOf():These two methods are used in enumeration automatically .The Values()
method returns an array that contains a list of enumeration constants.
The ValueOf() method returns the enumeration constant whose value corresponds to the string
passed in str in both cases enum type is the type of enumeration.

Syntax:
public static enum_type[] Values();
public static enum_type ValueOf(String str);
example:
class EnumExample
{ public class enum Day
{ Monday,Tuesday,Wednesday,Sunday
}
public static void main(String args[])
{ for(Day d: Day.values())
System.out.println(d);
}
}
O/P: Monday
Tuesday
Wednesday

61
62 Object Oriented Programing

Sunday
NOTE: enum does not support extended by other parent class and not extends to child class
because multiple inheritance is not possible in Java language and we cannot create an object of
enum. The enum is child class of java.lang.Enum class.

Write short note on autoboxing.


Ans. Automatic conversion of primitive to wrapper object by compiler is called autoboxing.
Ex: Integer I=10;
The compiler converts above line Integer to int. After compilation of the above line it will become
Integer I= Integer.ValueOf(10);
i.e. internally autoboxing concept is implemented by using valueOf() method.
AUTONBOXING: The wrapper class object converted to primitive type that is called autonboxing.
Integer I= new Integer(10);
int i=I;
After compilation the above line
int i=I.intValue();

Wrapper class.
Ans. A wrapper class is a class whose objects wraps or contains primitive datatype. When we
create an object to a wrapper class it contains a field. In this field we can store primitive datatype.
The advantage or objective of wrapper class is it convert primitive datatype into objects. The
classes in java.util package handle only objects and hence wrapper classes help in this case.

primitive datatype corresponding wrapper class


int Integer
char Character
byte Byte

Generics in Java
Ans. The main objective of generics are to provide type safety and resolve type casting problems.
A generic class represents a class that is typesafe. This means a generic class can act upon any
datatype .when a generic class or generic interface is written the programmer need not rewrite
the same class or interface whenever he wants to use the class within a new datatype. before
generics we can store any type of objects in collection i.e. non-generic.
Now in generics we can store only a specific type of objects. There are three main advantages of
generics:
i) Type safety: We can hold only a single type of objects in generics . It doesn’t allow to
store other objects. ex:arrays.

62
63 Object Oriented Programing

ii) Type casting is not required.


There is no need to typecast the objects.
Before generics we need to typecast.
ex: ArrayList AL=new ArrayList();
list.add(“hello”);
String S=(String)list.get(0);
After generics we need not typecast the object
ArrayList <string> list=new ArrayList<string> ();
list.add(“hello”);
String s=list.get(0);
i) Compile time checking
It is checked at compile time so problem will not occur at runtime. The good programming strategy
says it is far better to handle the problem at compile time than at runtime.

Java Inner Classes


Java inner class or nested class is a class which is declared inside the class or interface.
We use inner classes to logically group classes and interfaces in one place so that it can be more
readable and maintainable.
Additionally, it can access all the members of outer class including private data members and
methods.

Syntax
class Java_Outer_class{

//code

class Java_Inner_class{

//code

}
}

Advantage of java inner classes


There are basically three advantages of inner classes in java. They are as follows:
1) Nested classes represent a special type of relationship that is it can access all the members
(data members and methods) of outer class including private.
2) Nested classes are used to develop more readable and maintainable code because it logically
group classes and interfaces in one place only.
3) Code Optimization: It requires less code to write.

63
64 Object Oriented Programing

Difference between nested class and inner class in Java


Inner class is a part of nested class. Non-static nested classes are known as inner classes.

Types of Nested classes


There are two types of nested classes non-static and static nested classes.The non-static nested
classes are also known as inner classes.
 Non-static nested class (inner class)
o Member inner class
o Anonymous inner class
o Local inner class
 Static nested class

Type Description
Member Inner A class created within class and outside method.
Class
Anonymous Inner A class created for implementing interface or extending class. Its
Class name is decided by the java compiler.
Local Inner Class A class created within method.
Static Nested A static class created within class.
Class
Nested Interface An interface created within class or interface

Java Member inner class


A non-static class that is created inside a class but outside a method is called member inner class.

Syntax:

class Outer{

//code

class Inner{

//code

}
}

Example
In this example, we are creating msg() method in member inner class that is accessing the private
data member of outer class.
class TestMemberOuter1{

private int data=30;

64
65 Object Oriented Programing

class Inner{

void msg(){System.out.println("data is "+data);}

}
public static void main(String args[]){

TestMemberOuter1 obj=new TestMemberOuter1();


TestMemberOuter1.Inner in=obj.new Inner();
in.msg();
}
}

Output:
data is 30

Internal working of Java member inner class


The java compiler creates two class files in case of inner class. The class file name of inner class is
"Outer$Inner". If you want to instantiate inner class, you must have to create the instance of outer
class. In such case, instance of inner class is created inside the instance of outer class.

Java Anonymous inner class


A class that have no name is known as anonymous inner class in java. It should be used if you have
to override method of class or interface. Java Anonymous inner class can be created by two
ways:
1. Class (may be abstract or concrete).
2. Interface

Anonymous inner class Example using class


abstract class Person{

abstract void eat();

}
class TestAnonymousInner{

public static void main(String args[]){

Person p=new Person(){


void eat(){System.out.println("nice fruits");}

};
p.eat();
}

65
66 Object Oriented Programing

}
Output:
nice fruits

Internal working of given code


1. Person p=new Person(){
2. void eat(){System.out.println("nice fruits");}
3. };

1. A class is created but its name is decided by the compiler which extends the Person class
and provides the implementation of the eat() method.

2. An object of Anonymous class is created that is referred by p reference variable of Person


type.

Internal class generated by the compiler


1. import java.io.PrintStream;
2. static class TestAnonymousInner$1 extends Person
3. {
4. TestAnonymousInner$1(){}
5. void eat()
6. {
7. System.out.println("nice fruits");
8. }
9. }

Java anonymous inner class example using interface


1. interface Eatable{
2. void eat();
3. }
4. class TestAnnonymousInner1{
5. public static void main(String args[]){
6. Eatable e=new Eatable(){
7. public void eat(){System.out.println("nice fruits");}
8. };
9. e.eat();
10. }
11. }
Output:
nice fruits

66
67 Object Oriented Programing

Internal working of given code

It performs two main tasks behind this code:

1. Eatable p=new Eatable(){


2. void eat(){System.out.println("nice fruits");}
3. };

1. A class is created but its name is decided by the compiler which implements the Eatable
interface and provides the implementation of the eat() method.

2. An object of Anonymous class is created that is referred by p reference variable of Eatable


type.

Internal class generated by the compiler


1. import java.io.PrintStream;
2. static class TestAnonymousInner1$1 implements Eatable
3. {
4. TestAnonymousInner1$1(){}
5. void eat(){System.out.println("nice fruits");}
6. }

Java Local inner class


A class i.e. created inside a method is called local inner class in java. If you want to invoke the
methods of local inner class, you must instantiate this class inside the method.

Example
1. public class localInner1{
2. private int data=30;//instance variable
3. void display(){
4. class Local{
5. void msg(){System.out.println(data);}
6. }
7. Local l=new Local();
8. l.msg();
9. }
10. public static void main(String args[]){

67
68 Object Oriented Programing

11. localInner1 obj=new localInner1();


12. obj.display();
13. }
14. }
Output:
30

Internal class generated by the compiler


In such case, compiler creates a class named Simple$1Local that have the reference of the outer
class.

1. import java.io.PrintStream;
2. class localInner1$Local
3. {
4. final localInner1 this$0;
5. localInner1$Local()
6. {
7. super();
8. this$0 = Simple.this;
9. }
10. void msg()
11. {
12. System.out.println(localInner1.access$000(localInner1.this));
13. }
14. }

Rule: Local variable can't be private, public or protected.

Rules for Java Local Inner class

1) Local inner class cannot be invoked from outside the method.


2) Local inner class cannot access non-final local variable till JDK 1.7. Since JDK 1.8, it is possible to access
the non-final local variable in local inner class.

Example of local inner class with local variable


1. class localInner2{
2. private int data=30;//instance variable
3. void display(){
4. int value=50;//local variable must be final till jdk 1.7 only

68
69 Object Oriented Programing

5. class Local{
6. void msg(){System.out.println(value);}
7. }
8. Local l=new Local();
9. l.msg();
10. }
11. public static void main(String args[]){
12. localInner2 obj=new localInner2();
13. obj.display();
14. }
15. }
Output:
50

Java static nested class


A static class i.e. created inside a class is called static nested class in java. It cannot access non-
static data members and methods. It can be accessed by outer class name.
It can access static data members of outer class including private.
Static nested class cannot access non-static (instance) data member or method.

Java static nested class example with instance method


1. class TestOuter1{
2. static int data=30;
3. static class Inner{
4. void msg(){System.out.println("data is "+data);}
5. }
6. public static void main(String args[]){
7. TestOuter1.Inner obj=new TestOuter1.Inner();
8. obj.msg();
9. }
10. }
Output:
data is 30
In this example, you need to create the instance of static nested class because it has instance
method msg(). But you don't need to create the object of Outer class because nested class is
static and static properties, methods or classes can be accessed without object.

69
70 Object Oriented Programing

Internal class generated by the compiler


1. import java.io.PrintStream;
2. static class TestOuter1$Inner
3. {
4. TestOuter1$Inner(){}
5. void msg(){
6. System.out.println((new StringBuilder()).append("data is ")
7. .append(TestOuter1.data).toString());
8. }
9. }

Static nested class example with static method


If you have the static member inside static nested class, you don't need to create instance of static
nested class.

1. class TestOuter2{
2. static int data=30;
3. static class Inner{
4. static void msg(){System.out.println("data is "+data);}
5. }
6. public static void main(String args[]){
7. TestOuter2.Inner.msg();//no need to create the instance of static nested class
8. }
9. }
Output:
data is 30

70
71 Object Oriented Programing

UNIT 3: Exception Handling

71
72 Object Oriented Programing

Q.1. Define an exception.


Ans. An exception is an unwanted and unpredictable event that disturbs the normal flow of
program is called exception. An exception can be anything which interrupts the normal flow of
program. When an exception occurs program processing gets terminated, and doesn’t continue
further processing. In such cases we need a system generated error message. For this is java
programming we have exception handling mechanism. It is used to handle the runtime errors so
that normal flow of program can be maintained.
An exception is a runtime error. It is a problem that may arise during the execution of the program.
NOTE: In java we cannot call compile time errors as exceptions. All exceptions occur at runtime but
some exceptions are detected at runtime. The exceptions that are checked at compilation time
by java compiler.
The exceptions that are checked at runtime by JVM.
Reasons for exception:
Exception can occur at runtime as well as compile time. An exception can occur for different
reasons by following:
A user has entered an invalid data. A file that needs to be opened cannot be found/opened
(FileNotFound).
Division by zero.

What is exception handling? What are the Advantages of


exception handling.
Ans. Exception handling is a mechanism to handle runtime errors.
Ex: ClassNotFound, IOException, SQLException, RemoteException.
An exception handling mechanism provides an alternative way to provide graceful termination of
program that means when exception occurs we lose some data so that exception handler won’t
lose our data in program.

NOTE: If an exception is raised which has not been handled by the programmer then program
execution gets terminated and system generates a non-user friendly error-message.

ADVANTAGES:
1. Exception handling allows to control the normal flow of program by using exception handling in
program.
2. Exception handling in java is to continue program execution after an exception is caught and
handled.

72
73 Object Oriented Programing

3. It throws an exception whenever a calling method encounters an error providing that the calling
method takes care of that error.
4. It also gives us the scope of organizing and differentiating between different blocks of codes.
5. Propagating errors of the call stack.

Explain different types of Exception.


Ans. There are two types of exception in java. All exception classes are subclasses of
Java.lang.Exception class. The Exception class is a subclass of the Throwable class. Following are
types of exception

i) Checked exception
ii) Unchecked exception

i) Checked exception: the exceptions that are checked at compile-time by java compiler
are called checked exceptions. All exceptions other than runtime exceptions are known
as checked exceptions. These exceptions cannot simply be ignored at the time of
compilation the programmer should take care of handling these exceptions.

Ex: a file that needs to be opened is not found. These type of exceptions must be checked at
compile time.
Ex: import java.io.File;
importjava.io.FileReader;
public class FileNotFoundDemo
{
public static void main(String args[])
{
File f=new File(“abc.txt”);
FileReaderfr=new FileReader(f);
}
}

ii) Unchecked exception: the exceptions that are checked by the JVM are called
unchecked exceptions. Unchecked exceptions and errors are considered to be
unrecoverable and the programmer cannot do anything when the unchecked
exceptions occur in our program. The programmer can write a java program with
unchecked exceptions and compile the program he can see their effect only when he
runs/executes the program. The unchecked exceptions include programming hubs such
as logic errors or improper use of an API finally runtime exceptions are ignored at the
time of compilation.

73
74 Object Oriented Programing

ex: ArrayIndexOutOfBoundsException exception


classExceptionDemo
{
public static void main(String args[])
{
int a[]={1,2,3,4,5};
System.out.println(a[10]);
}
}
O/P:runtime error

Examples of unchecked exception:


1. ArithmeticException: if we divide any number by 0 this occurs an ArithmeticException.
int a=50/0;
2. NullPointerException: if we have null value in any variable performing any operation by the
variable it gives null pointer exception.
String s=NULL;
System.out.println(s.length());
ArrayIndexOutOfBoundException.

Q.4. Discuss about exception handling.


Ans. All exception classes are subtypes of the Java.lang.Exception class. The Exception class is
subclass of Throwable class. Other than the Exception class there is another subclass called Error
which is derived from the Throwable class.

NOTE:
i. Throwable class is a class that represents all errors and exceptions which may occur in java.
ii. The exception is the superclass of Exceptions in java.
iii. An exception is an error which can be handled. It means when an exception happens the
programmer can do something to avoid any harmful data, but an error is an error which
cannot be handled. It happens and programmer cannot do anything

74
75 Object Oriented Programing

Object

Throwable

Exception Error

Virtual
Runtime SQL I/O Machine Assertion
Error

ArithmeticException ArrayIndexOutOfbounds Null Pointer FileNotFound

Write short note on exception handling keywords.


Ans. There are 5 types of keywords used in Java exception handling.
i. try: a block of source code i.e. to be mentioned for exception. Generally in the key block
we have to write risk code.
ii. catch: catch block handles the specific type of exception alongwith try block. Note that for
each block corresponding try block there exists catch block.
iii. finally: it specifies the code that must be executed eventhough exception may or maynot
occur.
iv. throw: this keyword is used throw specific exception from program code.
v. throws: it specifies the exceptions that can be thrown by particular method.

Q.6. Explain try catch block with example.


Ans. the try block contains a set of statements where an exception can occur. A try block is always
followed by a catch block,which handles the exception that occur in associated try block. A try
block must be followed by catch block or finally block or both.
Java try block is used to enclose the code that might throw an exception. It must be used within
the method.

75
76 Object Oriented Programing

Syntax:
try
{//statements may cause exception/risk code
}
catch block:
1. Java catch block is used to handle the exception. It must be used after the try block only. We
can use multiple catch block with a single try block.
2. We can catch different exceptions in different catch blocks when an exception occurs in try
blocks the corresponding catch block that handles that particular exception executes.

Ex:
public class Testrycatch
{
public static void main(String args[])
{
int x=100/0;
System.out.println(“rest of programming code”);
}
}
O/P: exception in thread main java.lang.ArithmeticException: / by zero
Therefore, in the above program the rest of program code not executed.
Solutionof above program:
public class Testtrycatch
{
public static void main(String args[])
{
try
{
int x=100/0;
}
catch(ArithmeticException e)
{
System.out.println(e);

76
77 Object Oriented Programing

}
System.out.println(“rest of code”);
}
}

Exception
Causing •Try Block

Exception
• Catch
handling
statements
Block

Multiple catch blocks:


A try block can be followed by multiple catch blocks. We can have any no. of catch blocks after a
single try block. If an exception occurs in the guarded code the exception is passes to the first
catch block in the list. If the exception type of exception matches with the first catch block gets
caught, if not the exception is passed down to next catch block. This continues until the exception
is caught or falls through all the catches.

Ex:
class Example
{
public static void main(String args[])
{
try
{
intarr[]={10,20};

77
78 Object Oriented Programing

arr[3]=30/0;
}
catch(ArithemticException ar)
{
System.out.println(“division by zero”);
}
catch(ArrayIndexOutOfBOundsException e)
{
System.out.println(“Array Index exception”);
}
}
}
O/P:division by zero
Syntax:
try
{
//risk/exception code
}
catch(exceptiontype e)
{ //exception;
}
catch(exceptiontype e)
{// exception;
}
NOTE:
1. Although both ArrayIndexOutOfBoundsExceptionand ArithemticException occurred, but
since first catch is of ArithmeticException it will be caught there and program control will be
continued after the catch block.
2. At a time, only one exception is processed, and only one respective catch block is
executed.

Ex 2:
classExample
{

78
79 Object Oriented Programing

public static void main(String args[])


{
try
{
intarr[]={10,20};
arr[3]=30/0;
}
catch(Exception e)
{
System.out.println(“generic exception”);
}
catch(ArrayIndexOutOfBOundsException e)
{
System.out.println(“Array Index exception”);
}
}
}

O/P: generic exception


Note: while using multiple catch statements, it is important to remember that subclasses of class
Exception inside catch must come before any of their super classes otherwise it will lead to compile
time error.

Ex 3:
class Example
{
public static void main(String args[])
{
try
{
intarr[]={10,20};
arr[3]=30/0;
System.out.println(“first statement”);
}

79
80 Object Oriented Programing

catch(ArithemticException ar)
{
System.out.println(“division by zero”);
}
catch(ArrayIndexOutOfBOundsException e)
{
System.out.println(“Array Index exception”);
}
catch(Exception e)
{
System.out.println(“ some other exception”);
}
System.out.println(“out of try catch block”);
}
}
O/P: first statement
division by zero
out of try catch block
In above program there are multiple catch blocks and these catch blocks executes sequentially
when an exception occurs in try block which means if you put the last catch bock at the first place
just after the try block then in case of any exception this block will execute because it can handle
all exceptions.

NESTED TRY STATEMENTS


i) When there are chances of occurring multiple exceptions of different types
by the same set of statements then such situation can be handled using
nested try statement.
ii) try statement can be nested inside another block of try.

Ex:
classExampleNestedtry
{
public static void main(String args[])
{
try

80
81 Object Oriented Programing

{
intarr[]={1,2,3,4,5};
try
{
int x=arr[3]/arr[1];
}
catch(ArithemeticException ar)
{
System.out.println(“division by zero”);
}
arr[5]=3;
}
catch(ArrayIndexOutofBoundsException e)
{
System.out.println(“array index exception”);
}
}
}
O/P: divison by zero
array index exception

Finally block:
1. finally is a block always associated with try catch to maintain clean-up code.
2. Sometimes because of execution try block the execution breakoff and due to
this some important code may not get executed that means sometimes try bloc
may bring some unwanted things to happen.
3. The finally provides the assurance of execution of some important code that
must be executed after try block.
4. Even though there is any exception in try block the statements assured by finally
block are sure to execute.
5. These statements are sometimes called as clean-up code.
Syntax:
finally
{//clean-up code
81
82 Object Oriented Programing

}
6. Java finally block is always executed whether exception is handled/not.

Ex:
classFinallyEx
{
public static void main(String args[])
{ int a=20,b=-1;
try
{ b=a/0;
}
catch(ArithmeticExeption e)
{
System.out.println(e);
}
finally
{
if(b!=1)
{
System.out.println(“without exception”);
}
else
System.out.println(“exception”);
}
}
}
O/P: in catch block: java.lang.ArithmeticException : / by zero
Exception

Throws keyword:
1. We can use to delegate responsibility of exception handling to the caller (it
maybe method or JVM)

82
83 Object Oriented Programing

2. It is required only for checked exception and usage of throws keyword for
unchecked exception there is no use.
3. It is required only for convenience of compiler and usage of throws does not
prevent abnormal termination of program.

NOTE: the java throws keyword is used to declare an exception. it gives an


information to the programmer that there may occur an exception so it is better for
programmer to provide the exception handling code so that normal flow can be
maintained.
Ex:
classThrowses
{
static void check() throws ArithemticException
{
System.out.println(“inside check function”);
throw new ArithmeticException(“demo”);
}
public static void main(String args[])
{
try
{
check();
}
catch(ArithmeticException e)
{
System.out.println(e);
}
}
}
O/P: inside check function
caught java.lang.Arithmetic Exception
demo

83
84 Object Oriented Programing

Throw keyword:
1. Java throw keyword is used to explicitly throw an exception. we can throw
either checked/unchecked exception in java by throw keyword. the throw
keyword is mainly used throw custom exception.
Syntax:
throw exception;
ex: class Throwex
{
static void validate(int age)
{
if(age<18)
throw new ArithmeticException (“not valid voter”);
else
System.out.println(“welcome to vote”);
}
public static void main(String args[])
{
validate(13);
System.out.println(“rest of code”);
}
}
O/P: exception in thread main java.lang.ArithmeticException : not valid voter.
NOTE: sometimes we can create exception object explicitly we can handover to
JVM manually, for this we have to use throw keyword.

RETHROWING EXCEPTION
Sometimes the exception which is just caught need to be throw again. Since we
have already the reference to the current exception we can simply re-throw
that reference.
Ex:
class A
{
public static void main(String args[]) throws ArithmeticException
{
try
{
int a=30,b=0;
int c=a/b;
}
catch(ArithmeticException e)

84
85 Object Oriented Programing

{
System.out.println(“Caught exception:”+e);
throw e;// rethrowing of exception
}
}
}

Multi-Threading
What is thread and what is multi-threading?
Multi-Threading: The process of executing multiple threads simultaneously is known as multi-
threading.
Multi-threading is a specialized form of multi-tasking.
Thread: Thread is basically a light weight process (or) thread is a tiny program running continuously.
A thread represents a separate path of execution of a group of statements. These statements are
executed by JVM one by one.
Advantages of multi-threading
 It does not block the user because threads are independent and you can perform multiple
operations at the same time.
 We can perform many operations together so it saves time.
 Threads are independent so it does not affect any other threads if exception occurs in a
single thread.

Define Multi-tasking and Explain different types of multi-


tasking?
Multi-Tasking: Executing multiple tasks simultaneously is called multi-tasking. We use multi-tasking to
utilize the CPU to use the processor’s time in an efficient way we can give it several jobs at a time.
The main advantage of multi-tasking is to use the processor’s time in a better way. We are
engaging most of the processor’s time and it is not sitting idle. In this way we can complete several
tasks at a time, and thus we achieve good performance.
There are two types of multi-tasking

85
86 Object Oriented Programing

1. Process based multi-tasking.


2. Thread based multi-tasking

Process based multi-tasking:


Executing several tasks simultaneously where each task is a separate independent
program/process. Such a type of multi-tasking is called process based multi-tasking.
In process based multi-tasking several programs are executed at a time, by the micro-processor.
In this each process has its own address in memory i.e. each process allocates separate area.
Process is heavy weight.
The cost of communication between the processes is high.
Switching from one program to another requires some time for saving and loading the registers,
memory maps and updating lists.
Example: Process based multi-tasking enables you to run the java compiler at the same time you
listen to music.
Thread Based Multi-tasking:
Executing several tasks simultaneously where each task is a separate independent part of the
same program, such type of multi-tasking is called thread based multi-tasking.
In this several parts of the same program are executed at the same time the micro-processor.
1. Threads share the same address space.
2. Thread is light-weight.
3. The cost of communication between threads is low.
4. At least one process is required for each thread.
5. It is best suitable at programmatic level.

Example: A text editor can format text at the same time that it is printing. These two actions are
being performed by two separate threads.

Java Thread Model


1. The java runtime system depends on the threads for many things, and all the class libraries
are designed with multi-threading in mind.

2. Java uses threads to enable the entire environment to be asynchronous. This helps reduce
inefficiency by preventing the waste of CPU cycles.

3. The value of a multi-threaded environment is best understood in contrast to its counterpart.


Single threaded systems use an approach called an event loop with polling0

4. In this model, a single thread of control runs in an infinite loop, polling a single event queue
to decide what to do next.

86
87 Object Oriented Programing

5. Once this polling mechanism returns with, say a signal that a network file is ready to be
read, then the event loop dispatches the control to the appropriate event handler. Until this
event handler returns, nothing else happens in the program. This wastes CPU’s time.

6. The benefit of java multi-threading is the main loop/ polling mechanism is eliminated. One
thread can pause without stopping other parts of the program.

7. When a thread blocks in a java program, only the single thread that is blocked pauses, all
the other threads continue to run.

What are the various methods/types of executing threads in java?


There are two ways to create a thread in java:
1. Extends thread class
2. Implements runnable interface

Both the Thread class and Runnable interface are found in java.lang package
Extends Thread:
Create a new class that extends Thread, and then create an instance of that class. The extending
class must override the run () method, which is the entry point for the new thread. It should also call
start () to begin execution of the new thread.
Commonly used Constructors of Thread class:

o Thread()

o Thread(String name)

o Thread(Runnable r)

o Thread(Runnable r,String name)

Thread execution by extends Thread class:


Program:
importjava.lang.*;
classMyThread extends Thread
{
Public void run()
{
for(int i = 1; i< 10 ; i++)
{

87
88 Object Oriented Programing

System.out.print(“ ” + i);
}
}
}
class Test
{
public static void main(String[] args)
{
MyThreadobj = new MyThread();
Thread t = new Thread(obj);
t.start(); // now this thread will execute the code inside run() method.
}
{

Output:
0123456789
Methods in Thread class:
1. public String getName(): returns the name of the thread
2. public void setName(String name): changes the name of the thread.
3. public int getPriority(): returns the priority of the thread.
4. public int setPriority(int priority): changes the priority of the thread.
5. publicbooleanisAlive(): tests if the thread is alive.
6. public void join(): waits for a thread to die.
7. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
8. public void run(): is used to perform action for a thread.
9. public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
10. public void start(): starts the execution of the thread.JVM calls the run() method on the
thread.
11. public void suspend(): is used to suspend the thread(depricated).
12. public void resume(): is used to resume the suspended thread(depricated).
13. public void stop(): is used to stop the thread(depricated).
14. public void yield(): causes the currently executing thread object to temporarily pause and
allow other threads to execute.

Thread creation by implements Runnable interface:


The easiest way to create a thread is to create a class that implements Runnable interface,
because of the following two reasons.

88
89 Object Oriented Programing

i. If a class extends a thread class then it can’t extend any other classes which may be
required to extend.
ii. If the class Thread is extended then all of its functionality gets inherited. This is an expensive
operation.

Program:
classThreadDemo implements Runnable
{
Thread t;
String str = “ “;
ThreadDemo(String s)
{
t = new Thread(this);
str = s;
t.start();
}
public void run()
{
System.out.println(str);
{
}
public class RunnableThread
{
public static void main(String[] args)
{
ThreadDemo t = new ThreadDemo(“Thread Created”);
}
}

Explain about Thread life cycle with neat diagram


Starting from the birth of a thread, till its death, a thread exists in different states which are
collectively called “Thread life cycle”.
A thread is born when it is created using Thread class.
Thread t = new Thread();

89
90 Object Oriented Programing

Then the thread goes into runnable state when start() method is applied on it(called).
yield() method may pause a method briefly but the thread will be in runnable state only.
From runnable state a thread may get into non – runnable state when sleep() method or wait()
method act on it.
A thread may be occasionally blocked on some I/O device where it is expecting some input /
output from user.
Thread always exists in any one of the states.
1. New or create state
2. Runnable state
3. Waiting state
4. Timed waiting state
5. Blocked state
6. Terminated state

New

Completion
Waiting Runnable Terminated Exit

Waiting
Interval Request Completed
For
Wait Ends I/O Request
Interval
New State: When a Blocked thread starts its life
cycle it enters into the Timed Waiting new state or a
create state
Runnable State: This is a state in which a thread starts executing.
Waiting State: Sometimes a thread has to go into the waiting state because another thread starts
executing.
Time Waiting State: There is a provision to keep a thread waiting for some time interval. This allows
to execute high prioritized threads first. After the timing gets over the thread in waiting state enters
runnable state.
Blocked State: When a particular thread issues an I/O request then the operating system sends it in
blocked state until the I/O operation gets completed. After the I/O completion the thread is sent
back to the runnable state.
Terminated State: A thread terminates because of either of the following reasons:
 Because it exists normally. This happens when the code of thread has entirely executed by
the program.

90
91 Object Oriented Programing

 Because there occurred some unusual erroneous event, like segmentation fault or an
unhandled exception.

A thread that lies in terminated state does no longer consumes any cycles of CPU.

Explain about Thread Priorities


In java thread scheduler selects the threads using their priorities. The thread priority is a simple
integer value that can be assigned to the particular thread. These priorities can range from 1 to 10.
The thread scheduler mainly uses pre-emptive or time slicing scheduling to schedule the threads.
Difference between pre-emptive scheduling and time slicing.
Under pre-emptive scheduling, the highest priority task executes until it enters the waiting or dead
states or a higher priority task comes into existence. Under time slicing, a task executes for a
predefined slice of time and then re-enters the pool of ready tasks. The scheduler then determines
which task should execute next, based on priority and other factors.

Lowest Priority = 1
Highest Priority = 10
Higher priority threads get more CPU time than lower priority threads
These are the commonly used functionalities in thread scheduling
1. setPriority()

The function setPriority() is used to set the priority to each thread.


Syntax: final void setPriority(int level)
Here level specifies the new priority setting for the calling thread. The value of level must be written
in between MIN_PRIORITY (1) and MAX_PRIORITY (10)
NORM_PRIORITY is 5.

2. getPriority()

The function getPriority() is used to get the priority of the thread


Syntax: final int getPriority()

Program:
class A extends Thread
{
public void run()

91
92 Object Oriented Programing

{
System.out.println(“Thread #1”);
for(int i = 1 ; i<= 5; i++)
{
System.out.print(“\tA: ” + i);
}
System.out.println(“\nEnd of thread #1”);
}
}

class B extends Thread


{
public void run()
{
System.out.println(“Thread #2”);
for(int j = 1 ; j <= 5; i++)
{
System.out.print(“\tB: ” + j);
}
System.out.println(“\nEnd of thread #2”);
}
}

classThreadPriority
{
public static void main(String[] args)
{
A obj1 = new A();
B obj2 = new B();
obj1.setPriority(1);
obj2.setPriority(10);
System.out.println(“Starting Thread #1”);

92
93 Object Oriented Programing

obj1.start();
System.out.println(“Starting Thread #2”);
obj2.start();
}
}

Synchronization in Java
Synchronization in java is the capability to control the access of multiple threads to any shared
resource.
Java Synchronization is better option where we want to allow only one thread to access the
shared resource. (OR)
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. This process is called “Synchronization”.
Why use Synchronization
The synchronization is mainly used to
 To prevent thread interference.
 To prevent consistency problem.

Types of Synchronization
There are two types of synchronization
 Process Synchronization
 Thread Synchronization

What is Thread Synchronization?


When a thread is already action on an object, preventing any other thread from acting on the
same object is called Thread Synchronization or Thread Safe the threads that are synchronized are
called Synchronized Object.
Thread synchronization is recommended when multiple threads are used on the same object in
multi-threading.
The synchronization is the concept which is based on monitor. Monitor is used as a mutually
exclusive lock or muter. When a thread owns this monitor at a time, then other threads cannot
access the resources. Other threads have to be in waiting state. We use the synchronized keyword.
There are many ways to achieve the synchronization.
1. Synchronized Method
2. Synchronized Blocks
3. static synchronization.

Example of Synchronized method


class Table

93
94 Object Oriented Programing

voidprintTable(int n)
{
synchronized(this)
{ //synchronized block
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}
catch(Exception e)
{
System.out.println(e);
}
} //end of for
} //end of synchronized block
} //end of the method
}

class MyThread1 extends Thread


{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(5);

94
95 Object Oriented Programing

}
}
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(100);
}
}
public class TestSynchronizedBlock1
{
public static void main(String args[])
{
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}

Concept of Lock in Java


Synchronization is built around an internal entity known as the lock or monitor. Every object has a
lock associated with it. By convention, a thread that needs consistent access to an object's fields
has to acquire the object's lock before accessing them, and then release the lock when it's done
with them.
From Java 5 the package java.util.concurrent.locks contains several lock implementations.

95
96 Object Oriented Programing

Deadlock in java

Deadlock in java is a part of multithreading. Deadlock can occur in a situation when a thread is
waiting for an object lock, that is acquired by another thread and second thread is waiting for an
object lock that is acquired by first thread. Since, both threads are waiting for each other to
release the lock, the condition is called deadlock.

Inter-Thread Communication
Inter-thread communication or Co-operation is all about allowing synchronized threads to
communicate with each other. (Two or more threads communicate with each other by
exchanging the messages)
Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in
its critical section and another thread is allowed to enter (or lock) in the same critical section to be
executed. It is implemented by following methods of Object class:
o wait()

o notify()

o notifyAll()

wait() method
It tells the calling thread to give up the lock and go to sleep until some other thread enters the
same monitor and calls notify().

96
97 Object Oriented Programing

notify() method

Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on
this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the
discretion of the implementation.

Syntax:

public final void notify()

notifyAll() method
Wakes up all threads that are waiting on this object's monitor.

Syntax:

public final void notifyAll()

Difference between wait and sleep?

Let's see the important differences between wait and sleep methods.

wait() sleep()

wait() method releases the lock sleep() method doesn't release the lock.

is the method of Object class is the method of Thread class

is the non-static method is the static method

is the non-static method is the static method

should be notified by notify() or after the specified amount of time, sleep


notifyAll() methods is completed.

97
98 Object Oriented Programing

Producer Consumer Problem


The producer consumer problem is also called the “bounded-buffer” problem. It is a classic
problem of a multi-process synchronization plan.
The problem describes two processes. The producer and the consumer which share a common
fixed size buffer used as a queue.
 The producer’s job is to generate data, put it into the buffer, and start again.

 At the same time, the consumer is consuming the data (i.e. removing it from the buffer),
one piece at a time.

http://www.geeksforgeeks.org/producer-consumer-solution-using-threads-java/
Consider producer-consumer problem in which producer thread produces and the consumer
thread consumes whatever is produced. Both must work in co-ordination to avoid wastage of CPU
cycles. But there are situations in which producer has to wait for the consumer to finish
consumption of data.
Similarly the consumer may need to wait for the producer to produce the data. In polling system
either consumer will waste many CPU cycles when waiting for producer to produce or the
producer will waste many CPU cycles when waiting for consumer to consume the data.
In order to avoid this we use three inbuilt methods that take part in inter-thread communication.
1. notify()
2. notifyAll()
3. wait()

Program:
class MyClass
{
int n;
boolean flag = false;
synchronized int get()
{
if(!flag)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println(“Interrupted Exception”);

98
99 Object Oriented Programing

}
System.out.println(“Consumer consuming: ” + n);
flag =false;
notify();
return n;
}
synchronized void put(int n)
{
if(flag)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println(“Interrupted Exception”);
}
this.n = n;
flag = true;
System.out.println(“Producer Producing ” + n);
notify();
}
}

class Producer implements Runnable


{
MyClass obj;
Producer(MyClass obj)
{
this.obj = obj;
new Thread(this, “Producer”).start();
}

99
100 Object Oriented Programing

public void run()


{
for(int i = 0; i< 10; i++)
{
obj.put(i);
}
}
}
class Consumer implements Runnable
{
MyClass obj;
Producer(MyClassobj)
{
this.obj = obj;
new Thread(this, “Consumer”).start();
}
public void run()
{
for(int i = 0; i< 10; i++)
{
obj.get();
}
}
}
public class InterThread
{
public static void main(String[] args)
{
MyClassTobj = new MyClass();
new Producer(Tobj);
new Consumer(Tobj);
}

100
101 Object Oriented Programing

}
Issues:

Issue 1:
wait() method can only be used with in synchronized method or block otherwise it will throw
java.lang.IllegalMonitorStateException exception.

Issue 2:
One of the thread may go into waiting state forever. Take a look at your if condition of thread
waiting logic. In present case if you have created two different item objects for producer as well as
consumer then inter-thread logic will not work so make sure both producer and consumer threads
share same item object so they can share monitor lock.

101
102 Object Oriented Programing

Unit 4: Collections Framework

102
103 Object Oriented Programing

Define collection and collections framework?


Collections
Collections in java is a framework that provides an architecture to store and manipulate the group
of objects.
All the operations that you perform on a data such as searching, sorting, insertion, manipulation,
deletion etc. can be performed by Java Collections.
Java Collection simply means a single unit of objects. Java Collection framework provides many
interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList, PriorityQueue,
HashSet, LinkedHashSet, TreeSet etc).
This collection interfaces declare the operations that can be personal on each type of collection.

What is Collection in java


Collection represents a single unit of objects i.e. a group.

(or)

A collection is an object that can hold references to other objects.

Collection class: Collections is a unity class in java.util package. It consists of any static
methods which are used to operate on objects of type collection.
For example, collections has methods for finding the max element in a collection.

What is framework in java


 Provides readymade architecture.
 Represents set of classes and interface.
 Is optional.

What is Collection framework


A collection framework is a class library to handle groups of object. Collection framework is
implemented in java.util package.
Collection framework represents a unified architecture for storing and manipulating group of
objects. It has:
1. Interfaces and its implementations i.e. classes

103
104 Object Oriented Programing

2. Algorithm

What are the various collection Interfaces in java?


Collection classes provide the implementation of different collection interfaces. The collection
interface is the foundation upon which the collection framework is built because it must be
implemented by any class that defines a collection. Collection is a generic interface that has this
declaration.
Interface Collection <E>

Here E specifies the type of objects that the collection will hold. Collections extends the Iterable
interface.
This means that all collections can be cycled through by use of the for-each style for loop.

The following diagram shows different types of interfaces

Collection Map

List
•ArrayList
HashMap
•LinkedList
•Vector
•Stack

Set LinkedHashMap
•HashSet
•LinkedHashSet
•SortedSet
•TreeSet
HashTable
Queue
•Priority Queue
•Dequeue
•ArrayDequeue
Properties

104
105 Object Oriented Programing

Explain ArrayList classes?


 The Arraylist class implement the list interface.
 It is used to implement the dynamic array. The dynamic array means the size of array can
be created as per requirement.

Characterstics of Array
 Resizable Array is the underlying Datasturcture.
 Duplicate values are allowed.
 Insertion order followed.
 Hetrogenous objects accepted.
 Null insertion is possible.
 Seriolizable and cloneable interface implemented and also randomaccess implemented.

Constructors:-
 ArrayList l=new ArrayList(); default size 10
 New size=(current size/2)+1
 ArrayList l=new ArrayList(int intialcapacity);
 ArrayList l=new ArrayList(Collection c);
Note: ArrayList methods are not synchronized method.i.e; when more than one thread acts
simultaneously on the ArrayObject.

Array class methods


 boolean add(element obj):Adding an element at the end of Arraylist.
 void add(int position element obj): inserts specified element at specified location.

105
106 Object Oriented Programing

 remove(int position): remove specified position in the ArrayList.


 void clear() : remove all the elements from the ArrayList.
 Int size(): It returns number of elements present in the ArrayList.

PROGRAM:
import java.util.*;
class ArrayListDemo
{
public static void main(String [] args)
{
ArrayList l=new ArrayList();
l.add(“A”);
l.add(10);
l.add(“A”);
l.add(null);
System.out.println(l); //[A,10,A,null]
l.remove(2); //[A,10,null]
System.out.println(l);
l.add(2,”m”);
l.add(“N”);
System.out.println(l0;
}
}
output
[A,10,m,null,N]

Explain about Linked list class in collection Frame work?


 A Linked list contains a group of elements in the form of nodes. Each node will have three
fields the field contains data and the link fields contain references to previous and next
nodes.
 Linked List is very convenient to store data. Inserting the elements into the linked list and
removing the elements from the linked list and removing the elements from the linked list is
done quickly and takes the same amount of time.
 The Linked List class extends Abstract Sequential List and implements the list, deque, and
queue interface.
 The underlying dataStructure is Double Linked List.

106
107 Object Oriented Programing

 Insertion order is preserved.


 Duplicate order is preserved.
 Heterogeneous objects are allowed.
 Null insertion is possible.

Constructors:
LinkedList l =new LinkedList();
LinkedList l=new LinkedList(collection c);

Methods :
 addFirst(): To add elements to the start a list.
 addLast(): To add elements to the end of the list.
 getFirst()/Peekfirst : obtain the first element.
 getLast(): To obtain the last element.
 removeFirst():To remove the 1st element .
 removeLast(): To remove the last element.

PROGRAM:
Import java .util.*;
Class LinkedListDemo
{
Public static void main(String [] args)
{
LinkedList l = new LinkedList();
l.add(“Java”);
l.add(“30”);
l.add(0,“software”);
l.add(0,“venky”);
l.removeLast();
l.addFirst(“ccc”);
System.out,println(l);
}
}
Output: [Java, venky, software, 30, null]

Explain about vector class in collection Frameworks vector class?


 A vector also stores elements/objects similar to ArrayList but vectore is synchgronised.

107
108 Object Oriented Programing

 It means even if several threads act on vector on vector on vector objects simultaneously,
the results will be reliable.
 Vector is similar to ArrayLIst class which implements the dynamic array.
 It implements the list interface.

Constructors:
Vector v =new Vector();
Vector v = new Vector(int size);
Vector v = new Vector(int size; int intialcapacity);

Commonly used methods of Vector Class:


1. void addElement(Object element): It inserts the element at the end of the Vector.
2. int capacity(): This method returns the current capacity of the vector.
3. int size(): It returns the current size of the vector.
4. void setSize(int size): It changes the existing size with the specified size.
5. boolean contains(Object element): This method checks whether the specified
element is present in the Vector. If the element is been found it returns true else false.
6. boolean containsAll(Collection c): It returns true if all the elements of collection c are
present in the Vector.
7. Object elementAt(int index): It returns the element present at the specified location in
Vector.
8. Object firstElement(): It is used for getting the first element of the vector.
9. Object lastElement(): Returns the last element of the array.
10. Object get(int index): Returns the element at the specified index.
11. boolean isEmpty(): This method returns true if Vector doesn’t have any element.
12. boolean removeElement(Object element): Removes the specifed element from
vector.
13. boolean removeAll(Collection c): It Removes all those elements from vector which
are present in the Collection c.
14. void setElementAt(Object element, int index): It updates the element of specifed
index with the given element.

Vector Program Example:


Import java.util.*;
class Vectorexample
{
public static void main(String[] args)
{
Vector v =new Vector(25);
System.out.println(v.capacity);

108
109 Object Oriented Programing

for(int i=0;i<=10;i++)
{
v.addElement(i);
}
System.out.println(v.capacity);
v.addElement(“A”);
System.out.println(v.capacity());
System.out.println(v);
}
} Output: [1,2,3,4,5,6,7,8,9,10,A]

ArrayList Vector

1) ArrayList is not synchronized. Vector is synchronized.

2) ArrayList increments 50% of Vector increments 100% means doubles the array
current array size if number of size if total number of element exceeds than its
element exceeds from its capacity.
capacity.

3) ArrayList is not a legacyclass, Vector is a legacy class.


it is introduced in JDK 1.2.

4) ArrayList is fast because it is Vector is slow because it is synchronized i.e. in


non-synchronized. multithreading environment, it will hold the other
threads in runnable or non-runnable state until
current thread releases the lock of object.

5)ArrayList uses Iterator Vector uses Enumeration interface to traverse the


interface to traverse the elements. But it can use Iterator also.
elements.

EXPLAIN STACK CLASS IN COLLECTION FRAME WORK?


Stack is a sub class of vector that implements a standard last in first out stack.
Stack data structure in which elements are inserted and deleted in one end called top.
We can perform basic opertations push and pop using push() and pop() methods

109
110 Object Oriented Programing

Constructors:
Stack s = new Stack();
Methods:
Apart from the methods inherited from its parent class Vector, Stack defines the following methods

Sr.No. Method & Description

1 boolean empty()
Tests if this stack is empty. Returns true if the stack is empty, and returns false if the stack
contains elements.

2 Object peek( )
Returns the element on the top of the stack, but does not remove it.

3 Object pop( )
Returns the element on the top of the stack, removing it in the process.

4 Object push(Object element)


Pushes the element onto the stack. Element is also returned.

5 int search(Object element)


Searches for element in the stack. If found, its offset from the top of the stack is returned.
Otherwise, .1 is returned.

110
111 Object Oriented Programing

EXPLAIN ABOUT SET INTERFACE AND EXPLAIN HASHSET CLASS?


1) The set interface is used to define the set of elements it extends the collection interface.
2) The set involves defined unique elements.hence it any duplicate elements is tried to insert in the
set then add() method returns false.
3) If we want to represent a group of individual objects as a single entity where duplicates are not
allowed and insertion order not preserved then we should go to set

HashSet

Collection Set

LinkedHashSet

HashSet:
HashSet extends AbstractSet and implements the set interface .it creates a collection that uses a
hashtable for storage.
1. The underlying data structure is hashtable.

111
112 Object Oriented Programing

2. Duplicate values are not allowed .if we are trying to insert duplicate values ,we won’t get
any compile time (or) runtime errors .add() method simply returns false.
3. Insertion order is not preserved.
4. Heterogeneous objects are allowed.
5. ‘null’ insertion is possible .
6. Implementing serialization and cloneable interfaces but not random access.
7. HashSet is the best choice, if our operation is “search”.

Hash Set Program Example:


import java.util,*;
class Hashsetexample
{
public static void main()
{
HashSet h=new HashSet();
h.add(“B”);
h.add(“C”);
h.add(“D”);
h.add(“Z”);
h.add(null);
h.add(10);
System.out.println(h.add(“2”));//false
System.out.println(h);
}
}
Output: [null,D,B,C,10,Z]

Constructors:
1) HashSet h=new HashSet();
 default size is 16
 default fill ratio is 0.75
2) HashSet h=new HashSet(int initialcapacity);
3) HashSet h=new HashSet(collection());

Methods:
Method Description
void clear() remove all elements
Boolean add(object) add object
isEmpty() return true
remove(object o) remove specified object

112
113 Object Oriented Programing

NOTE:
HashSet does not guarantee the order of its elements, because the process of hashing doesn’t
usually lend itself to the creation of sortedset.

Explain About TreeSet Classes In java.util Package?


 TreeSet extends AbstractSet and implements the navigatableSet interface. It creates a
collection that uses a tree for storage.
 Objects are stored in sorted, ascending order.
 Access and retrival times are quite fast, which makes treeSet an excellent choice when
storing large amounts of stored information that must be found quickly.
 Null insertion is allowed, but only once.

Constructors of Java TreeSet class


Constructor Description
TreeSet() It is used to construct an empty tree set that will be sorted in an ascending
order according to the natural order of the tree set.
TreeSet(Collection c) It is used to build a new tree set that contains the elements of the collection
c.
TreeSet(Comparator It is used to construct an empty tree set that will be sorted according to
comp) given comparator.
TreeSet(SortedSet ss) It is used to build a TreeSet that contains the elements of the given
SortedSet.

Methods of Java TreeSet class


Method Description
boolean addAll(Collection It is used to add all of the elements in the specified collection to this set.
c)
boolean contains(Object o) It is used to return true if this set contains the specified element.
boolean isEmpty() It is used to return true if this set contains no elements.
boolean remove(Object o) It is used to remove the specified element from this set if it is present.
void add(Object o) It is used to add the specified element to this set if it is not already
present.
void clear() It is used to remove all of the elements from this set.
Object clone() It is used to return a shallow copy of this TreeSet instance.
Object first() It is used to return the first (lowest) element currently in this sorted set.
Object last() It is used to return the last (highest) element currently in this sorted set.
int size() It is used to return the number of elements in this set.

TreeSet program example:


import java.util.* ;
class TreeSetexample
{
public static void main(String[] args)
{

113
114 Object Oriented Programing

TreeSet t=new TreeSet();


t.add(“a”);
t.add(“b”);
t.add(“Z”);
t.add(“I”);
t.add(null);
System.out.println(t);
}
}

For-Each:
1. If we won’t be modifying the content s of a collection or obtaining elements in reverse
order, then the for-each version of the for loop is often a more convenient alternative to
cycling through a collection than is using an iterator.
2. Recall that the for can cycle through any collection of objects, that implemented the
Iterable Interface. Because all of the collection classes implement this interface, they
can all be operated upon by the for.

Ex:
Class ForEachDemO
{
public static void main(String [ ] args)
{
ArrayList l = new ArrayList( );
l.add(1);
l.add(2);
l.add(5);
System.ot.println9”contents of list”);
System.out.println(l);
}
}

Queue Interface:-
1. Java queue interface orders the element in FIFO(First in First out)manner. First and last
elements are removed at last.
2. Queue is a generic interface

Constructor:
Interface Queue<E>

114
115 Object Oriented Programing

Here E specifies the type of objects that the queue will hold.

Methods:
Method Description
object element () It is used to retrieves, and but does not
remove the head of this queue.
boolean add(object) It is used to insert the specified element
into this queue and return true upon
success.
object remove() It is used to retrieves and removes the
head of this queue.
object poll() It is used to retrieve and remove the head
of the queue, or return null if the queue is
empty.
object peek() It is used to retrieve, but doesn’t remove
the head of this queue or returns null if the
queue is empty.

Priority Queue Class:


The PriorityQueue class provides the facility of using queue but doesn’t orders the elements in FIFO
manner. It inherits the AbstractQueueClass.
Syntax:
public class PriorityQueue<E>extends Abstract<E> implements Serializalble

Ex:
import java.util.*;
class PriorityQueueDemo
{
Public static void main(String[ ] args)
{
PriorityQueue<String> queue=new PriorityQueue<String>();
queue.add(“java”);
queue(“pgm”);
queue.add(“language”);
System.out.println(“head” +queue.element());
System.out.println(“head” +queue.peek());
System.out.println(“queue elements”);
Iterator(itr=queue.iterator());
While(it.hasNext())

115
116 Object Oriented Programing

{
System.out.println(itr.next());
}
queue.remove();
queue.poll();
System.out.println(“after removing two elements”);
Iterator<String>itr2=queue.iterator();
While(itr2.hasNext())
{
System.out.println(itr2.next( ));
}
}
}

Output:
Head:Java
Head:Java
Iterting the queue elements
Java
Pgm
language
After removing two elements
language

ArrayDeque Class:
1. Java deque interface is a linear collection that supports element insertuion and removal
at both ends.
2. Dequeue is anj acronym for” double ordered queue”.
3. The Arrayqueue class extends AbstractCollection and implements the dequeue
interface. It adds no methods of its own.
4. ArrayDequeue creates a dynamic array and has no capacity restrictions.

Constructor:
Class ArrayDequeue<E>
Here E specifies the type of object stored in the collection.

116
117 Object Oriented Programing

Methods:

Method Description
boolean add(object) It is used to insert the specified element
into this dequeue and return
true upon success
object remove() It is used to retrieves and remotes the
head of this queue.
Object poll() It is used to retrieves but doesnot remove
the head of this queue.
Object peek() It is used to retrieve but doesnot remove,
the head of this dequeue.
Example:
Import java.util.*;
public class ArrayDequeDemo
{ public static void main(String[] args)
Deque<String> deque =new ArrayDeque<String> (0);
deque.add(“RAVI”);
deque.add(“VIJAY”);
deque.add(“AJAY”);
for( String str:deque)
{ System.out.println(str);
}
}
}
Output:
RAVI
VIJAY
AJAY

Explain about Hashtable class?


1. Hashtable is similarly to Hashmap can store elements in the form of hey-value pasirs.
2. Underlying Data struture for Hashtable is Hashtable.
3. Insertion order is not preserved and it is based on Hashtable of keys.
4. Duplicate keys are not allowed and values cane be duplicated.
5. Hetrogenous objects are allowerd for both key and values.
6. Null is not allowed for both key and values,otherwise we will get runtime Exception i.e;
NullPointException
7. It implements serializable & cloneable interfaces but not Random access.
8. Every method present in Hash table is synchronized and hence it is Thread safe.
9. Hash table is best choice if our frequent operation is retrieval/search operation.

117
118 Object Oriented Programing

Constructors of Java Hashtable class

Constructor Description
Hashtable() It is the default constructor of hash table it instantiates the Hashtable
class.
Hashtable(int size) It is used to accept an integer parameter and creates a hash table that has
an initial size specified by integer value size.
Hashtable(int size, float It is used to create a hash table that has an initial size specified by size
fillRatio) and a fill ratio specified by fillRatio.

Methods of Java Hashtable class

Method Description
void clear() It is used to reset the hash table.
boolean contains(Object This method return true if some value equal to the value exist
value) within the hash table, else return false.
boolean containsValue(Object This method return true if some value equal to the value exists
value) within the hash table, else return false.
boolean containsKey(Object This method return true if some key equal to the key exists within
key) the hash table, else return false.
boolean isEmpty() This method return true if the hash table is empty; returns false if it
contains at least one key.
void rehash() It is used to increase the size of the hash table and rehashes all of
its keys.
Object get(Object key) This method return the object that contains the value associated
with the key.
Object remove(Object key) It is used to remove the key and its value. This method return the
value associated with the key.
int size() This method return the number of entries in the hash table.

Program:-
Import java.uti.*;
class HashtableDemo
{ public static void main(String[] args)
{ Hashtable h= new Hashtable();
h.put(new Temp(5),”A”);
h.put(new Temp(2),”B”);
h.put(new Temp(6),”C”);
h.put(new Temp(15),”D”);
h.put(new Temp(23),”E”);
System.out.println(h);
}
}
class temp{
{ int i;
Temp(int i)

118
119 Object Oriented Programing

{ this .i=i;
}
public int hashtable()
{
return i;
}
public String toString()
{ return i+ “ “;
}
}
Output:
{6=c,5=A,15=D,2=B,23=B}
NOTE:
1. from top to bottom it will be printed.
2. If multiple values are there the right to left printed.
It can be represented as

10
9
8
7
6 6=C
5 5=A
4 15=D
3
2 2=B
1 23=E
0

EXPLAN MAP INTERFACES IN COLLECTION FRAMEWORK?


 Map is kind of data structure which is associates the keys to the value. If there is unique
value present for each unique key then the mapping is called one to one mapping.
 The map interface maps unique keys to values. A key is an object that you use to values. A
key is an object that you use to retrieve a value at a later date .given a key and a value,
you can store the value in a map object. After the value is stored, you can retrieve it by
using its key.

119
120 Object Oriented Programing

Map

Hashtable HashMap TreeMap

Method Description
Object put(Object key, Object It is used to insert an entry in this map.
value)
void putAll(Map map) It is used to insert the specified map in this
map.
Object remove(Object key) It is used to delete an entry for the specified
key.
Object get(Object key) It is used to return the value for the specified
key.
boolean containsKey(Object It is used to search the specified key from this
key) map.
Set keySet() It is used to return the Set view containing all
the keys.
Set entrySet() It is used to return the Set view containing all
the keys and values.

120
121 Object Oriented Programing

HashMap class:

1. Hashmap is a collection that stores elements in the fom of key value pairs.if key is
provided later, its corresponding value can be easily retrieved from the HashMap .
2. Keys should be unique .This means we cannot use duplicate data forkeys in the
HashMap. However ,HashMap is not synchronized and hence while using multiple
threads on HashMap object , we can get unreliable results.

Constructors of Java HashMap class


Constructor Description
HashMap() It is used to construct a default HashMap.
HashMap(Map m) It is used to initializes the hash map by using the elements of the
given Map object m.
HashMap(int capacity) It is used to initializes the capacity of the hash map to the given
integer value, capacity.
HashMap(int capacity, float It is used to initialize both the capacity and fill ratio of the hash
fillRatio) map by using its arguments.

121
122 Object Oriented Programing

Methods of Java HashMap class


Method Description
void clear() It is used to remove all of the mappings from this map.
boolean containsKey(Object It is used to return true if this map contains a mapping for the
key) specified key.
boolean containsValue(Object It is used to return true if this map maps one or more keys to
value) the specified value.
boolean isEmpty() It is used to return true if this map contains no key-value
mappings.
Object clone() It is used to return a shallow copy of this HashMap instance: the
keys and values themselves are not cloned.
Set entrySet() It is used to return a collection view of the mappings contained
in this map.
Set keySet() It is used to return a set view of the keys contained in this map.
Object put(Object key, Object It is used to associate the specified value with the specified key
value) in this map.
int size() It is used to return the number of key-value mappings in this
map.
Collection values() It is used to return a collection view of the values contained in
this map.

Example Program:
import java.util.*;
public class HashMapdemo
{
HashMap m=new HashMap();
m.put(“Mahesh”,700);
m.put(“ramu”,800);
m.put(“raju”,200);
m.put(“problems”,500);
System.out.println(m);
System.out.println(m.put(“Mahesh”,100);
Set s=m.keySet();
System.out.println(s);
Collection c=m.Values();

122
123 Object Oriented Programing

System.out.println(c);
Set s1=m.entrySet();
System.out.println(s1);
Iterator itr=s1.iterator();
While(itr.hasNext())
{
Map.Entry m1=(map.Entry)itr.next();
System.out.println(m1.getkey()+” “ +m1.getValue());
If(m1.getkey().equals(“ramu));
{
M1.setVale(10000);
}
}
System.out.println(m);
}
}

Comparator Interface:
 Java comparator interface is used to order the objects of user defined class.
 This interface is found in java.util package and contain 2 methods
1) compare
2) equals
Example:
Compare(Object obj1,Object obj2)
equals(Object element)

compare() method
public int compare(Object obj1,Object obj2): compares the first object with second object.
It provides multiple sorting sequence i.e. You can sort the elements on the basis of any data
members, for Example roll, name, age etc.

Example Program:
Student.java
Class student
{
int rollno;

123
124 Object Oriented Programing

String name;
int age;
Student(int rollno,String name,int age)
{
this.rollno=rollno;
this.name=name;
this.age=age;
}
}
Age comparator.java
Class agecomparator implements comparator<student>
{
public int compare (student s1,student s2)
{
if(s1.age==s2.age)
return 0;
else if(s1.age>s2.age)
return 1;
else
return -1;
}
}

Java Comparable interface


Java Comparable interface is used to order the objects of user-defined class.This interface is found
in java.lang package and contains only one method named compareTo(Object). It provide single
sorting sequence only i.e. you can sort the elements on based on single data member only. For
example it may be rollno, name, age or anything else.
compareTo(Object obj) method
public int compareTo(Object obj): is used to compare the current object with the specified object.

We can sort the elements of:


1. String objects
2. Wrapper class objects
3. User-defined class objects

124
125 Object Oriented Programing

File: Student.java

class Student implements Comparable<Student>{


int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}

public int compareTo(Student st){


if(age==st.age)
return 0;
else if(age>st.age)
return 1;
else
return -1;
}
}

Properties Class in Collection Frame Work:


In our program if anything which changes frequently(like username, pwd, mail id, ph.no etc) are
not recommended to hardcode in java program .because if there is any change to reflect that
change recompilation, rebuilt, restart, server are required. Which redeplay, restart sever are
required .which creates a big business impact for customers/clients.
We can overcome this problem by using “properties file “,such type of variable things we have to
configure in the properties file ,from that properties file we have to read into java program and we
can use those properties.

1.
compile
rebuilt
Username:”scott”
redeplay
restart
Password:”tiger”
restart server
without properties 2
to 3 hours

125
126 Object Oriented Programing

load

User name:”scott” Username:”scott”


Password:”tiger” Password:”tiger”

object
Store

3) The properties object contains key and value pair both as a string .the java.util.properties
class is the subclass of hashtable. It can be used to get property value based on the
property key. The property class provides methods to get data from properties file and store
data into properties file.

Method Description
public void load(Reader r) Loads data from the Reader object.
public void load(InputStream is) loads data from the InputStream
object
public String getProperty(String key) Returns value based on the key.
public void setProperty(String Sets the property in the properties
key,String value) object.
public void store(Writer w, String Writes the properties in the writer
comment) object.
public void store(OutputStream os, Writes the properties in the
String comment) OutputStream object.
storeToXML(OutputStream os, String Writes the properties in the writer
comment) object for generating xml document.
public void storeToXML(Writer w, Writes the properties in the writer
String comment, String encoding) object for generating xml document

126
127 Object Oriented Programing

with specified encoding.


Example Program:
import java.util.*;
import java.io.*;
public class propertiesdemo
{
public static void main(String args[])throws Exception
{
Filereader reader=new Filereader(“db.properties”);
Properties p=new Properties();
p.load(reader);
System.out.println(p.getProperties(“user”));
System.out.println(p.getProperty(“password”));
}
}
o/p:
system
oracle

Explain Various Cursors In Java.


If you want to retrieve object one by one from collection we use cursors.
There are 3 types of cursors in java.
1) Enumeration
2) Iterator
3) ListIterator

EXPLAIN ITERATOR WITH EXAMPLE:


 It is introduced in 1.2 version.
 Enumeration is applicable only legacy classes (vector) not for all collection classes.
 To avoid above problem we use iterator .we can get iterator object for any collection
implemented class hence it is a universal cursor.
 While iterator objects,we are allowed to perform removal operation in addition to read
operation.
This interface contains following 3 methods .

127
128 Object Oriented Programing

1) Public Boolean hasNext()


2) Public Object next()
3) Public void remove()

Drawbacks:
1) Iterator and enumerator are single directional cursors.they can always move towards
forward direction only.
2) By using iterator we can perform read and remove operation and we cant perform any
replace or addition of new objects.

Example Program:
import java.util.*;
Class iteratoreaxmple
{
Public static void main(String[] args)
{
ArrayList l=new ArrayList();
for(i=0;i<=6;i++)
{
l.add(i);
}
System.out.println(l);
Iterator itr=l.iterator();
While(itr.hasNext())
{
Integer I=(Integer)itr.next();
if(I%2==0)
System.out.println(l);
else
itr.remove();
}
}
}
o/p:
2
4

128
129 Object Oriented Programing

6
8

Dictionary classes:
1. Dictionary is an abstract class that represents a key/value storage repository & operates much
like maps.
2. Given a key and value, you can store the value in dictionary object.
3. Once value is stored, you can retrieve it by using its key.
4. Thus, like a map, a dictionary can be thought of as list of key /value pairs
5. Dictionary is classified as absolute, because use it is fully superseded by map.
Constructor:
Dictionary ( )
Methods:
Method Description
object get( object key) Returns the object that contains the value
associated with the key.
object put(object key, object value) Inserts key and its value into the dictionary.
abstract boolean is empty() This method tests if this dictionary maps no keys
to value.
object remove(object key) This method removes the key (and its
corresponding value) from this dictionary.
abstract int size() This method returns the number of entries
(distinct keys) in this dictionary.

Example:-
import java.util.*;
public class DictionaryDemo
{
public static void main(Stringt[] args)
{
Dictionary d=new Hashtable( );
d.put(“1”,”java”);
d.put(“2”,”MFCS”);
for(Enumeration e=d.key());
e.hasMoreElements();
{
System.out,println(e.nextElement())

129
130 Object Oriented Programing

}
}
}
Output:
2
1

Collection Algorithms:
1. The collection framework defines several algorithms that can be applied to collections
and maps.
2. These algorithms are defined as static methods within the collection class.
3. Several of the methods can throw a ClasscostException,which occurs when an attempt
is made to compare incomplete types, or an unsupported OperationException which
occurs when an attempt is made to modify an unmodifiable collection.
4. The set of methods that begins with unmodifiable returns views of the various collections
that cannot be modified.
5. These will be useful when you want to grant some process read- but not write-
capabilities on a collection.
6. Collections defines three static variables.
 EMPTY_SET
 EMPTY_LIST
 EMPTY_MAP
Methods:
1. static<T> boolean add(Collection<? Super T >c,T---------element)
2. Inserts elements specified by elements into the collection specified by c.
3. static CheckedSet()
4. static comparatror()
5. Static void rotate ()
6. Static void shuffle()

Java Calendar Class


Java Calendar class is an abstract class that provides methods for converting date between a
specific instant in time and a set of calendar fields such as MONTH, YEAR, HOUR, etc. It inherits
Object class and implements the Comparable interface.

130
131 Object Oriented Programing

Java Calendar class declaration


Let's see the declaration of java.util.Calendar class.

1. public abstract class Calendar extends Object


2. implements Serializable, Cloneable, Comparable<Calendar>

Methods of Java Calendar


Method Description

abstract void add(int It is used to add or subtract the specified amount of time
field, int amount) to the given calendar field, based on the calendar's
rules.

int get(int field) It is used to return the value of the given calendar field.

static Calendar It is used to get a calendar using the default time zone
getInstance() and locale.

abstract int It is used to return the maximum value for the given
getMaximum(int field) calendar field of this Calendar instance.

abstract int It is used to return the minimum value for the given
getMinimum(int field) calendar field of this Calendar instance.

void set(int field, int value) It is used to set the given calendar field to the given
value.

void setTime(Date date) It is used to set this Calendar's time with the given Date.

Date getTime() It is used to return a Date object representing this


Calendar's time value.

Java Calendar Class Example

1. import java.util.Calendar;
2. public class CalendarExample1 {
3. public static void main(String[] args) {
4. Calendar calendar = Calendar.getInstance();

131
132 Object Oriented Programing

5. System.out.println("The current date is : " + calendar.getTime());


6. calendar.add(Calendar.DATE, -15);
7. System.out.println("15 days ago: " + calendar.getTime());
8. calendar.add(Calendar.MONTH, 4);
9. System.out.println("4 months later: " + calendar.getTime());
10. calendar.add(Calendar.YEAR, 2);
11. System.out.println("2 years later: " + calendar.getTime());
12. }
13. }

Output:

The current date is : Thu Jan 19 18:47:02 IST 2017


15 days ago: Wed Jan 04 18:47:02 IST 2017
4 months later: Thu May 04 18:47:02 IST 2017
2 years later: Sat May 04 18:47:02 IST 2019

java.util.Date Class
The java.util.Date class represents date and time in java. It provides constructors and methods to deal
with date and time in java.

The java.util.Date class implements Serializable, Cloneable and Comparable<Date> interface. It is


inherited by java.sql.Date, java.sql.Time and java.sql.Timestamp interfaces.

After Calendar class, most of the constructors and methods of java.util.Date class has been
deprecated. Here, we are not giving list of any deprecated constructor and method.

java.util.Date Constructors
No. Constructor Description

1) Date() Creates a date object representing current date and


time.

2) Date(long Creates a date object for the given milliseconds since


milliseconds) January 1, 1970, 00:00:00 GMT.

132
133 Object Oriented Programing

java.util.Date Methods
No. Method Description

1) boolean after(Date date) tests if current date is after the given date.

2) boolean before(Date date) tests if current date is before the given date.

3) Object clone() returns the clone object of current date.

4) int compareTo(Date date) compares current date with given date.

5) boolean equals(Date date) compares current date with given date for
equality.

6) static Date from(Instant returns an instance of Date object from


instant) Instant date.

7) long getTime() returns the time represented by this date


object.

8) int hashCode() returns the hash code value for this date
object.

9) void setTime(long time) changes the current date and time to given
time.

10) Instant toInstant() converts current date into Instant object.

11) String toString() converts this date into Instant object.

java.util.Date Example
Let's see the example to print date in java using java.util.Date class.

1st way:
1. java.util.Date date=new java.util.Date();
2. System.out.println(date);

133
134 Object Oriented Programing

Output:
Wed Mar 27 08:22:02 IST 2015
2nd way:
1. long millis=System.currentTimeMillis();
2. java.util.Date date=new java.util.Date(millis);
3. System.out.println(date);

Output:
Wed Mar 27 08:22:02 IST 2015

Java.util.Random class in Java


Random class is used to generate pseudo random numbers in java. Instance of this class are
thread safe. The instance of this class are however cryptographically insecure. This class provides
various method call to generate different random data types such as float, double, int.

Constructors:
 Random(): Creates a new random number generator
 Random(long seed): Creates a new random number generator using a single long seed

Declaration:
public class Random
extends Object
implements Serializable

Methods:
1. java.util.Random.doubles(): Returns an effectively unlimited stream of pseudo random double values,
each between zero (inclusive) and one (exclusive)
Syntax:
public DoubleStream doubles()
Returns: A stream of pseudorandom double values

2. java.util.Random.ints(): Returns an effectively unlimited stream of pseudo random int values


Syntax:
public IntStream ints()
Returns: A stream of pseudorandom int values

3. java.util.Random.longs(): Returns an effectively unlimited stream of pseudo random long values


Syntax:
public LongStream longs()
Returns: A stream of pseudorandom long values

4. next(int bits): java.util.Random.next(int bits) Generates the next pseudo random number
Syntax:
protected int next(int bits)
Parameters: bits - random bits

134
135 Object Oriented Programing

Returns: the next pseudo random value from this Random number generator's sequence

5. java.util.Random.nextBoolean(): Returns the next pseudo random, uniformly distributed boolean


value from this random number generator’s sequence
Syntax:
public boolean nextBoolean()
Returns: The next pseudorandom, uniformly distributed Boolean value from this random number
generator's sequence

6. java.util.Random.nextBytes(byte[] bytes) :Generates random bytes and places them into a


user-supplied byte array
Syntax:
public void nextBytes(byte[] bytes)
Parameters: bytes - the byte array to fill with random bytes
Throws: NullPointerException - if the byte array is null

7. java.util.Random.nextDouble(): Returns the next pseudo random, uniformly distributed double


value between 0.0 and 1.0 from this random number generator’s sequence
Syntax:
public double nextDouble()
Returns: The next pseudo random, uniformly distributed double
value between 0.0 and 1.0 from this random number generator's sequence

8. java.util.Random.nextFloat(): Returns the next pseudo random, uniformly distributed float value
between 0.0 and 1.0 from this random number generator’s sequence
Syntax:
public float nextFloat()
Returns: The next pseudorandom, uniformly distributed float value between 0.0 and 1.0 from this
random number generator's sequence

9. java.util.Random.nextGaussian(): Returns the next pseudo random, Gaussian (“normally”)


distributed double value with mean 0.0 and standard deviation 1.0 from this random number generator’s
sequence
Syntax:
public double nextGaussian()
Returns: The next pseudorandom, Gaussian ("normally") distributed double value with mean 0.0 and
standard deviation 1.0 from this random number generator's sequence

10. java.util.Random.nextInt(): Returns the next pseudorandom, uniformly distributed int value from this
random number generator’s sequence
Syntax:
public int nextInt()
Returns: Rhe next pseudorandom, uniformly distributed int value from this random number generator's
sequence

11. java.util.Random.nextInt(int bound): Returns a pseudo random, uniformly distributed int value
between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator’s
sequence
Syntax:
public int nextInt(int bound)
Parameters: bound - the upper bound (exclusive). Must be positive.

135
136 Object Oriented Programing

Returns: The next pseudorandom, uniformly distributed int value between zero (inclusive) and bound
(exclusive) from this random number generator's sequence
Throws: IllegalArgumentException - if bound is not positive

12. java.util.Random.nextLong(): Returns the next pseudorandom, uniformly distributed long value
from this random number generator’s sequence
Syntax:
public long nextLong()
Returns: The next pseudorandom, uniformly distributed long valuefrom this random number generator's
sequence

13. java.util.Random.setSeed(long seed): Sets the seed of this random number generator using a
single long seed
Syntax:
public void setSeed(long seed)
Parameters:seed - the initial seed

Methods inherited from class java.lang.Object


 clone
 equals
 finalize
 getClass
 hashCode
 notify
 notifyAll
 toString
 wait

Java program to demonstrate usage of Random class


// Java program to demonstrate
// method calls of Random class
import java.util.Random;
public class Test
{
public static void main(String[] args)
{
Random random = new Random();
System.out.println(random.nextInt(10));
System.out.println(random.nextBoolean());
System.out.println(random.nextDouble());
System.out.println(random.nextFloat());
System.out.println(random.nextGaussian());

136
137 Object Oriented Programing

byte[] bytes = new byte[10];


random.nextBytes(bytes);
System.out.printf("[");
for(int i = 0; i< bytes.length; i++)
{
System.out.printf("%d ", bytes[i]);
}
System.out.printf("]\n");

System.out.println(random.nextLong());
System.out.println(random.nextInt());

long seed = 95;


random.setSeed(seed);

// Note: Running any of the code line below


// will keep the program running as each of the
// methods below produces an unlimited random
// values of the corresponding type

/* System.out.println("Sum of all the elements in the IntStream returned = " +


random.ints().count());
System.out.println("Count of all the elements in the DoubleStream returned = " +
random.doubles().count());
System.out.println("Count of all the elements in the LongStream returned = " +
random.longs().count());

*/

}
}
Output:

137
138 Object Oriented Programing

true

0.19674934340402916

0.7372021

1.4877581394085997

[-44 75 68 89 81 -72 -1 -66 -64 117 ]

158739962004803677

-1344764816

138
139 Object Oriented Programing

Unit 5: GUI Programming with Swing

Explain about AWT and AWT class hierarchy.


Ans. AWT means Abstract Window Toolkit represents a class library to develop applications using
GUI.

139
140 Object Oriented Programing

It is in java.awt package. This package got classes and interfaces to develop GUI and let the users
interact in a more friendly way with the applications.
The AWT contains large number of classes which help to include various graphical components in
the java program.
These graphical components include text box, buttons, labels, radio buttons, list items and so on.

JAVA AWT HIERARCHY

Object Button

Label
Component

Checkbox

Choice

List

Container

Window Panel

Frame Dialog

LIMITATIONS OF AWT:
1. AWT components are platform dependent .
2. The look and feel are different for different OS.
3. AWT is heavyweight i.e. its components are using the resources of operating system.
4. AWT supports limited number of GUI components.
5. The AWT component is converted by the native code of the O.S.
1. Component: This is the superclass of all the graphical classes from which variety of graphical
classes can be derived. It helps in displaying the graphical object in the screen. It handles the
mouse and keyboard events.

140
141 Object Oriented Programing

2. Container: This is a graphical component derived from the component class. It is responsible for
managing the layout and placement of graphical components in the container.
3. Window: The top-level window without border and without the menu bar is created using
window class. It decides the layout of the window.
4. Frame: This is a top-level window with a border and menu bar.

METHODS IN COMPONENT CLASS:

Commonly used Methods of Component class


The methods of Component class are widely used in java swing that are given below.

Method Description

public void add(Component c) Add a component on another component.

public void setSize(int width,int height) Sets size of the component.

public void setLayout(LayoutManager Sets the layout manager for the component.
m)

public void setVisible(boolean b) Sets the visibility of the component. It is by default


false.

Example:
import java.awt.*;
class AwtDemo
{
AwtDemo()
{
Frame f=new Frame ();
Button b=new Button(“click me”);
b.setBounds (30, 50, 80, 30);
f.add (b);
f.setSize (300,300);
f.setLayout (null);
f.setVisible (true);

141
142 Object Oriented Programing

}
public static void main(String args[])
{
AwtDemo a=new AwtDemo();
}
}

MVC Architecture.
Ans. MVC means model, view and controller. This pattern is used to separate application concerns.
1. Model: The model represents the state (data) and business logic of the application.
2. View: The view model is responsible to display data i.e. it represents presentation.
3. Controller: The controller module acts as an interface between view and model. It interrupts
all the request i.e. receivers input and commands to model/view to change accordingly.

Controller

Database
Model
View (JSP) (Java Bean)

Container

ADVANTAGES OF MVC:

1. Easy to maintain.
2. Easy to control.
3. Easy to test.
4. Better separation of concerns.

JAVA LAYOUT MANAGERS:


The LayoutManagers are used to arrange components in a particular manner. LayoutManager is

142
143 Object Oriented Programing

an interface that is implemented by all classes of layout managers. These are following classes that
represent the layout managers.
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout
Etc…

JAVA BorderLayout:
The BorderLayout is used to arrange the components in five regions: north, south, east, west and
center. Each region (area) may contain one component only. It is the default layout of frame or
window. The BorderLayout provides five constants for each region:
 public static final int NORTH
 public static final int SOUTH
 public static final int EAST
 public static final int WEST
 public static final int CENTER

Constructors of BorderLayout Class:


 BorderLayout(): creates a border layout but with no gaps between the components.
 JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and
vertical gaps between the components.

143
144 Object Oriented Programing

NORTH

CENTER EAS
WEST
T

SOUTH

BORDER LAYOUT PROGRAM:


import java.awt.*;
import javax.swing.*;

public class Border {


JFrame f;
Border()
{
f = new JFrame();
JButton b1=new JButton (“NORTH”);
JButton b2=new JButton (“SOUTH”);
JButton b3=new JButton (“EAST”);
JButton b4=new JButton (“WEST”);
JButton b5=new JButton (“CENTER”);

f.add(b1, BorderLayout.NORTH);
f.add(b2, BorderLayout.SOUTH);
f.add(b3, BorderLayout.EAST);
f.add(b4, BorderLayout.WEST);

144
145 Object Oriented Programing

f.add(b5, BorderLayout.CENTER);

f.setSize(300,300);
f.setVisible(true);
}
public static void main(String args[])
{
new Border();
}
}

JAVA GridLayout:
The GridLayout is used to arrange the components in rectangular grid. One component is
displayed in each rectangle.
Constructors of GridLayout Class:
 GridLayout(): creates a grid layout with one column per component in a row.
 GridLayout(int rows, int columns): creates a grid layout with given rows and columns but no
gaps between the component.
 GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the given
rows and columns along with given horizontal and vertical gaps.

PROGRAM:
import java.awt.*;
import javax.swing.*;

public class MyGridLayout


{
JFrame f;
MyGridLayout()
{
f=new JFrame();
Button b1=new JButton(“1”);
Button b2=new JButton(“2”);
Button b3=new JButton(“3”);

145
146 Object Oriented Programing

Button b4=new JButton(“4”);


Button b5=new JButton(“5”);
Button b6=new JButton(“6”);
Button b7=new JButton(“7”);
Button b8=new JButton(“8”);
Button b9=new JButton(“9”);

f.add(b1); f.add(b2); f.add(b3); f.add(b4); f.add(b5);


f.add(b6); f.add(b7); f.add(b8); f.add(b9);

f.setLayout(new GridLayout(3,3));
//setting grid layout of 3 rows and 3 columns

f.setSize(300,300);
f.setVisible(true);
}

public static void main(String args[])


{
new MyGridLayout();
}
}

Example of GridLayout Class:

146
147 Object Oriented Programing

1 2 3

4 5 6

7 8 9

JAVA FlowLayout:
The FlowLayout is used to arrange the components in a line, one after another (in a flow).It is the
default layout of applet or panel.

FIELDS OF FlowLayout Class:


1. public static final int LEFT
2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING
5. public static final int TRAILING

Constructors of FlowLayout Class:


1. FlowLayout(): creates a flow layout with centered alignment and a default 5
unit horizontal and vertical gap.
2. FlowLayout(int align): creates a flow layout with the given alignment and a
default 5 unit horizontal and vertical gap.

PROGRAM:
import java.awt.*;
import javax.swing.*;

147
148 Object Oriented Programing

public class MyGridLayout


{
JFrame f;
MyGridLayout()
{ f=new JFrame();

Button b1=new JButton(“1”);


Button b2=new JButton(“2”);
Button b3=new JButton(“3”);
Button b4=new JButton(“4”);
Button b5=new JButton(“5”);
f.add(b1); f.add(b2); f.add(b3); f.add(b4); f.add(b5);

f.setLayout(new FlowLayout(FlowLayout.RIGHT));
//setting flow layout of right alignment

f.setSize(300,300);
f.setVisible(true);
}

public static void main(String args[])


{ new MyFlowLayout();
}
}

JAVA CardLayout:
The CardLayout class manages the components in such a manner that only one component is
visible at a time. It treats each component as a card that is why it is known as CardLayout.

Constructors of CardLayout Class:


1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given horizontal
and vertical gap.

148
149 Object Oriented Programing

COMMONLY USED METHODS OF CardLayout Class:


 public void next(Container parent): is used to flip to the next card of the
given container.
 public void previous(Container parent): is used to flip to the previous card
of the given container.
 public void first(Container parent): is used to flip to the first card of the
given container.

 public void last(Container parent): is used to flip to the last card of the
given container.

PROGRAM:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class CardLayoutExample extends JFrame implements ActionListener{
CardLayout card;
JButton b1,b2,b3;
Container c;
CardLayoutExample(){

c=getContentPane();
card=new CardLayout(40,30);
//create CardLayout object with 40 hor space and 30 ver space
c.setLayout(card);

b1=new JButton(“Apple”);
b2=new JButton(“Boy”);
b3=new JButton(“Cat”);
b1.add ActionListener(this);
b2.add ActionListener(this);
b3.add ActionListener(this);

149
150 Object Oriented Programing

c.add(“a”,b1);
c.add(“b”,b2);
c.add(“c”,b3);
}
public void actionPerformed(ActionEvent e)
card.next( c );
}
public static void main(String args[])
{
CardLayoutExample cl=new CardLayoutExample;
cl.setSize(400,400);
cl.setVisible(true);
cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}

EXAMPLE OF CARD LAYOUT CLASS:

Applet

JAVA GridBagLayout:
150
151 Object Oriented Programing

The Java GridBagLayout class is used to align components vertically, horizontally or along their
baseline.
The components may not be of same size . Each GridBagLayout object maintains a
dynamic,rectangular grid of cells. Each component occupies one or more cells known as its
dispkay area. Each component associates as instance of GridBagConstraints .With the help of
constraints object we arrange component’s display area on grid. the GridBagLayout manages
each component’s minimum and preferred sizes in order to determine component’ s size.
import java.awt.Button;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.*;

public class GridBagLayoutExample extends JFrame


{
public static void main(String args[])
{
GridBagLayoutExample a=new GridBagLayoutExample;
}
public GridBagLayoutExample()
{
GridBagLayout grid= new GridBagLayout();
GridBagConstraints gbc= new GridBagConstraints();
setLayout(grid);
setTitle(“GridBagLayout Example”);
GridBagLayout layout= new GridBagLayout();
this.setLayout(layout);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx=0;
gbc.gridy=0;
this.add(new Button(“Button One”),gbc);
gbc.gridx=1;
gbc.gridy=0;
this.add(new Button(“Button Two”),gbc);

151
152 Object Oriented Programing

gbc.ipady=20;
gbc.gridx=0;
gbc.gridy=1;
this.add(new Button(“Button Three”),gbc);
gbc.gridx=1;
gbc.gridy=1;
this.add(new Button(“Button Four”),gbc);
gbc.gridx=0;
gbc.gridy=2;
this.add(new Button(“Button Five”),gbc);
setSize(300,300);
setPreferredSize(getSize());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
OUTPUT:

GridBagLayout Example

Button One Button Two

Button Three Button Four

Button Five

152
153 Object Oriented Programing

EVENT HANDLING
Change in the state of an object is known as event i.e. event describes the change in state of
source. Events are generated as result of user interaction with graphical user interface
components. For example, clicking on a button, moving the mouse, entering a character through
keyboard, selecting an item from list, scrolling the page are the activities that causes an event to
happen.

What is Event Handling?


Ans. Event handling is the mechanism that controls the vent and decides what should happen if an
event occurs. This mechanism have the code which is known as event handler that is executed
when an event occurs. Java uses Delegation Event Model to handle the events. This model defines
the standard mechanism to generate and handle the events.

What is Delegation Event Model?


The Delegation Event Model has the following key participants namely:
Source- The source is an object on which event occurs. Source is responsible for providing
information of the occurred event to it’s handler. Java provide as with classes for source object.
Listener- It is also known as event handler.Listener is responsible for generating response to an
event. From java implementation point of view the listener is also an object. Listener waits until it
receives an event. Once the event is received, the listener process the event an then returns.
The benefit of this approach is that the user interface logic is completely separated from the logic
that generates the event. The user interface element is able to delegate the processing of an
event to the separate piece of code. In this model, Listener needs to be registered with the source
object so that the listener can receive the event notification. This is an efficient way of handling the
event because the event notifications are sent only to those listeners that want to receive them.

Steps involved in event handling


The user clicks the button and the event is generated.
Now the object of concerned event class is created automatically and information about the
source and the event get populated with in same object.
Event object is forwarded to the method of registered listener class.
The method is now executed and returns.

Callback Methods:
These are the methods that are provided by API provider and are defined by the application
programmer and invoked by the application developer. Here the callback methods represents an
event method. In response to an event java jre will fire callback method.

153
154 Object Oriented Programing

All such callback methods are provided in listener interfaces.


If a component wants some listener will listen to its events the source must register itself to the
listener.

Explain different event Listener in java.awt.event Package.


The Event Listener represents the interfaces responsible to handle events.
Java provides us various Event Listener classes.
Every method of an event listener method has a single argument as an object which is subclass of
EventObject class. For example, mouse event listener methods will accept instance of MouseEvent,
where MouseEvent derives from EventObject.

EventListener interface:
It is a marker interface which every listener interface has to extend . This class is defined in java.util
package.
SYNTAX:
public interface EventListener
AWT Event Listener Interfaces:

Following is the list of commonly used event listeners:-

NO. Control and Description


1. ActionListener:

This interface is used for receiving the action events.


2. ComponentListener:

This interface is used for receiving the component events.


3. ItemListener:

This interface is used for receiving item events.


4. KeyListener:

This interface is used for receving the key events.


5. MouseListener:

This interface is used for receiving the mouse events.


6. TextListener:

This interface is used for receiving the text events.


7. WindowListener:

This interface is used for receiving the window events.

154
155 Object Oriented Programing

8. AdjustmentListener:

This interface is used for receiving the adjustment events.


9. ContainerListener:

This interface is used for receiving the container events.


10. MouseMonitorListener:

This interface is used for receiving the mouse motion events.

EVENT CLASSES:
The Event classes represent the event. Java provides us Event classes EventObject class.
It is the root class from which all event state objects shall be derived. All Events are constructed
with a reference to the object, the source, that is logically deemed to be the object upon which
the Event in question initially occurred upon. This class is defined in java.util package.

Constructors:
EventObject(Object source):Constructs a protypical Event.

Class Methods:
1. Object getSource(): The object on which the Event initially occurred.
2. String toString():Returns a string representation of this EventObject.

AWT EVENT CLASSES:


Following is the list of commonly used event classes.
NO. Control and Description
1. AWTEvent

It is the root event class for all the AWT events.This class and its
subclasses supercede the original java.awt.Event class.
2. ActionEvent

The ActionEvent is generated when button is clicked or the item of a


list is double clicked.
3. InputEvent

The InputEvent class is root event class for all the component-level
input events.
4. KeyEvent

155
156 Object Oriented Programing

On entering the character the Key event is generated.


5. MouseEvent

This event indicates a mouse action occurred in a component.


6. TextEvent
The object of this class represents the text event.
7. WindowEvent

The object of this class represents the change in state of a window.


8. AdjustmentEvent

The object of this class represents the adjustment event emitted by


Adjustable objects.
9. ComponentEvent

The object of this class represents the change in state of a window.


10. ContainerEvent

The object of this class represents the change in state of a window.

JAVA APPLET
Applet is a special type of program that is embedded in the webpage to generate
the dynamic content. It runs inside the browser and works at client side.

ADVANTAGE OF APPLET
There are many advantages of applet. They are as follows:
 It works at client side so less response time.
 Secured.
 It can be executed by browsers running under many platforms ,including Linux,
Windows, Mac OS etc.

DRAWBACKS OF APPLET
 Plugin is required at client browser to execute applet.
 Hierarchy of Applet.

156
157 Object Oriented Programing

As displayed in the above diagram, Applet class extends Panel.


Panel class extends Container which is the subclass of Component.

Lifecycle of Java Applet


1. Applet is initialized
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.

Lifecycle methods for Applet:


The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life
cycle methods for an applet.

java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods
of applet.

 public void init(): is used to initialized the Applet. It is invoked only once.

157
158 Object Oriented Programing

 public void start(): is invoked after the init() method or browser is maximized. It is
used to start the Applet.
 public void stop(): is used to stop the Applet. It is invoked when Applet is stop or
browser is minimized.
 public void destroy(): is used to destroy the Applet. It is invoked only once.

java.awt.Component class
The Component class provides 1 life cycle method of applet.

 public void paint(Graphics g): is used to paint the Applet. It provides Graphics
class object that can be used for drawing oval, rectangle, arc etc.

How to run an Applet?

There are two ways to run an applet


 By html file.
 By appletViewer tool (for testing purpose).

EXAMPLE:

1.//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g)
{
g.drawString(“welcome”,150,150);
}

}
myapplet.html
<html>
<body>
<applet code = “First.class” width=”300” height=”300”>
</applet>
</body>
</html>

158
159 Object Oriented Programing

To execute the applet by appletviewer tool , write in command prompt:


c:\>javac First.java
c:\>appletviewer First.java

What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify the
development of desktop applications.

Difference between AWT and Swing


There are many differences between java awt and swing that are given below.

No. Java AWT Java Swing

1) AWT components are platform-dependent. Java swing components


are platform-independent.

2) AWT components are heavyweight. Swing components


are lightweight.

3) AWT doesn't support pluggable look and Swing supports pluggable look
feel. and feel.

4) AWT provides less components than Swing. Swing provides more powerful
components such as tables, lists,
scrollpanes, colorchooser,
tabbedpane etc.

5) AWT doesn't follows MVC (Model View Swing follows MVC.


Controller) where model represents data, view
represents presentation and controller acts as
an interface between model and view.

159
160 Object Oriented Programing

Hierarchy of Java Swing classes


The hierarchy of java swing API is given below.

Java Swing Examples


There are two ways to create a frame:

o By creating the object of Frame class (association)

o By extending Frame class (inheritance)

We can write the code of swing inside the main(), constructor or any other method.

160
161 Object Oriented Programing

Simple Java Swing Example


Let's see a simple swing example where we are creating one button and adding it on the JFrame
object inside the main() method.

File: FirstSwingExample.java

1. import javax.swing.*;
2. public class FirstSwingExample {
3. public static void main(String[] args) {
4. JFrame f=new JFrame();//creating instance of JFrame
5.
6. JButton b=new JButton("click");//creating instance of JButton
7. b.setBounds(130,100,100, 40);//x axis, y axis, width, height
8.
9. f.add(b);//adding button in JFrame
10.
11. f.setSize(400,500);//400 width and 500 height
12. f.setLayout(null);//using no layout managers
13. f.setVisible(true);//making the frame visible
14. }

15. }

161
162 Object Oriented Programing

Example of Swing by Association inside constructor


We can also write all the codes of creating JFrame, JButton and method call inside the java
constructor.
File: Simple.java

1. import javax.swing.*;
2. public class Simple {
3. JFrame f;
4. Simple(){
5. f=new JFrame();//creating instance of JFrame
6.
7. JButton b=new JButton("click");//creating instance of JButton
8. b.setBounds(130,100,100, 40);
9.
10. f.add(b);//adding button in JFrame
11.
12. f.setSize(400,500);//400 width and 500 height
13. f.setLayout(null);//using no layout managers
14. f.setVisible(true);//making the frame visible
15. }
16.
17. public static void main(String[] args) {
18. new Simple();
19. }
20. }
The setBounds(int xaxis, int yaxis, int width, int height)is used in the above example that sets the
position of the button.

Simple example of Swing by inheritance


We can also inherit the JFrame class, so there is no need to create the instance of JFrame class
explicitly.

File: Simple2.java

1. import javax.swing.*;
2. public class Simple2 extends JFrame{//inheriting JFrame
3. JFrame f;
4. Simple2(){

162
163 Object Oriented Programing

5. JButton b=new JButton("click");//create button


6. b.setBounds(130,100,100, 40);
7.
8. add(b);//adding button on frame
9. setSize(400,500);
10. setLayout(null);
11. setVisible(true);
12. }
13. public static void main(String[] args) {
14. new Simple2();
15. }}

Java JFrame
The javax.swing.JFrame class is a type of container which inherits the java.awt.Frame class. JFrame
works like the main window where components like labels, buttons, textfields are added to create
a GUI.
Unlike Frame, JFrame has the option to hide or close the window with the help of
setDefaultCloseOperation(int) method.

Nested Class
Modifier and Class Description
Type

protected class JFrame.AccessibleJFrame This class implements accessibility support for the
JFrame class.

Fields
Modifier and Field Description
Type

protected accessibleContext The accessible context property.


AccessibleContext

static int EXIT_ON_CLOSE The exit application default window close


operation.

163
164 Object Oriented Programing

protected JRootPane rootPane The JRootPane instance that manages the


contentPane and optional menuBar for this
frame, as well as the glassPane.

protected boolean rootPaneCheckingEnabled If true then calls to add and setLayout will be
forwarded to the contentPane.

Constructors
Constructor Description

JFrame() It constructs a new frame that is initially invisible.

JFrame(GraphicsConfiguration gc) It creates a Frame in the specified GraphicsConfiguration of


a screen device and a blank title.

JFrame(String title) It creates a new, initially invisible Frame with the specified
title.

JFrame(String title, It creates a JFrame with the specified title and the specified
GraphicsConfiguration gc) GraphicsConfiguration of a screen device.

Useful Methods
Modifier and Method Description
Type

protected void addImpl(Component comp, Object Adds the specified child


constraints, int index) Component.

protected createRootPane() Called by the constructor


JRootPane methods to create the
default rootPane.

protected void frameInit() Called by the constructors


to init the JFrame properly.

void setContentPane(Containe contentPane) It sets the contentPane


property

164
165 Object Oriented Programing

static void setDefaultLookAndFeelDecorated(boolean Provides a hint as to


defaultLookAndFeelDecorated) whether or not newly
created JFrames should
have their Window
decorations (such as
borders, widgets to close
the window, title...)
provided by the current
look and feel.

void setIconImage(Image image) It sets the image to be


displayed as the icon for this
window.

void setJMenuBar(JMenuBar menubar) It sets the menubar for this


frame.

void setLayeredPane(JLayeredPane It sets the layeredPane


layeredPane) property.

JRootPane getRootPane() It returns the rootPane


object for this frame.

TransferHandler getTransferHandler() It gets the transferHandler


property.

JFrame Example
1. import java.awt.FlowLayout;
2. import javax.swing.JButton;
3. import javax.swing.JFrame;
4. import javax.swing.JLabel;
5. import javax.swing.Jpanel;
6. public class JFrameExample {
7. public static void main(String s[]) {
8. JFrame frame = new JFrame("JFrame Example");
9. JPanel panel = new JPanel();
10. panel.setLayout(new FlowLayout());
11. JLabel label = new JLabel("JFrame By Example");
12. JButton button = new JButton();

165
166 Object Oriented Programing

13. button.setText("Button");
14. panel.add(label);
15. panel.add(button);
16. frame.add(panel);
17. frame.setSize(200, 300);
18. frame.setLocationRelativeTo(null);
19. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
20. frame.setVisible(true);
21. }
22. }

Output

Java JButton
The JButton class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed. It inherits
AbstractButton class.

JButton class declaration


Let's see the declaration for javax.swing.JButton class.

1. public class JButton extends AbstractButton implements Accessible

Commonly used Constructors:


Constructor Description

JButton() It creates a button with no text and icon.

166
167 Object Oriented Programing

JButton(String s) It creates a button with the specified text.

JButton(Icon i) It creates a button with the specified icon object.

Commonly used Methods of AbstractButton class:


Methods Description

void setText(String s) It is used to set specified text on button

String getText() It is used to return the text of the button.

void setEnabled(boolean b) It is used to enable or disable the button.

void setIcon(Icon b) It is used to set the specified Icon on the button.

Icon getIcon() It is used to get the Icon of the button.

void setMnemonic(int a) It is used to set the mnemonic on the button.

void addActionListener(ActionListener a) It is used to add the action listener to this object.

Java JButton Example


1. import javax.swing.*;
2. public class ButtonExample {
3. public static void main(String[] args) {
4. JFrame f=new JFrame("Button Example");
5. JButton b=new JButton("Click Here");
6. b.setBounds(50,100,95,30);
7. f.add(b);
8. f.setSize(400,400);
9. f.setLayout(null);
10. f.setVisible(true);
11. }
12. }

Output:

167
168 Object Oriented Programing

Java JButton Example with ActionListener


1. import java.awt.event.*;
2. import javax.swing.*;
3. public class ButtonExample {
4. public static void main(String[] args) {
5. JFrame f=new JFrame("Button Example");
6. final JTextField tf=new JTextField();
7. tf.setBounds(50,50, 150,20);
8. JButton b=new JButton("Click Here");
9. b.setBounds(50,100,95,30);
10. b.addActionListener(new ActionListener(){
11. public void actionPerformed(ActionEvent e){
12. tf.setText("Welcome to Java.");
13. }
14. });
15. f.add(b);f.add(tf);
16. f.setSize(400,400);
17. f.setLayout(null);
18. f.setVisible(true);
19. }
20. }

Output:

168
169 Object Oriented Programing

Example of displaying image on the button:


1. import javax.swing.*;
2. public class ButtonExample{
3. ButtonExample(){
4. JFrame f=new JFrame("Button Example");
5. JButton b=new JButton(new ImageIcon("D:\\icon.png"));
6. b.setBounds(100,100,100, 40);
7. f.add(b);
8. f.setSize(300,400);
9. f.setLayout(null);
10. f.setVisible(true);
11. f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
12. }
13. public static void main(String[] args) {
14. new ButtonExample();
15. }
16. }

Output:

169
170 Object Oriented Programing

Java JLabel
The object of JLabel class is a component for placing text in a container. It is used to display a
single line of read only text. The text can be changed by an application but a user cannot edit it
directly. It inherits JComponent class.

JLabel class declaration


Let's see the declaration for javax.swing.JLabel class.

1. public class JLabel extends JComponent implements SwingConstants, Accessible

Commonly used Constructors:


Constructor Description

JLabel() Creates a JLabel instance with no image and with an empty


string for the title.

JLabel(String s) Creates a JLabel instance with the specified text.

JLabel(Icon i) Creates a JLabel instance with the specified image.

JLabel(String s, Icon i, int Creates a JLabel instance with the specified text, image,
horizontalAlignment) and horizontal alignment.

170
171 Object Oriented Programing

Commonly used Methods:


Methods Description

String getText() t returns the text string that a label displays.

void setText(String text) It defines the single line of text this component will
display.

void setHorizontalAlignment(int It sets the alignment of the label's contents along the X
alignment) axis.

Icon getIcon() It returns the graphic image that the label displays.

int getHorizontalAlignment() It returns the alignment of the label's contents along the
X axis.

Java JLabel Example


1. import javax.swing.*;
2. class LabelExample
3. {
4. public static void main(String args[])
5. {
6. JFrame f= new JFrame("Label Example");
7. JLabel l1,l2;
8. l1=new JLabel("First Label.");
9. l1.setBounds(50,50, 100,30);
10. l2=new JLabel("Second Label.");
11. l2.setBounds(50,100, 100,30);
12. f.add(l1); f.add(l2);
13. f.setSize(300,300);
14. f.setLayout(null);
15. f.setVisible(true);
16. }
17. }

Output:

171
172 Object Oriented Programing

Java JTextField
The object of a JTextField class is a text component that allows the editing of a single line text. It
inherits JTextComponent class.

JTextField class declaration


Let's see the declaration for javax.swing.JTextField class.

1. public class JTextField extends JTextComponent implements SwingConstants

Commonly used Constructors:


Constructor Description

JTextField() Creates a new TextField

JTextField(String text) Creates a new TextField initialized with the specified text.

JTextField(String text, int Creates a new TextField initialized with the specified text and
columns) columns.

JTextField(int columns) Creates a new empty TextField with the specified number of
columns.

172
173 Object Oriented Programing

Commonly used Methods:


Methods Description

void addActionListener(ActionListener It is used to add the specified action listener to receive


l) action events from this textfield.

Action getAction() It returns the currently set Action for this ActionEvent
source, or null if no Action is set.

void setFont(Font f) It is used to set the current font.

void It is used to remove the specified action listener so that it


removeActionListener(ActionListener l) no longer receives action events from this textfield.

Java JTextField Example


1. import javax.swing.*;
2. class TextFieldExample
3. {
4. public static void main(String args[])
5. {
6. JFrame f= new JFrame("TextField Example");
7. JTextField t1,t2;
8. t1=new JTextField("Welcome to Java.");
9. t1.setBounds(50,100, 200,30);
10. t2=new JTextField("AWT Tutorial");
11. t2.setBounds(50,150, 200,30);
12. f.add(t1); f.add(t2);
13. f.setSize(400,400);
14. f.setLayout(null);
15. f.setVisible(true);
16. }
17. }

Output:

173
174 Object Oriented Programing

Java JCheckBox
The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or off
(false). Clicking on a CheckBox changes its state from "on" to "off" or from "off" to "on ".It inherits
JToggleButton class.

JCheckBox class declaration


Let's see the declaration for javax.swing.JCheckBox class.

1. public class JCheckBox extends JToggleButton implements Accessible

Commonly used Constructors:


Constructor Description

JJCheckBox() Creates an initially unselected check box button with no text,


no icon.

JChechBox(String s) Creates an initially unselected check box with text.

JCheckBox(String text, boolean Creates a check box with text and specifies whether or not it is
selected) initially selected.

JCheckBox(Action a) Creates a check box where properties are taken from the
Action supplied.

174
175 Object Oriented Programing

Commonly used Methods:


Methods Description

AccessibleContext It is used to get the AccessibleContext associated with this


getAccessibleContext() JCheckBox.

protected String paramString() It returns a string representation of this JCheckBox.

Java JCheckBox Example


1. import javax.swing.*;
2. public class CheckBoxExample
3. {
4. CheckBoxExample(){
5. JFrame f= new JFrame("CheckBox Example");
6. JCheckBox checkBox1 = new JCheckBox("C++");
7. checkBox1.setBounds(100,100, 50,50);
8. JCheckBox checkBox2 = new JCheckBox("Java", true);
9. checkBox2.setBounds(100,150, 50,50);
10. f.add(checkBox1);
11. f.add(checkBox2);
12. f.setSize(400,400);
13. f.setLayout(null);
14. f.setVisible(true);
15. }
16. public static void main(String args[])
17. {
18. new CheckBoxExample();
19. }}

Output:

175
176 Object Oriented Programing

Java JRadioButton
The JRadioButton class is used to create a radio button. It is used to choose one option from
multiple options. It is widely used in exam systems or quiz.
It should be added in ButtonGroup to select one radio button only.

JRadioButton class declaration


Let's see the declaration for javax.swing.JRadioButton class.

1. public class JRadioButton extends JToggleButton implements Accessible

Commonly used Constructors:


Constructor Description

JRadioButton() Creates an unselected radio button with no text.

JRadioButton(String s) Creates an unselected radio button with specified text.

JRadioButton(String s, boolean Creates a radio button with the specified text and selected
selected) status.

176
177 Object Oriented Programing

Commonly used Methods:


Methods Description

void setText(String s) It is used to set specified text on button.

String getText() It is used to return the text of the button.

void setEnabled(boolean b) It is used to enable or disable the button.

void setIcon(Icon b) It is used to set the specified Icon on the button.

Icon getIcon() It is used to get the Icon of the button.

void setMnemonic(int a) It is used to set the mnemonic on the button.

void addActionListener(ActionListener a) It is used to add the action listener to this object.

Java JRadioButton Example


1. import javax.swing.*;
2. public class RadioButtonExample {
3. JFrame f;
4. RadioButtonExample(){
5. f=new JFrame();
6. JRadioButton r1=new JRadioButton("A) Male");
7. JRadioButton r2=new JRadioButton("B) Female");
8. r1.setBounds(75,50,100,30);
9. r2.setBounds(75,100,100,30);
10. ButtonGroup bg=new ButtonGroup();
11. bg.add(r1);bg.add(r2);
12. f.add(r1);f.add(r2);
13. f.setSize(300,300);
14. f.setLayout(null);
15. f.setVisible(true);
16. }
17. public static void main(String[] args) {
18. new RadioButtonExample();

177
178 Object Oriented Programing

19. }
20. }

Output:

Java JComboBox
The object of Choice class is used to show popup menu of choices. Choice selected by user is
shown on the top of a menu. It inherits JComponent class.

JComboBox class declaration


Let's see the declaration for javax.swing.JComboBox class.

1. public class JComboBox extends JComponent implements ItemSelectable, ListDataListener, Acti


onListener, Accessible

Commonly used Constructors:


Constructor Description

JComboBox() Creates a JComboBox with a default data model.

JComboBox(Object[] items) Creates a JComboBox that contains the elements in the specified
array.

JComboBox(Vector<?> Creates a JComboBox that contains the elements in the specified


items) Vector.

178
179 Object Oriented Programing

Commonly used Methods:


Methods Description

void addItem(Object anObject) It is used to add an item to the item list.

void removeItem(Object anObject) It is used to delete an item to the item list.

void removeAllItems() It is used to remove all the items from the list.

void setEditable(boolean b) It is used to determine whether the JComboBox is


editable.

void addActionListener(ActionListener It is used to add the ActionListener.


a)

void addItemListener(ItemListener i) It is used to add the ItemListener.

Java JComboBox Example


1. import javax.swing.*;
2. public class ComboBoxExample {
3. JFrame f;
4. ComboBoxExample(){
5. f=new JFrame("ComboBox Example");
6. String country[]={"India","Aus","U.S.A","England","Newzealand"};
7. JComboBox cb=new JComboBox(country);
8. cb.setBounds(50, 50,90,20);
9. f.add(cb);
10. f.setLayout(null);
11. f.setSize(400,500);
12. f.setVisible(true);
13. }
14. public static void main(String[] args) {
15. new ComboBoxExample();
16. }
17. }

Output:

179
180 Object Oriented Programing

Java JTable
The JTable class is used to display data in tabular form. It is composed of rows and columns.

JTable class declaration


Let's see the declaration for javax.swing.JTable class.

Commonly used Constructors:


Constructor Description

JTable() Creates a table with empty cells.

JTable(Object[][] rows, Object[] columns) Creates a table with the specified data.

Java JTable Example


1. import javax.swing.*;
2. public class TableExample {
3. JFrame f;
4. TableExample(){
5. f=new JFrame();
6. String data[][]={ {"101","Amit","670000"},
7. {"102","Jai","780000"},
8. {"101","Sachin","700000"}};

180
181 Object Oriented Programing

9. String column[]={"ID","NAME","SALARY"};
10. JTable jt=new JTable(data,column);
11. jt.setBounds(30,40,200,300);
12. JScrollPane sp=new JScrollPane(jt);
13. f.add(sp);
14. f.setSize(300,400);
15. f.setVisible(true);
16. }
17. public static void main(String[] args) {
18. new TableExample();
19. }
20. }
Output:

Java JList
The object of JList class represents a list of text items. The list of text items can be set up so that the
user can choose either one item or multiple items. It inherits JComponent class.

JList class declaration


Let's see the declaration for javax.swing.JList class.

1. public class JList extends JComponent implements Scrollable, Accessible

Commonly used Constructors:


Constructor Description

181
182 Object Oriented Programing

JList() Creates a JList with an empty, read-only, model.

JList(ary[] listData) Creates a JList that displays the elements in the specified array.

JList(ListModel<ary> Creates a JList that displays elements from the specified, non-null,
dataModel) model.

Commonly used Methods:


Methods Description

Void addListSelectionListener(ListSelectionListener It is used to add a listener to the list, to be


listener) notified each time a change to the selection
occurs.

int getSelectedIndex() It is used to return the smallest selected cell


index.

ListModel getModel() It is used to return the data model that holds a


list of items displayed by the JList component.

void setListData(Object[] listData) It is used to create a read-only ListModel from


an array of objects.

Java JList Example


1. import javax.swing.*;
2. public class ListExample
3. {
4. ListExample(){
5. JFrame f= new JFrame();
6. DefaultListModel<String> l1 = new DefaultListModel<>();
7. l1.addElement("Item1");
8. l1.addElement("Item2");
9. l1.addElement("Item3");
10. l1.addElement("Item4");
11. JList<String> list = new JList<>(l1);
12. list.setBounds(100,100, 75,75);
13. f.add(list);

182
183 Object Oriented Programing

14. f.setSize(400,400);
15. f.setLayout(null);
16. f.setVisible(true);
17. }
18. public static void main(String args[])
19. {
20. new ListExample();
21. }}
Output:

Java JToggleButton
JToggleButton is used to create toggle button, it is two-states button to switch on or off.

Nested Classes
Modifier Class Description
and Type

protected class JToggleButton.AccessibleJToggleButton This class implements accessibility


support for the JToggleButton class.

static class JToggleButton.ToggleButtonModel The ToggleButton model

183
184 Object Oriented Programing

Constructors
Constructor Description

JToggleButton() It creates an initially unselected toggle button without


setting the text or image.

JToggleButton(Action a) It creates a toggle button where properties are taken


from the Action supplied.

JToggleButton(Icon icon) It creates an initially unselected toggle button with the


specified image but no text.

JToggleButton(Icon icon, boolean It creates a toggle button with the specified image and
selected) selection state, but no text.

JToggleButton(String text) It creates an unselected toggle button with the specified


text.

JToggleButton(String text, boolean It creates a toggle button with the specified text and
selected) selection state.

JToggleButton(String text, Icon icon) It creates a toggle button that has the specified text and
image, and that is initially unselected.

JToggleButton(String text, Icon icon, It creates a toggle button with the specified text, image,
boolean selected) and selection state.

Methods
Modifier and Method Description
Type

AccessibleContext getAccessibleContext() It gets the AccessibleContext associated with this


JToggleButton.

String getUIClassID() It returns a string that specifies the name of the l&f
class that renders this component.

protected String paramString() It returns a string representation of this

184
185 Object Oriented Programing

JToggleButton.

void updateUI() It resets the UI property to a value from the current


look and feel.

JToggleButton Example
1. import java.awt.FlowLayout;
2. import java.awt.event.ItemEvent;
3. import java.awt.event.ItemListener;
4. import javax.swing.JFrame;
5. import javax.swing.JToggleButton;
6.
7. public class JToggleButtonExample extends JFrame implements ItemListener {
8. public static void main(String[] args) {
9. new JToggleButtonExample();
10. }
11. private JToggleButton button;
12. JToggleButtonExample() {
13. setTitle("JToggleButton with ItemListener Example");
14. setLayout(new FlowLayout());
15. setJToggleButton();
16. setAction();
17. setSize(200, 200);
18. setVisible(true);
19. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
20. }
21. private void setJToggleButton() {
22. button = new JToggleButton("ON");
23. add(button);
24. }
25. private void setAction() {
26. button.addItemListener(this);
27. }
28. public void itemStateChanged(ItemEvent eve) {
29. if (button.isSelected())
30. button.setText("OFF");

185
186 Object Oriented Programing

31. else
32. button.setText("ON");
33. }
34. }

Output

Java JScrollPane
A JscrollPane is used to make scrollable view of a component. When screen size is limited, we use a
scroll pane to display a large component or a component whose size can change dynamically.

Constructors
Constructor Purpose

JScrollPane() It creates a scroll pane. The Component parameter, when present,


sets the scroll pane's client. The two int parameters, when present, set
the vertical and horizontal scroll bar policies (respectively).

JScrollPane(Component)

JScrollPane(int, int)

JScrollPane(Component,
int, int)

186
187 Object Oriented Programing

Useful Methods
Modifier Method Description
void setColumnHeaderView(Component) It sets the column header for the scroll
pane.
void setRowHeaderView(Component) It sets the row header for the scroll pane.
void setCorner(String, Component) It sets or gets the specified corner. The int
parameter specifies which corner and must
be one of the following constants defined in
ScrollPaneConstants: UPPER_LEFT_CORNER,
UPPER_RIGHT_CORNER,
LOWER_LEFT_CORNER,
LOWER_RIGHT_CORNER,
LOWER_LEADING_CORNER,
LOWER_TRAILING_CORNER,
UPPER_LEADING_CORNER,
UPPER_TRAILING_CORNER.
Component getCorner(String) (The same as setCorner)
void setViewportView(Component) Set the scroll pane's client.

JScrollPane Example
1. import java.awt.FlowLayout;
2. import javax.swing.JFrame;
3. import javax.swing.JScrollPane;
4. import javax.swing.JtextArea;
5.
6. public class JScrollPaneExample {
7. private static final long serialVersionUID = 1L;
8.
9. private static void createAndShowGUI() {
10. // Create and set up the window.
11. final JFrame frame = new JFrame("Scroll Pane Example");
12.
13. // Display the window.
14. frame.setSize(500, 500);
15. frame.setVisible(true);
16. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
17.
18. // set flow layout for the frame
19. frame.getContentPane().setLayout(new FlowLayout());
20.
21. JTextArea textArea = new JTextArea(20, 20);

187
188 Object Oriented Programing

22. JScrollPane scrollableTextArea = new JScrollPane(textArea);


23.
24. scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

25. scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
26.
27. frame.getContentPane().add(scrollableTextArea);
28. }
29. public static void main(String[] args) {
30.
31.
32. javax.swing.SwingUtilities.invokeLater(new Runnable() {
33.
34. public void run() {
35. createAndShowGUI();
36. }
37. });
38. }
39. }

Output:

188
189 Object Oriented Programing

Java JTabbedPane
The JTabbedPane class is used to switch between a group of components by clicking on a tab
with a given title or icon. It inherits JComponent class.

JTabbedPane class declaration


Let's see the declaration for javax.swing.JTabbedPane class.

1. public class JTabbedPane extends JComponent implements Serializable, Accessible, SwingConst


ants

Commonly used Constructors:


Constructor Description

JTabbedPane() Creates an empty TabbedPane with a default tab


placement of JTabbedPane.Top.

JTabbedPane(int tabPlacement) Creates an empty TabbedPane with a specified tab


placement.

JTabbedPane(int tabPlacement, int Creates an empty TabbedPane with a specified tab


tabLayoutPolicy) placement and tab layout policy.

Java JTabbedPane Example


1. import javax.swing.*;
2. public class TabbedPaneExample {
3. JFrame f;
4. TabbedPaneExample(){
5. f=new JFrame();
6. JTextArea ta=new JTextArea(200,200);
7. JPanel p1=new JPanel();
8. p1.add(ta);
9. JPanel p2=new JPanel();
10. JPanel p3=new JPanel();
11. JTabbedPane tp=new JTabbedPane();
12. tp.setBounds(50,50,200,200);
13. tp.add("main",p1);
14. tp.add("visit",p2);
15. tp.add("help",p3);

189
190 Object Oriented Programing

16. f.add(tp);
17. f.setSize(400,400);
18. f.setLayout(null);
19. f.setVisible(true);
20. }
21. public static void main(String[] args) {
22. new TabbedPaneExample();
23. }}
Output:

Displaying image in swing:


For displaying image, we can use the method drawImage() of Graphics class.

Syntax of drawImage() method:


1. public abstract boolean drawImage(Image img, int x, int y, ImageObserver
observer): is used draw the specified image.

190
191 Object Oriented Programing

Example of displaying image in swing:

1. import java.awt.*;
2. import javax.swing.JFrame;
3.
4. public class MyCanvas extends Canvas{
5.
6. public void paint(Graphics g) {
7.
8. Toolkit t=Toolkit.getDefaultToolkit();
9. Image i=t.getImage("p3.gif");
10. g.drawImage(i, 120,100,this);
11.
12. }
13. public static void main(String[] args) {
14. MyCanvas m=new MyCanvas();
15. JFrame f=new JFrame();
16. f.add(m);
17. f.setSize(400,400);
18. f.setVisible(true);
19. }
20.
21. }

191

You might also like