Object Oriented Programming Using Java
Code: PCCS4203 (2021-2022)
4th Semester B.Tech CSE
IGIT, Sarang, Dhenkanal Dist., Odisha.
Syllabus
Module 2: -
Chapter 1-: Introduction to Classes and Objects.
Classes, Methods, Objects, Description of data hiding and data encapsulation,
Constructors, Use of static Keyword in Java, Use of this Keyword in Java, Array of
Objects, Concept of Access Modifiers (Public, Private, Protected,Default).
Chapter 2-: Inheritance
Understanding Inheritance, Types of Inheritance and Java supported Inheritance,
Significance of Inheritance, Constructor call in Inheritance, Use of super keyword
in Java, Polymorphism, Understanding Polymorphism, Types of polymorphism,
Significance of Polymorphism in Java, Method Overloading, Constructor
Overloading, Method Overriding, Dynamic Method Dispatching.
Chapter 3-: String Manipulations.
Introduction to different classes, String class, String Buffer, String Builder, String
Tokenizer, Concept of Wrapper Classes, Introduction to wrapper classes, Different
predefined wrapper classes, Predefined Constructors for the wrapper classes.
Conversion of types from one type (Object) to another type (Primitive) and Vice
versa, Concept of Auto boxing and unboxing.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Chapter 4:- DataAbstraction
Basics of Data Abstraction, Understanding Abstract classes, Understanding
Interfaces, Multiple Inheritance Using Interfaces, Packages, Introduction to
Packages, Java API Packages, User-Defined Packages, Accessing Packages, Error
and Exception Handling, Introduction to error and exception, Types of exceptions
and difference between the types, Runtime Stack Mechanism, Hierarchy of
Exception classes, Default exception handling in Java, User defined/Customized
Exception Handling, Understanding different keywords (try, catch, finally, throw,
throws), User defined exception classes, Commonly used Exceptions and their
details.
Chapter 5:- Multithreading
Introduction of Multithreading/Multitasking, Ways to define a Thread in Java,
Thread naming and Priorities, Thread execution prevention methods. (yield(),
join(), sleep()), Concept of Synchronisation, Inter Thread Communication, Basics
of Deadlock, Demon Thread, Improvement in Multithreading, Inner Classes,
Introduction, Member inner class, Static inner class, Local inner class, Anonymous
inner class.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
NESTED CLASS EXAMPLES
// Inner Class Example-1.
class OuterClass
{
// nested inner class declaration
class InnerClass
{
public void show()
{
System.out.println("In a nested class method");
}
} Note:
} Static methods are not allowed in nested class.
// main program An inner class implicitly associated with the
class NestedClass object of its outer class. Hence it cannot define
any static method for itself.
{
public static void main(String[] args)
{
OuterClass.InnerClass obj = new OuterClass().new InnerClass();
obj.show();
}
}
// Inner Class Example-2.
class OuterClass
{
void OuterShow()
{
System.out.println("Inside OuterClass Method");
// nested inner class declaration
class InnerClass
{
public void InnerShow()
{
System.out.println("Inside InnerClass Method");
}
// main program
} class NestedClass1
// object declaration of InnerClass {
InnerClass iobj = new InnerClass(); public static void main(String[] args)
iobj.InnerShow(); {
} OuterClass obj = new OuterClass();
} obj.OuterShow();
}
}
// Inner Class Example-3.
class OuterClass
{
final int number = 143;
void OuterShow()
{
System.out.println("Inside OuterClass Method");
// nested inner class declaration
class InnerClass
{
public void InnerShow()
{
System.out.println("Inside InnerClass Method");
System.out.println("The Local Variable 'number' of Outer Class = "
+ number);
}
}
// object declaration of InnerClass
InnerClass iobj = new InnerClass();
iobj.InnerShow();
}
}
// main program
class NestedClass2
{
public static void main(String[] args)
{
OuterClass obj = new OuterClass();
obj.OuterShow();
}
}
Note:
An inner class cannot access the local variable of outer class.
To access those local variables, it must be declared as final.
INHERITANCES
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Java classes can be reused in several ways.
This is basically done by creating a new classes,
reusing the properties of existing ones.
The mechanism of deriving a new class from an
old class is called inheritance.
The old class is called base class or super class or
parent class.
The new class is called sub-class or derived or
child class.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
The inheritance allows sub-classes to inherit all the
variables and methods of their parent classes.
It is of different forms:
i. Single Inheritance (only one super class)
ii. Multiple Inheritance (Several Super Classes)
iii.Hierarchical Inheritance (One Super Class,
many sub-classes)
iv.Multilevel Inheritance (Derived from a derived
class)
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
A A A
B
B C D
B
Hierarchical
Single C
A B
Multilevel
C
3rd Semester B. Tech (CSE) OOP using Java Multiple IGIT, Sarang
Single Inheritance
A new class is derived from one base class
(super class).
Syntax:
class sub_class_name extends super_class_name
{
variable(s) declaration;
method(s) declaration;
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
// single inheritance example
class BOX // base class
{
protected int l , b;
void Assign1( int x, int y )
{
l = x; b = y;
}
int area( )
{
return(l*b);
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
class VOLUME extends BOX // derived class
{
private int h;
void Assign2( int a)
{
h = a;
}
int volume( )
{
return(l*b*h);
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
class single_inheritance
{
public static void main(String args[ ] )
{
VOLUME obj = new VOLUME();
obj.Assign1(5, 10);
obj.Assign2(3);
int r1 = obj.area( );
int r2 = obj.volume();
System.out.print("Area=" + r1 + "Volume =" + r2);
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
// Multilevel inheritance example
class ONE // base class
{
void display( )
{
System.out.println(“Inside class ONE”);
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
class TWO extends ONE // intermediate base class
{
void display( )
{
super.display();
System.out.println(“Inside class TWO”);
}
}
class THREE extends TWO // derived class
{
void display( )
{
super.display();
System.out.println(“Inside class THREE”);
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
class Multuileval
{
public static void main(String args[ ])
{
THREE obj = new THREE( );
obj.display( );
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Output
Inside class ONE
Inside class TWO
Inside class THREE
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
// Hierarchical inheritance example
class ONE // base class
{
void display( )
{
System.out.println(“Inside class ONE”);
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
class TWO extends ONE // derived class
{
void display( )
{
super.display();
System.out.println(“Inside class TWO”);
}
}
class THREE extends ONE // derived class
{
void display( )
{
super.display();
System.out.println(“Inside class THREE”);
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
class Hierarchical
{
public static void main(String args[ ])
{
TWO obj1 = new TWO( );
THREE obj2 = new THREE( );
obj1.display( );
obj2.display( );
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Output
Inside class ONE
Inside class TWO
Inside class ONE
Inside class THREE
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Figure
Rectangle Triangle
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
// Hierarchical Inheritance
class Figure // super class
{
protected float a, b;
Figure ( float x, float y)
{
a = x; b = y;
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
class Rectangle extends Figure
{
Rectangle(float x, float y)
{
super (x,y); }
float area()
{
System.out.println(“Inside Rectangle”);
return(a*b);
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
class Triangle extends Figure
{
Triangle(float x, float y)
{
super (x,y); }
float area()
{
System.out.println(“Inside Triangle”);
return(a*b/2);
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
// main program for calculation of area
class Area_Calculation
{
public static void main(String args[ ])
{
Triangle tobj = new Triangle(6, 12);
Rectangle robj = new Rectangle(9, 15);
System.out.println(“Area =“ + tobj.area());
System.out.println(“Area =“ + robj.area());
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Output
Inside Triangle
Area = 36.000000
Inside Rectangle
Area = 135.000000
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Method Overriding
If a method in a sub-class has the same
name and signature as a method in its
super class, then the method in the
sub-class is said to be override the
method in super-class.
The overridden method is called from a
sub-class always.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
The method of sub-class always overrides the
method of super-class if both the methods are
having same name and signature.
To avoid such situation the keyword super is
used.
This super keyword can invoke method of
super-class.
The statement becomes 1st statement in the
method of sub-class.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
// using overridden method
class A
{
int i, j;
void Assign1( int x, int y )
{
i = x; j = y;
}
void show( )
{
System.out.println(" I =" + i + " J =" + j );
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
class B extends A
{
int k;
void Assign2(int d )
{
k = d;
}
void show( )
{
System.out.println(" " K =" + k );
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
class override
{
public static void main(String args[ ])
{
B obj = new B( );
obj.Assign1(12,5);
obj.Assign2(7);
obj.show( );
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Output:
K=7
Because the sub-class method show()
overrides the method show() in super-class
which has same name and signature.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
// using without-overridden method
class A
{
int i, j;
void Assign1( int x, int y )
{
i = x; j = y;
}
void show( )
{
System.out.println(" I =" + i + " J =" + j );
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
class B extends A
{
int k;
void Assign2(int d )
{
k = d; }
void show( )
{
super.show( );
System.out.println( " K =" + k );
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
class without_override
{
public static void main(String args[ ])
{
B obj = new B( );
obj.Assign1(12,5);
obj.Assign2(7);
obj.show( );
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Output:
I = 12 J = 5
K=7
When obj invokes show( ) method it finds of
invoking method show( ) of super-class. Here no
overriding of methods.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Sub-class Constructor
It is used to construct the instance
variables of both the sub-class and the
super-class.
The sub-class constructor uses the
keyword super to invoke the constructor
method of super-class.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
The keyword super has some limitations:
i.It is only used in sub-class constructor
method.
ii.It must appear as the first statement with in
the sub-class constructor.
iii.The parameters or arguments of super( )
must match the order and type of the instance
variable declared in the super-class.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
// single inheritance and constructor example
class BOX // base class
{
protected int l , b;
// parameterized constructor in base class
BOX( int x, int y)
{
l = x; b = y;
}
int area( )
{
return(l*b);
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
class VOLUME extends BOX // derived class
{
private int h;
// parameterized constructor in derived class
VOLUME( int a, int b, int c)
{
super(a, b); // to invoke the constructor of super class
h = c;
}
int volume( )
{
return( l*b*h);
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
class single_constructor
{
public static void main(String args[ ] )
{
VOLUME obj = new VOLUME(5, 10, 2);
int r1 = obj.area( );
int r2 = obj.volume();
System.out.print("Area=" + r1 + "Volume =" + r2);
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
final
All methods and variables can be overridden by default in
sub-class. If we wish to prevent the sub-classes from
overriding the members of the super class, declare them by
using the keyword final.
The final has the following advantages:
i. It is used to create the equivalent of a named constant.
ii. To prevent method overriding in inheritance.
iii. To prevent inheritance.
The final keyword used in:
variable, method, and class
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Final Variables
A variable can be declared as final.
It prevents from modification of contents.
To declare a variable with some initial value with the
keyword final now acts as a constant ( similar to const in C/
C++ ).
Syntax: final data_type <variable_name> = value;
Example: final int a = 5;
final float PI = 3.142f;
Variable with final declaration does not occupy memory
because it becomes a constant.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Final Methods
To prevent method overriding, then the
method must be declared as final.
Syntax:
final return_type method_name (Argument(s),if any)
{
// statement(s);
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Example: class xyz
{
final void display( )
{
System.out.println(“ I Am in Super-Class”);
} }
class pqr extends xyz
{
void display( )
{
System.out.println(“ I Am in Derived-Class”);
}}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Because display() is declared as final.
It cannot be overridden in pqr. If you
do so, then a compile-time error
results.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
final class
To prevent a class from being inherited.
To do so, precede the keyword final
before class name.
A class cannot be sub-classed further is
called final class.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Syntax: Example:
final class class_name final class A
{ {
// statement(s); // statement(s);
} }
class B extends A
{
// statement(s);
}
Illegal operation since A is declared as final. So it
cannot be inherited to B.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Dynamic Method Dispatch
It is known as run-time polymorphism in JAVA.
It is the mechanism by which a call to an
overridden method is resolved at run-time rather
than compile-time.
It is the type of object being referred to that
determines which version of an overridden method
will be executed.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Example
class ONE
{
void display( )
{
System.out.println( “Inside class ONE”);
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
class TWO extends ONE
{ void display( )
{
System.out.println(“Inside class TWO”);
}
}
class THREE extends TWO
{ void display( )
{
System.out.println(“Inside class THREE”);
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
class Dispatch
{ public static void main(String args[ ])
{
ONE ref; // reference type of ONE kind
ONE obj1 = new ONE( );
TWO obj2 = new TWO( );
THREE obj3 = new THREE( );
ref = obj1; ref.display( );
ref = obj2; ref.display( );
ref = obj2; ref.display( );
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Output
Inside class ONE
Inside class TWO
Inside class THREE
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
// Using Dynamic Dispatch
class Figure // super class
{
protected float a, b;
void Figure ( float x, float y)
{
a = x; b = y;
}
float area()
{
System.out.println(“Area of figure not Defined”);
return(0);
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
class Triangle extends Figure
{
void Triangle(float x, float y)
{
super (x,y);
}
float area()
{
System.out.println(“Inside Triangle”);
return(a*b/2);
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
class Rectangle extends Figure
{
void Rectangle(float x, float y)
{
super (x, y);
}
float area()
{
System.out.println(“Inside Rectangle”);
return(a*b);
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
// main program for calculation of areas
class Area_Calculation
{
public static void main(String args[ ])
{
Figure ref;
Figure fobj = new Figure(4,2);
Triangle tobj = new Triangle(6,12);
Rectangle robj = new Rectangle(9,15);
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
ref = fobj;
System.out.println(“Area =“ + ref.area());
ref = tobj;
System.out.println(“Area =“ + ref.area());
ref = robj;
System.out.println(“Area =“ + ref.area());
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Output
Area of figure not Defined
Area = 0
Inside Triangle
Area = 36.000000
Inside Rectangle
Area = 135.000000
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Interfaces
Java does not support multiple inheritance i.e.
classes in Java cannot have more than one super-
class.
i.e. class name1 extends name2 extends ……
{
// statement(s);
} is invalid.
An alternative of multiple inheritance is called
interfaces, which supports the concept of multiple
inheritance.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Defining Interfaces
It is also a class kind.
It also contains variables and methods.
The method should not contain any code.
Only methods prototype or declaration must
be included.
The variables must contain a constant
value.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Syntax of variable declaration in Interfaces
final static data_type variable_name = value;
Example:
final static float PI = 3.142f;
final static int area = 10;
Note : All variables of interface are final and
static kind.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Syntax of method declaration in Interfaces
return_type method_name (parameter(s) list,
if any);
Examples: void display( );
int result( );
double maximum(double x, double y);
int sum(int, int, int);
Note: A method contain only the declaration
without having body inside the interface.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Example-1:
interface area
{
final static int l = 10, b = 5;
void display( );
}
The class which implements the above
interface area must define the code for the
method display( ).
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Example-2:
interface circle
{
final static float PI = 3.142f;
float area(float x, float y);
void display( );
}
The above interface has 2 methods area( )
and display( ), whose codes must be defined
in the class where it implements.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Implementation of Interfaces
Interfaces are used as super-class whose
properties are inherited by classes. So it is
necessary to create a class that inherits the
given interfaces.
Syntax:
class class_name implements interface_name
{
// statement(s);
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Example: interface AREA
{
final static float PI = 3.142f;
float result(float a, float b);
}
class rectangle implements AREA
{
public float result(float a, float b)
{
return(a*b);
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
class circle implements AREA
{
public float result( float x, float y)
{
return(PI* x * x);
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
class INTERFACE
{
public static void main(String args[ ])
{
rectangle robj = new rectangle( );
circle cobj = new circle( );
float r1 = robj.result(5, 15);
float r2 = cobj.result(10, 0);
System.out.println(“Area of Rectangle = “ + r1);
System.out.println(“Area of Circle = “ + r2);
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Extending Interfaces
Like class, interfaces can also be extended, i.e.
interfaces can be sub-interfaced from other
interfaces. The new sub-interface inherits all the
members of the super-interface similar to sub-
classes.
Syntax:
interface interface_name extends interface_name
{
// statement(s);
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Example:
interface product
{
final static int code = 786;
final static String name = “COMPUTER”;
}
interface details extends product
{
void output( );
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
class product_list implements details
{
public void output()
{
System.out.println(“….Computer Details….”);
System.out.println(“Code = “+ code);
System.out.println(“Product Name = “+ name);
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
class main_program
{
public static void main(String args[ ])
{
product_list obj = new product_list( );
obj.output();
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Here, product is the super-interface
which has variables code and name.
detail is the sub-interface which has
one member method called output( ).
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
// Example of extending interface
interface ONE
{
voidA();
void B();
}
interface TWO extends ONE
{
void C();
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
// class implements all methods of interface ONE and TWO
class myclass implements TWO
{
public void A()
{
System.out.println("Implementing method A()");
}
public void B()
{
System.out.println("Implementing method B()");
}
public void C()
{
System.out.println("Implementing method C()");
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
// main program
class interface_extends
{
public static void main(String args[ ])
{
myclass obj = new myclass( );
obj.A();
obj.B();
obj.C();
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
// multiple inheritance by interface
interface Animal
{
void moves(); // by default every
} // method of interface is
//public and abstract
interface Bird
{
void fly();
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
class multiple_inheritance implements
Animal, Bird
{
public void moves()
{
System.out.println(“Animals move on land”);
}
public void fly()
{
System.out.println(“Birds fly in air”);
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
public static void main (String args[ ])
{
multiple_inheritance obj = new
multiple_inheritance( );
obj.moves();
obj.fly();
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
interface Plane
Abstract method Engine_Number( )
implements implements
class Model1 class Model2
Implementation of Implementation of
Engine_Number( ) Engine_Number( )
Object1 Object2
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
// implementing interface in 2 classes
interface Plane
{
int Engine_number();
}
class Model1 implements Plane
{
public int Engine_number()
{
return 5; }
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
class Model2 implements Plane
{
public int Engine_Number()
{
return 10; }
}
class interface_plane // main program
{
public static void main(String args[ ])
{
Model1 obj1 = new Model1();
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Model2 obj2 = new Model2();
int a = obj1.Engine_Number();
System.out.println(“No. of Engines in
Model1=“+ a);
a = obj2.Engine_Number();
System.out.println(“No. of Engines in
Model2=“+ a);
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Question:
Define an interface called Numbers, which has two
variables with values 5 and 10. Define another
interface called Results which inherits from super
interface Numbers, which contains three methods
ShowNumbers( ), Sum( ), and Product( ).
Define a class called NumberResults which
implements the sub-interface Results. Write the
complete program.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Interface Numbers
extends
Interface Results
implements
Class NumbersResults
Object
Creation
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
String class
Objects of String class are immutable i.e. its contents
cannot be modified.
Hence no methods are available in String class.
Examples of classes of objects of immutable kind are:
Character, Byte, Integer, Float, Double,
Long etc. – wrapper classes
Class
BigInteger, BigDecimal etc.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Example:
String a = new String (“Hello”);
String b = new String (“Java”);
String c = a+b;
System.out.print(c); Output: HelloJava
a.append(b); is a invalid statement since object “a” and
object “b” immutable kind. Hence it is a compile- time
error.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
StringBuffer class
Objects of StringBuffer class are mutable i.e. its contents can be
modified.
The modification of contents of the objects are done by using its
available methods.
It is synchronized by default.
Several threads process on a StringBuffer class object one after
another.
Synchronizing the object is like locking the object when a thread
acts on the object, it is locked and any other thread should wait till
the current thread completes and unlocks the object.
Synchronization does not allow more than one thread to act
simultaneously.
It takes more execution time.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Examples:
• StringBuffer a = new StringBuffer(“Hello”);
• StringBuffer b = new StringBuffer();
The StringBuffer object b as an empty one having a default capacity
of 16 characters.
• StringBuffer c = new StringBuffer(20);
The StringBuffer object c as an empty one having a capacity of
storing 20 characters. More than 20 characters can be assigned since
it is a mutable kind of object.
• a.append(“Java”);
System.out.print(a); Output: HelloJava
Now “Java” is appened to “Hello” in object “a” since object “a” is a
mutable one.
• b.append(“Java”);
System.out.print(b); Output: Java
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
StringBuilder class
Added in jdk1.5.
Objects of StringBuilder class are mutable i.e. its
contents can be modified.
The modification of contents of the objects are done by
using its available methods.
It is unshynchronized.
Several threads process on a StringBuilder object
simultaneosly.
It may lead to inaccurate result in some cases.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Examples:
i. StringBuilder a = new StringBuilder(“Hello”);
ii. StringBuilder b = new StringBuilder();
The StringBuilder object b as an empty one having a default capacity
of 16 characters.
iii. StringBuilder c = new StringBuilder(20);
The StringBuilder object c as an empty one having a capacity of
storing 20 characters. More than 20 characters can be assigned
since it is a mutable kind of object.
a.append(“Java”);
System.out.print(a); Output: HelloJava
The StringBuilder object “a” is of mutable kind. Hence string literal
“Java” is appened with object “a”.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
length( ) : To find the length of a string.
Syntax: int string.length( )
Here string is an object or string literals.
Examples:
i. int a = “Hello”.length( );
ii. String st = “Java String”;
int len = st.length( );
iii.String ab = “I.G.I.T”;
System.out.print(ab.length( ));
iv. char z[ ] = {'H','E','L','L','O'};
String m = new String(z);
System.out.print(“Length=“+ m.length( ));
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
concat( ): To concatenate two strings.
Syntax: String string1.concat(string2)
Example:
String a = “I Like”;
String b = “India”;
System.out.print(a+”\n“+b);
String c = a.concat(b);
System.out.print(a+”\n“+b+”\n”+c);
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
toUpperCase(): To change a string or character to
uppercase..
Syntax: String string. toUpperCase( )
Examples:
i. String a = “Hello”. toUpperCase( );
System.out.print(a);
ii. String b = “hello”;
String c = b. toUpperCase( );
System.out.print(c);
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
toLowerCase( ): To change a string or character to
lowercase.
Syntax: String string.toLowerCase( )
Examples:
i. String a = “HELLO”.toLowerCase( );
System.out.print(a);
ii. String b = “HellO”;
String c = b.toLowerCase( );
System.out.print(c);
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
charAt(): To pick a particular positioned
character from a string.
Syntax: char string.charAt(int position)
Example:
i. char a = “I.G.I.T”.charAt(2);
System.out.print(a);
ii. String st = “Java Programming”;
char b = st.charAt(6);
System.out.print(b + “ “ + st.charAt(0));
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
substring(n, m): To retrieve a substring from nth character
to m characters.
Syntax:
String string.substring(int position, int noc)
Here noc: number of characters.
Examples:
i. String a = “TECHNOLOGY”.substring(5, 9);
System.out.print(a);
ii. String d = “Talcher”;
String a =d.substring(4, 6);
System.out.print(a);
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
substring(n): To retrieve a substring from nth
character to end of the string.
Syntax: String string.substring(int position)
Examples:
i. String a = “TECHNOLOGY”.substring(5);
System.out.print(a);
ii. String d = “RAILWAY”;
String a =d.substring(4);
System.out.print(a);
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
replace(): It replaces all occurrences of one
character in a string with the specified character.
Syntax: String string.replace(char ac, char rc)
Here ac: actual character.
rc: replacement character.
Examples:
i. String a = “INDIAN”.replace('I', '?');
System.out.print(a);
ii. String b =“INDIAN”;
String c = b.replace('I', '*');
System.out.print(c);
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
equals(): It checks for two strings are same or not, and
returns a boolean value true or false.
Syntax: boolean string1.equals(string2)
Example:
String s1 = “Java”, s2 = “JAVA”;
boolean b = s1.equals(s2);
if (b==true)
System.out.print(“Equal”);
else
System.out.print(“Not Equal”);
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
equalsIgnoreCase(): It checks for two strings are same
or not by ignoring its cases, and returns a boolean value
true or false.
Syntax: boolean string1.equalsIgnoreCase(string2)
Example:
String s1 = “Java”, s2 = “JAVA”;
boolean b = s1.equalsIgnoreCase (s2);
if(b==true)
System.out.print(“Equal”);
else
System.out.print(“Not Equal”);
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
compareTo( ): Compares 2 strings and returns an
integer value.
Syntax: int string1.compareTo(string2)
if string1 > string2 then a +ve value returns.
if string1 < string2 then a -ve value returns.
if string1 = string2 then a zero value returns.
Example:
String a = “Cool”, b = “Don”;
int t = a.compareTo(b);
if( t > 0 ) System.out.print(“Bigger=“ + a);
if( t < 0 ) System.out.print(“Bigger=“ + b);
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
String a = “India”, b = “India”;
If(a==b) System.out.print(“Same”);
else System.out.print(“Not”);
a 100
India Output: Same
b 100 100
String p = “Java”, q = new String(“Java”);
If(p==q) System.out.print(“Same”);
else System.out.print(“Not”); Output: Not
p 200 Java q 300 Java
200 300
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
String Tokenizer or Tokenizing a String
The split() method in the String class is specifically for
splitting a string into tokens.
It returns all the tokens from a string as an array of
String objects.
It passes two arguments.
Syntax:
String[] object = StringObject.split(“[delimiters]”, LimitValue);
LimitValue: 0 or -1
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Example-1:
class StringTokenizing
{
public static void main(String[] args)
{
String text = "To be or not to be, that is the question.";
// Delimiters are comma, space, and period
String delimiters = "[, .]";
String[] tokens = text.split(delimiters, 0);
System.out.println("Number of tokens: " + tokens.length);
for(String token : tokens)
System.out.println(token);
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Example-2:
class StringTokenizing1
{
public static void main(String[] args)
{
String text = "To be or not to be, that is the question.";
// Delimiters are comma, space, and period
String delimiters = "[, .]";
String[] tokens = text.split(delimiters, -1);
System.out.println("Number of tokens: " + tokens.length);
for(String token : tokens)
System.out.println(token);
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Extra blank line at the end
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Example-3:
class StringTokenizing2
{
public static void main(String[] args)
{
String text = "To be or not to be, that is the question.";
String delimiters = "[abt]"; // Delimiters are a, b, and t
String[] tokens = text.split(delimiters, 0);
System.out.println("Number of tokens: " + tokens.length);
for(String token : tokens)
System.out.println(token);
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Wrapper Classes
A wrapper class a class whose object wraps or contains a
primitive data type. After creation of an object to a
wrapper class, it contains a field where the primitive
data stores.
In other words, we can wrap a primitive data into a
wrapper class object.
Primitive Data or Value
Wrapper Class Object
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Example:
If we create an object to Character wrapper class, it
contains a single field char and which can store a
primitive character data say 'A'.
So, Character is a wrapper class of char data type.
A
char
Character Object
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
List of wrapper classes defined in java.lang package.
It coverts the primitive data types into object form.
Primitive Data Types Wrapper Classes
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Number Class
It is an abstract class whose sub-class are Byte, Short,
Integer, Long, Float, and Double.
Number Class Methods Purpose
byte byteValue() It converts byte object into byte value.
short shortValue() It converts byte object into short value.
int intValue() It converts byte object into int value.
long longValue() It converts byte object into long value.
float floatValue() It converts byte object into float value.
double doubleValue() It converts byte object into double value.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Character Class
It wraps a value of the primitive type char in an object.
Character class has only one constructor which accepts
primitive data type.
Syntax: Character (char value)
Example: Character obj = new Character ('A');
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Character Class Methods Purpose
It compares two Character
int Charater_Object.compareTo(Character objects for equal or greater
Object) than or less than, and returns
an integer value.
It converts Character object
String toString() into String object and returns
that String object.
It converts a single character
static Character valueOf(char variable) variable to Character object
and return that object.
It returns a true value if the
static boolean isDigit(char variable) character is a digit; otherwise
returns a false value.
It returns a true value if the
static boolean isLetter(char variable) character is an alphabet;
otherwise returns a false value.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Character Class Methods Purpose
It returns a true value if the character is an
static boolean isUpperCase(char
uppercase alphabet; otherwise returns a
variable) false value.
It returns a true value if the character is a
static boolean isLowerCase(char
lowercase alphabet; otherwise returns a
variable) false value.
static boolean isSpaceChar(char It returns a true value if the character is a
variable) space; otherwise returns a false value.
It returns a true value if the character is a
static boolean isWhiteSpace(char white space character (tab key, enter key,
variable) or backspace key); otherwise returns a
false value.
It returns a true value if the character is
static boolean isLetterOrDigit(char
either an alphabet or a digit; otherwise
variable) returns a false value.
It converts the character into uppercase
static char toUpperCase(char variable)
and returns the uppercase character.
It converts the character into lowercase
static char toLowerCase(char variable)
and returns the lowercase character.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Byte Class
It wraps a value of the primitive type byte in an object.
It has two constructors.
Syntax of 1st constructor: Byte(byte value)
Example: Byte obj = new Byte(786);
Syntax of 2nd constructor: Byte(String object)
Example: Byte obj = new Byte(“786”);
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Byte Class Methods Purpose
It compares two Byte
objects for equal or greater
int byte_object.compareTo(Byte object)
than or less than, and
returns an integer value.
It returns the primitive
static byte parseByte(String object) byte number contained in
the String object.
It converts a Byte object
String toString()
into String object.
It converts a String object
static Byte valueOf(String object) that contain byte value into
Byte class object.
It converts the primitive
static Byte valueOf(byte variable) byte data into Byte class
object.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Short Class
It wraps a value of the primitive type short in an object of
Short class kind.
It has two constructors.
Syntax of 1st constructor: Short(short value)
Example: Short obj = new Short(7860);
Syntax of 2nd constructor: Short(String object)
Example: Short obj = new Short(“7860”);
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Short Class Methods Purpose
It compares two numerical
values of Short class objects
int ShortObject1.compareTo(ShortObject2)
and returns 0, -ve value or +ve
value.
It compares two Short class
boolean ShortObject1.equals(ShortObject2) objects. If same then returns
true; otherwise false.
It returns the short value of the
static short parseShort(String Object) string object contains short
value.
It converts Short class object
String ShortObject.toString() into String object and returns
that String object.
It converts a string object of
Static Short valueOf(String object) short value to Short class
object and return that object.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Integer Class
It wraps a value of the primitive type int in an object of
Integer class kind.
It has two constructors.
Syntax of 1st constructor: Integer(int value)
Example: Integer obj = new Integer(78607);
Syntax of 2nd constructor: Integer(String object)
Example: Integer obj = new Integer(“78607”);
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Integer Class Methods Purpose
It compares two numerical
values of Integer class objects
int IntegerObject1.compareTo(IntegerObject2)
and returns 0, -ve value or +ve
value.
It compares two Integer class
boolean IntegerObject1.equals(IntegerObject2) objects. If same then returns
true; otherwise false.
It returns the int value of the
static int parseInt(String Object) string object contains int
value.
It converts Integer class object
String IntegerObject.toString() into String object and returns
that String object.
It converts a string object of
static Integer valueOf(String object) int value to Integer class
object and return that object.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Integer Class Methods Purpose
It converts the Integer class object to
int IntegerObject.intValue() primitive int data type.
It converts a decimal integer to its
static String toBinaryString(int) equivalent binary number and returns as
String kind.
It converts a decimal integer to its
static String toOctalString(int) equivalent octal number and returns as
String kind.
It converts a decimal integer to its
static String toHexaString(int) equivalent hexadecimal number and
returns as String kind.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Long Class
It wraps a value of the primitive type long in an object of
Long class kind.
It has two constructors.
Syntax of 1st constructor: Long(long value)
Example: Long obj = new Long(12345678);
Syntax of 2nd constructor: Long(String object)
Example: Long obj = new Long(“12345678”);
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Long Class Methods Purpose
It compares two numerical
values of Long class objects
int LongObject1.compareTo(LongObject2)
and returns 0, -ve value or +ve
value.
It compares two Long class
boolean LongObject1.equals(LongObject2) objects. If same then returns
true; otherwise false.
It returns the long value of the
static long parseLong(String Object) string object contains long
value.
It converts Long class object
String LongObject.toString() into String object and returns
that String object.
It converts a string object of
static Long valueOf(String object) long value to Long class
object and return that object.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Float Class
It wraps a value of the primitive type float in an object of
Float class kind.
It has three constructors.
Syntax of 1st constructor: Float(float value)
Example: Float obj = new Float(12.345f);
Syntax of 2nd constructor: Float(double value)
Example: Float obj = new Float(12.345);
Syntax of 3rd constructor: Long(String object)
Example: Long obj = new Long(“12.345”);
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Float Class Methods Purpose
It compares two numerical
values of Float class objects
int FloatObject1.compareTo(FloatObject2)
and returns 0, -ve value or +ve
value.
It compares two Float class
boolean FloatObject1.equals(FloatObject2) objects. If same then returns
true; otherwise false.
It returns the float value of the
static float parseFloat(String Object) string object contains float
value.
It converts Float class object
String FloatObject.toString() into String object and returns
that String object.
It converts a string object of
static Float valueOf(String object) float value to Float class
object and return that object.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Double Class
It wraps a value of the primitive type double in an object
of Double class kind.
It has two constructors.
Syntax of 1st constructor: Double(double value)
Example: Double obj = new Double(12.3456);
Syntax of 2nd constructor: Double(String object)
Example: Double obj = new Double(“12.3456”);
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Double Class Methods Purpose
It compares two numerical
values of Double class objects
int DoubleObject1.compareTo(DoubleObject2)
and returns 0, -ve value or +ve
value.
It compares two Double class
boolean DoubleObject1.equals(DoubleObject2) objects. If same then returns
true; otherwise false.
It returns the double value of
static double parseDouble(String Object) the string object contains
double value.
It converts Double class object
String DoubleObject.toString() into String object and returns
that String object.
It converts a string object of
static Double valueOf(String object) double value to Double class
object and return that object.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Boolean Class
It wraps a value of the primitive type boolean in an
object of Boolean class kind.
It has two constructors.
Syntax of 1st constructor: Boolean(boolean value)
Example: Boolean obj = new Boolean(true);
Syntax of 2nd constructor: Boolean(String object)
Example: Boolean obj = new Boolean(“true”);
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Boolean Class Methods Purpose
It compares two boolean
values of Boolean class
int BooleanObject1.compareTo(BooleanObject2)
objects and returns 0, -ve
value or +ve value.
It compares two Boolean
boolean BooleanObject1.equals(BooleanObject2) class objects. If same then
returns true; otherwise false.
It returns the boolean value
static boolean parseBoolean(String Object) of the string object contains
boolean value.
It converts Boolean class
String BooleanObject.toString() object into String object and
returns that String object.
It converts a string object of
boolean value to Boolean
static Boolean valueOf(String object) class object and return that
object.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Autoboxing
Conversions from a primitive type to the corresponding
class type are called boxing conversions, and automatic
conversions of this kind are described as autoboxing.
Syntax:
ClassName ObjectRef = Primitive data/variable/expression;
Examples:
Integer obj1 = 15;
int a=10;
Integer obj2 = a;
Integer obj3 = a +15;
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Unboxing
To convert from class type to a primitive data type
automatically, is called as unboxing.
Syntax: PrimitiveDataType Variable = ObjectReference;
Examples:
int num1 = obj1;
int num2 = obj2;
int num3 = obj3;
Here obj1, obj2, and obj3 are of Integer class kind.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Autoboxing and Unboxing Example-1:
class box_unbox
{
public static void main(String args[])
{
// Autoboxing, which changes from primitive integer to
// integer object
Integer a=17;
// Unboxing, which changes from integer object to integer
int b=a;
// int b=a.intValue();
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Double dobj = 6.78; // Autoboxing
double d=dobj; // Unboxing
System.out.println("Integer Object a="+a);
System.out.println("Integer Variable b="+b);
System.out.println("Double Object a="+dobj);
System.out.println("Double Variable d="+d);
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Output
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Autoboxing and Unboxing Example-2:
class Autoboxing
{
public static void main(String []args)
{
int num[] = { 3, 97, 55, 22, 12345 };
// Array to store Integer objects
Integer obj[] = new Integer[num.length];
// Call function to cause boxing conversions
for(int i = 0 ; i<num.length ; i++)
{
obj[i] = Boxing(num[i]);
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
// Call function to cause unboxing conversions
for(Integer Object : obj)
{
Unboxing(Object);
}
}
// Function to cause boxing conversion
public static Integer Boxing(Integer Iobj)
{
return Iobj;
}
// Method to cause unboxing conversion
public static void Unboxing(int n)
{
System.out.println("Integer Value = " + n);
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Output
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Abstract Class
It is a class that contains zero or more abstract methods.
Syntax:
abstract class className
{
// declaration of abstract method(s)
}
Abstract Method
It is a method without method body. Its definition is to be given in the
class where the abstract class is extended its features.
Syntax:
abstract class className
{
abstract returnType methodName (Declaration of argument(s) if
any);
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
// abstract class example
abstract class AbstractClass
{
// abstract method
abstract void Calculate(double a);
}
class Square extends AbstractClass
{
void Calculate(double a)
{
System.out.println("Square of " + a + " = " + (a*a));
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
class SquareRoot extends AbstractClass
{
void Calculate(double a)
{
System.out.println("Square Root of " + a + " = " + Math.sqrt(a));
}
}
class Cube extends AbstractClass
{
void Calculate(double a)
{
System.out.println("Cube of " + a + " = " + (a*a*a));
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
// main class
class DifferentCalculations
{
public static void main (String args[])
{
Square s = new Square();
SquareRoot sr = new SquareRoot();
Cube c = new Cube();
s.Calculate(12);
sr.Calculate(625);
c.Calculate(3);
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Output
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Abstract Classes Vs. Interfaces
1. It is written when there is some 1. It is written when all the features are
common features shared by all the implemented differently by all the objects.
objects.
2. The programmer leaves the
2. It is the duty of the programmer to
implementation part to the third party
provide sub-classes to it.
vendor.
3. It contains both abstract methods and
3. It only contains abstract methods.
concrete methods.
4. It only contains instance variables. 4. It cannot contains instance variables.
5. All the abstract methods should be 5. All the abstract methods should be
implemented in its sub-classes. implemented in its implementation classes.
6. A class is declared with the keyword 6. It is declared by using the keyword
abstract. interface in place of class.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
abstract class WholeSale1
{
void TextBooks( ) // concrete method
{
// text books of xth class
}
abstract void Stationery( ); // pen or papers or note books
}
interface WholeSale2
{
// text books of xth, ixth, viiith class
abstract void TextBooks( );
// pen or papers or note books
abstract void Stationery( );
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Let us consider Retailer1 and Retailer2 are two classes represented
by two retail shops.
When Retailer1 wants text books of xth class and some pens.
Similarly, Retailer2 also wants text books of xth class and some
papers. Then such cases, we require an abstract class WholeSale1 with
method TextBooks( ) as concrete and method Stationery( ) as abstract
kind, since the stationeries asked by the retailers is different.
Suppose, Retailer1 asks for viiith class text books and Retailer2 asks
for xth books. Such cases different text books by different retailers. So
the TextBooks( ) method must be declared as abstract class whose
implementation is done in the respective Retailer class according to
their requirements. Here both methods TextBooks( ) and Stationery( )
are abstract kind. So the class must be an interface. Here the interface
is WholeSale2.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
WholeSale1 as abstract class
TextBooks( ) method for xth Stationery( ) method for pens
class. or papers or note books.
Retailer1 Retailer2
Implementation of Stationery( ) Implementation of Stationery( )
method for pens. method for papers.
Object1 Object2
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
WholeSale2 as interface
TextBooks( ) method for xth Stationery( ) method for pens
or ixth or viiith class. or papers or note books.
Retailer1 Retailer2
Implementation Implementation Implementation Implement
of TextBooks( ) of Stationery( ) of TextBooks( ) Stationery( )
method for method for method for xth method for
viiith class. pens. class. papers.
Object1 Object2
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Packages
• Encapsulation is a technique in OOP language by which
multiple related objects can be grouped under one object.
• Java implements encapsulation by the use of packages.
• A package is a collection of related classes and interfaces.
• It checks two things:
Reduce problems in name conflicts.
Control the visibility of classes, interfaces, methods, and
data defined within them.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Reusability of Codes
•Generally reusability of code in a program by
extending the classes and implementing the
interfaces (Physically Copying).
•To use classes from other programs without
physically copying them into the program. This
can be achieved in Java by using packages.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
JAVA PACKAGES
JAVAAPI PACKAGES USER-DEFINED PACKAGES
(Application Programming Packages)
i. java.lang: Language support classes which contains
primitive data types, strings, math functions, threads and
exceptions.
ii.java.io: Input/Output support classes which includes
operation for input and output of data.
iii.java.util: Language utility classes and interfaces which
contains vectors, random numbers, date, hash tables etc.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
JAVA PACKAGES
JAVAAPI PACKAGES USER-DEFINED PACKAGES
(Application Programming Packages)
iv.java.awt: awt means abstract window toolkit. Contains
graphical user interface (GUI) classes includes classes for
windows, buttons, lists, menus, etc.
v.java.net: Classes for networking which include classes
for communicating with local computers and internet
servers.
vi.java.applet: Classes for creation and implementation of
applets.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
JAVA PACKAGES
JAVAAPI PACKAGES USER-DEFINED PACKAGES
(Application Programming Packages)
vii.javax.swing: x means extended. It is the extended
package of java.awt.
viii.java.text: It has classes DateFormat to format dates
and times, and NumberFormat to format numeric values .
ix.java.sql: It helps to connect databases like Oracle or
Sybase and retrieve data from it.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Java Package is a Directory
java directory
java.io io sub-directory
java.lang lang sub-directory
java.awt iwt sub-directory
java.awt.event event sub-directory
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
• To access Image class, the statement is java.awt.Image.
•To import in the program, it must appear at the top of the
program before any class declaration. So, the statement is:
• import java.awt.Image;
•After it in the program any method belonging to Image
class can be included directly by using
Image.method_name( );
•The statement import java.awt.*; means inclusion of all
classes of the package awt.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Package containing awt package
java
awt
Color
Graphics
Font
Image
awt package containing classes
Classes containing methods
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
double res = java.lang.Math.sqrt(n);
Package Method
Class
name name
name
The above statement can also be written as:
import java.lang.Math; // import java.lang.*;
double res = Math.sqrt(n);
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
USER-DEFINED PACKAGES
Syntax: package package_name; //package declaration
public class class_name
{
// method(s) declarations;
}
Example: package mypackage;
public class myclass
{
public void display( )
{
System.out.println(“ My Package”);
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
In the above package mypackage contains only one class
called myclass which must be public kind.
The file name for saving must be the class name which is of
public kind.
Steps to follow for saving and compile a package:
• For the above example, the name of the file will be
myclass.java.
• Then compile by using this javac –d . Myclass.java
•If no error then myclass.class will be created and saved
under the package name as directory (here it is mypackage).
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
ACCESSING PACKAGE IN THE
MAIN PROGRAM
In main program a package can be imported in
this way:
import package_name.class_name;
OR
import package_name.*;
For the above package example:
import mypackage.myclass;
// import mypackage.*;
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Note:
•If more than one classes are added in a package at a
time, one class must be public. Remaining classes
are declared as non-public kind.
•Save the program as public class name and store
under the package ( i.e. the sub-directory).
• After compilation it creates all classes class files.
•While importing the package in a program only
public class can access outside but not accessing
non-public class.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
ACCESSING ALL CLASSES OF A
PACKAGE IN A PROGRAM
•Declare at a time one class which must be public
kind.
•To add one more class into the existing package,
again declare a class of public kind and add to the
sub-directory which is the package name.
• Then compile to create the class file.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
ADDING CLASSES TO AN EXISTING
PACKAGE
• Let us consider a package page with class AA:
package page;
public class AA
{
--------;
--------;
}
• Save as AA.java under the sub-directory called
page (the package name).
• Then compile to get its class file as AA.class.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
• To add another class called BB into the package
page, then do the following:
package page;
public class BB
{
--------;
--------;
}
• Save as BB.java under the sub-directory called
page (the package name). Then compile to get its
class file as BB.class.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
ADDING A PACKAGE IN AN EXISTING
PACKAGE
Syntax:
package old_package_name.new_package_name;
Example: package mypackage.pack1;
Here mypackage is the existing one.
A new package called pack1 is added in the above
package and made as sub-package.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Interfaces in Package
• It is also possible to write interfaces in a package.
•The implementation classes must be defined in the
package itself. Since the interface cannot create object.
Example:
// Create an interface dateDisplay in the package called pack
package pack;
public interface dateDisplay
{
void showDate();
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
// Create a class called dateImplement as implementation class of
// interface dateDisplay in the same package pack
package pack;
import pack.dateDisplay;
import java.util.*;
public class dateImplement implements dateDisplay
{
public void showDate()
{
// default the object dd assigns with system date and time
Date dd = new Date();
System.out.print("The Current Date and Time = " + dd);
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
// Write a program which uses implementation class
// dateImplement as for displaying date.
import pack.dateImplement;
class dateProgram
{
public static void main(String args[])
{
dateImplement obj = new dateImplement();
obj.showDate();
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
How to call garbage collector?
Ans: To call garbage collector of JVM for deletion of
unused variables and unreferenced objects from memory
using gc( ) method. This method is present in both
runtime and system classes of java.lang package.
So garbage collector can be called as:
System.gc( );
Or
Runtime.getRuntime( ).gc( );
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Exception Handling
A wrong is known as exception.
An exception may produce an incorrect
output or may terminate the execution of the
program abruptly or even causes the system
to crash.
There are two types of errors:
• Compile-time errors
• Run-time errors
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Compile Time Error
All syntax errors are detected and displayed by the java
compiler known as compile-time errors.
Some of the compile-time errors are:
(i) Semicolon missing.
(ii) Misspelling of identifiers and keywords.
(iii) Missing of brackets in classes and methods.
(iv) Missing of double quotes in string.
(v) Use of undeclared variables.
(vi) Wrong initialization.
(vii) Bad references to objects.
(viii) Use of = in place of == operator.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Example:
class ErrorProgram
{
public static void main(String args[ ])
{
System.out.println(“Java Program”)
}
}
ErrorProgram.Java: 5 : ; expected
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Run-Time Error
Sometimes a program compiles successfully but may not
run properly. This program gives wrong result due to wrong
logic or may terminate due to errors such as stack overflow.
Most common run-time errors are:
(i) Dividing by 0.
(ii)Accessing an element that is out of the bounds of an
array.
(iii)Trying to store a value into an array of an
incompatible class or type.
(iv) Passing invalid parameters for a method.
(v) Converting invalid string to a number.
(vi)Accessing a character that is out of bound of string
etc.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Example:
class ErrorProgram1
{
public class void main(String args[ ])
{
int a=10, b=4, c=4;
int res = a/(b-c); // dividing by zero
System.out.println(“Result = “ + res);
}
}
The error is / (divided) by zero.
Java.lang.ArithmeticException
After generating the error, the program stops.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
The purpose of exception handling is to produce a
means to detect and report an exceptional
circumstance. So that appropriate action can be
taken.
The following tasks are to be followed:
(i) Find the problem (hit the exception).
(ii) Detect the error (throw the exception).
(iii) Receive the error (catch the exception).
(iv )Take correct action (handle the exception).
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Common Java Exception
ArithmeticException : Caused by math errors such as division
by zero.
ArrayIndexOutOfBoundsException : Caused by bad array
indices.
FileNotFoundException : Non-existence of file.
IOException : General I/O failures, inability to read from a file.
NumberFormatException : Caused when conversion
between string and number fails.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Common Java Exception
OutOfMemoryException : There is not enough memory to
allocate a new object.
StringIndexOutOfBoundsException : Attempts to access
non existent character position in a string.
StackOverflowException : When the system runs out of
stack space.
ArrayStoreException : When an array attempts to store
different data type.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
try block
Throws exception object
catch block
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Syntax:try{
statement (s);
}
catch (Exception_type object_name)
{
statement (s);
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
The try block could generate the exception. If any
exception occurs then the control jumps to the catch block
by skipping the remaining statements of the block.
The catch block receives the exception and perform the
statements present in it.
The catch block always appear after the try block.
The catch block passes single parameter which is
reference to the exception object thrown by the try block.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
class error1
{
public static void main (String args [ ])
{
int a = 10, b = 4, c = 4;
int p, q;
try
{
p = a / ( b – c ); // exception here
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
catch (ArithmeticException e)
{
System.out.println(“Division by zero”);
}
q = a/(b+c);
System.out.println(“Q=” + q);
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Multiple Catch Block
• We can have more than one catch block in a program.
• Each catch block for a particular exception.
• These catch blocks are written after the try block.
• Syntax: try
{
statement (s);
}
catch (exception_type1 object1)
{
statement (s);
}
catch (exception_type2 object2)
{
statement (s);
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
// Read two numbers. Find its division
// using exception handling method
import java.io.*;
import java.util.*;
class Division_Exception
{
public static void main (String args [ ])
{
DataInputStream in = new DataInputStream(System.in);
int a, b, c;
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
try
{
System.out.print("Enter two numbers :");
a = Integer.parseInt(in.readLine());
b = Integer.parseInt(in.readLine());
c = a/b;
System.out.println ("Division = " + c);
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
// number input exception
catch (IOException ie)
{
System.out.println("Wrong Data Input");
}
// arithmetic division exception
catch (ArithmeticException e)
{
System.out.println("Division by zero");
}
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Output
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
// Without exception in a command line programming
class Arg_Add1
{
public static void main (String args[ ])
{
int sum = 0;
for (String st : args)
{
sum += Integer.parseInt(st);
}
System.out.println("Sum = " + sum);
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Output
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
// With exception in a command line programming
class Arg_Add2
{
public static void main (String args[ ])
{
int sum = 0;
try
{
for ( String st : args )
{
sum += Integer.parseInt(st);
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
catch (NumberFormatException object)
{
System.out.println(" [ " + object + " ] is not an integer " +
" and will not be included in the sum.");
}
System.out.println("Sum = " + sum);
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Output
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
// With exception in a command line
programming
class Arg_Add3
{
public static void main (String args[ ])
{
int sum = 0;
for ( String st : args )
{
try
{
sum += Integer.parseInt(st);
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
catch (NumberFormatException object)
{
System.out.println(" [ " + st + " ] is not an integer " + "
and will not be included in the sum.");
}
}
System.out.println("Sum = " + sum);
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Output
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
finally statement
It is used to handle an exception that is not
caught by any of the previous catch
statement.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Syntax-1: Syntax-2:
try try
{ {
statement (s); statement (s);
} }
finally catch (exception_type e)
{ {
statement (s); statement (s);
} }
catch (exception_type e) finally
{ {
statement (s); statement (s);
} }
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
// Example using finally
class FinallyExample
{
public static void main (String args[ ])
{
int i = 0;
String greetings[ ] ={"Hello world", "I mean it",
"HELLO WORLD" };
while (i < 4)
{
try
{
System.out.println (greetings[i]);
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“Array out of index");
}
finally
{
System.out.println("This is always printed");
}
i++;
} // while close
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Output
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
// Example of exception handling in command-line
// argument programming
class command_exception
{
public static void main (String args[ ])
{
int wrong = 0, num, valid = 0;
for ( int i=0; i<args.length; i++)
{
try
{
num = Integer.parseInt (args [i]);
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
catch (NumberFormatException ne)
{
System.out.println (" Wrong Number Format = " + args[i]);
wrong++;
continue;
}
valid++;
}
System.out.println ("Valid Numbers = " + valid);
System.out.println (" Invalid Numbers = " + wrong);
System.out.println (" Total Inputs = " + args.length);
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Output
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
User-Defined Exception
To throw our own exception then it can be
created by using the keyword throw.
Syntax:
throw new your_own_exception_class_name;
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
import java.lang.Exception; Example
class own_exception extends Exception
{
own_exception ( String m )
{
super (m);
}
}
class Test_Myexception
{
public static void main (String args[ ])
{
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
try
{
int a = 5, b = 10;
if (a < b)
{
throw new own_exception
(“First number is smaller than 2nd number”);
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
catch ( own_exception e )
{
System.out.println (“Caught my exception”);
System.out.println (e.getMessage());
}
}
}
Note: getMessage() is a method belongs to
Exception class, which shows the message residing
in the object of own_exception class kind (in this
example).
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
First number is smaller than 2nd number
100 own_exception object
e 100
new allocates an object of own_exception kind
and its reference is thrown to the exception
handler catch( ) and the object e assigns with
the reference here it is 100(Say).
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Output
Caught my exception
First number is smaller than 2nd number
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Using user-defined exception handling, read
numbers from the user and display +ve / -ve/ zero.
import java.lang.*;
import java.io.*;
class positive extends Exception
{
positive(String st)
{
super (st);
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
class negative extends Exception
{
negative(String st)
{
super (st);
}
}
class zero extends Exception
{
zero(String st)
{
super (st);
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
class multi_exception
{
public static void main( String args[ ]) throws IOException
{
DataInputStream in = new DataInputStream(System.in);
int n=0;
String a = "yes";
do
{
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
try
{
System.out.print ("Enter a number…. ");
n = Integer.parseInt(in.readLine());
if (n>0) { throw new positive("+ve"); }
if (n<0) { throw new negative("-ve"”); }
if (n==0) { throw new zero("Zero"); }
}
catch (positive p)
{
System.out.println (p.getMessage());
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
catch (negative n)
{
System.out.print (n.getMessage());
}
catch (zero z)
{
System.out.print (z.getMessage());
}
System.out.print ("Do you want to Continue[yes/No]?");
a = in.readLine();
} while(a.equalsIgnoreCases("yes"));
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Output
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Multithreaded
Programming
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Definition:
Running several programs simultaneously is
known as multitasking.
In system technology, it is called
multithreading.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Multitasking is of two types:
i.Process-based: In this multi tasking, several
programs are executed at a time by the
microprocessor.
ii.Thread-based: In this multi tasking, several
parts of the same program is executed at a
time by the microprocessor.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Java enables multiple flow of control.
Each flow of control can be considered as a
small program( or module) known as a
thread.
Each thread runs in parallel to others.
Program containing multiple flows of
control is known as multithreaded program.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Main Thread
start start start
Thread A Thread B Thread C
switching switching
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Uses of Threads
It is mainly used in server-side programs to
serve the needs of multiple clients on a
network or internet. On internet, a server
machine has to cater the needs of thousands of
clients at a time.
It is also used to create games and
animation.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Creating a Thread
Create a class that extends Thread class
or implements Runnable interface.
Both are belonged to the java.lang
package.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Syntax of thread class using Thread extends
class class_name extends Thread
{
public void run ( )
{
//statement(s) for implementing thread
}
// statement(s);
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Syntax of thread class using Runnable interface
class class_name implements Runnable
{
public void run ( )
{
// statement(s) for implementing thread
}
// statement(s);
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Running a Thread
Syntax
class_name object_name = new class_name( );
object_name.start( );
OR
new class_name.start( );
A thread is born with no name and brings to runnable state
with the help of start( ) and moving to running state.
The thread invokes run() because it is inherited by the
class class_name.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Example-1:
// Create a thread and run it.
// own thread class
class mythread extends Thread
{
public void run()
{
for( int i=1; i<=100; i++)
System.out.print( i + “ “);
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
// main class
class thread_demo
{
public static void main(String args[ ])
{
mythread obj = new mythread();
obj.start();
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
OR
// main class
class thread_demo
{
public static void main(String args[ ])
{
mythread obj = new mythread();
Thread th = new Thread(obj);
th.start();
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Example-2:
// Create three threads and run it.
class mythread1 extends Thread
{
public void run()
{
System.out.println(“1st Thread“);
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
class mythread2 extends Thread
{
public void run()
{
System.out.println(“2nd Thread“);
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
class mythread3 extends Thread
{
public void run()
{
System.out.println(“3rd Thread“);
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
class three_threads // main class
{
public static void main(String args[ ])
{
mythread1 obj1 = new mythread1( );
mythread2 obj2 = new mythread2( );
mythread3 obj3 = new mythread3( );
obj1.start( );
obj2.start( );
obj3.start( );
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
OR
class three_threads // main class
{
public static void main(String args[ ])
{
new mythread1().start();
new mythread2().start();
new mythread3().start();
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Terminating the Thread
A thread will terminate automatically when it comes out
of run( ) method.
To terminate a thread from the middle, the statement
return is used with a proper condition.
The condition should be placed in the run( ) method.
Syntax: public void run()
{
// statement (s);
if (condition) return;
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
// Create a thread ,run it and stop by pressing enter key.
import java.io.*;
class mythread extends Thread
{
boolen stop = false;
public void run()
{
for( int i=1; i<=100000; i++)
{ System.out.print( i + “ “);
if (stop) return;
}
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
class thread_demo // main class
{
public static void main(String args[ ])
{
mythread obj = new mythread();
obj.start();
System.in.read(); // to come out of thread press
obj.stop=true; // enter key
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Write a loop in thread-1. Read two numbers and
swap it in thread-2.
import java.io.*;
class thread1 extends Thread
{
public void run()
{
for( int i=1; i<=5; i++)
System.out.println( “Thread One“);
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
class thread2 extends Thread
{
int a=0, b=0;
public void run( )
{
read( );
System.out.println(“A=“+a+”B=“+b);
int c = a;
a = b;
b = c;
System.out.println(“A=“+a+”B=“+b);
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
void read( )
{
try
{
DataInputStream in = new DataInputStream(System.in);
System.out.print(“Enter Two numbers: ”);
a = Integer.parseInt(in.readLine( ));
b = Integer.parseInt(in.readLine( ));
}
catch(Exception e)
{ }
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
class main_thread_program // main class
{
public static void main(String args[ ])
{
thread1 obj1 = new thread1();
thread2 obj2 = new thread2();
obj1.start();
obj2.start();
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Output
Thread One Thread One
Thread One Thread One
Thread One Thread One
Thread One Thread One
Enter 2 numbers: Thread One Or Thread One
5 Enter 2 numbers: 6
10 9
A=5 B=10 A=6 B=9
A=10 B=5 A=9 B=6
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Program to execute multiple task using one thread.
class my_thread_class implements Runnable
{
public void run()
{
job1( );
job2( );
job3( );
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
void job1( )
{
System.out.println (“Job No. 1”);
}
void job2( )
{
System.out.println (“Job No. 2”);
}
void job3( )
{
System.out.println (“Job No. 3”);
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
class main_class
{
public static void main(String args[ ])
{
// create an object of my_thread_class kind
my_thread_class obj = new my_thread_class( );
// create a thread and link to the above object
Thread t = new Thread(obj);
//execute the thread t on the above object‟s run( ) method
t.start();
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Output
Job No. 1
Job No. 2
Job No. 3
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
NEW
Thread State
BORN
Stop( )
RUNNING
Stop( ) DEAD
RUNNABLE
Killed
suspend( ) resume( ) Thread
sleep( ) notify( )
Stop( )
wait( )
BLOCKED
Idle thread or non-runnable thread
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
i. stop ( ): To stop a thread which moves to
the dead state.
Syntax: object_name.stop( )
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Blocked or non-runnable state of a thread
ii.sleep( ) : To block a thread for a specified
time.
Syntax:
object_name.sleep (int time_in_milliseconds)
iii.suspend( ): To suspend a thread until further
orders.
Syntax: object_name.suspend( )
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
iv.wait( ): To block a thread until certain
condition occurs.
Syntax: object_name.wait( )
v. esume( ): It s used to get back to the
running state if the thread is in suspend ( )
state.
vi.notify ( ): It is used in case of the thread
is in wait( ) state.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Method
Name
Purpose
getName() To get the name of the thread
getPriority() To get the priority of the thread
isAlive() Determine if a thread is still running
join() Wait for a thread to terminate or die
run() Entry point for the thread
sleep() Suspend a thread for a period of
time
start() Start a thread by calling its run
method
setName() To change or set the name of the
method
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
// Display the maximum, minimum, and normal
//priority of main thread
class Priority
{
public static void main(String args[ ])
{
Thread t = Thread.currentThread( );
System.out.println("Priority of Main Thread:“ +
t.getPriority( ));
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
System.out.println ("Normal Priority of
Main Thread:" + t.NORM_PRIORITY);
System.out.println ("Minimum Priority of
Main Thread:" + t.MIN_PRIORITY);
System.out.println ("Maximum Priority of
Main Thread:" + t.MAX_PRIORITY);
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Output
Priority of Main Thread: 5
Normal Priority of Main Thread: 5
Minimum Priority of Main Thread: 1
Maximum Priority of Main Thread: 10
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
// set and get the priorities of threads
class child extends Thread
{
child(String n)
{
super (n);
System.out.println("Thread Name: " + this);
}
}
class Priority1
{
public static void main(String args[ ])
{
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Thread t = Thread.currentThread( );
child T1 = new child("ONE");
child T2 = new child("TWO");
child T3 = new child("THREE");
System.out.println("Priority of Main
Thread:“ + t.getPriority( ));
System.out.println("Priority of Thread “ +
T1.getName() + "=“ + T1.getPriority( ));
System.out.println("Priority of Thread “
+ T2.getName()+"="+ T2.getPriority( ));
System.out.println("Priority of Thread “
+ T3.getName() + "=“ + T3.getPriority( ));
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
t.setPriority(Thread.MAX_PRIORITY);
T1.setPriority(Thread.MAX_PRIORITY-3);
T2.setPriority(Thread.MIN_PRIORITY+3);
T3.setPriority(Thread.MAX_PRIORITY-
Thread.MIN_PRIORITY);
System.out.println("After set new priority to all 4
threads.");
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
t.setPriority(Thread.MAX_PRIORITY);
System.out.println("Priority of Main Thread:"
+ t.getPriority());
System.out.println("Priority of Thread " +
T1.getName()+"="+T1.getPriority());
System.out.println("Priority of Thread "
+ T2.getName()+"="+T2.getPriority());
System.out.println("Priority of Thread "
+ T3.getName()+"="+T3.getPriority());
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Thread Name: Thread [ ONE , 5, main]
Thread Name: Thread [ TWO , 5, main]
Thread Name: Thread [ THREE , 5, main]
Priority of Main Thread: 5
Priority of Thread ONE : 5
Priority of Thread TWO : 5
Priority of Thread THREE : 5
After set new priority to all 4 threads.
Priority of Main Thread: 10
Priority of Thread ONE : 7
Priority of Thread TWO : 4
Priority of Thread THREE : 9
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Thread Priorities
Thread priorities are used by the thread scheduler
to decide when each thread should be allowed to
run.
Higher-priority threads get more CPU time than
lower priority threads.
Threads of equal priority should get equal access
to the CPU.
To set a thread‟s priority, use the setPriority( )
method, which is a member of Thread.
The general form:
final void setPriority(int level)
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Here, level specifies the new priority setting for the
calling thread. The value of level must be within the range
MIN_PRIORITY and MAX_PRIORITY. Currently, these
values are 1 and 10, respectively.
To return a thread to default priority, specify
NORM_PRIORITY, which is currently 5. These priorities
are defined as final variables within Thread.
You can obtain the current priority setting by calling the
getPriority( ) method of Thread.
The general form: final int getPriority( )
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
One thread is set two levels above the normal priority, as
defined by Thread.NORM_PRIORITY, and the other is
set to two levels below it.
The threads are started and allowed to run for ten
seconds.
Each thread executes a loop, counting the number of
iterations.
After ten seconds, the main thread stops both threads.
The number of times that each thread made it through the
loop is then displayed
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
// thread priorities program
import java.lang.*;
class thread_class extends Thread
{ int count = 0;
public void run( )
{
for( int i=1; i<=10000; i++)
count++;
System.out.println("Completed Thread :" +
Thread.currentThread( ).getName( ));
System.out.println("Its Priority:" +
Thread.currentThread( ).getPriority( ));
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
class Priority2
{
public static void main(String args[ ])
{
thread_class obj = new thread_class( );
Thread t1 = new Thread(obj, "One");
Thread t2 = new Thread(obj, "Two");
// set priority
t1.setPriority(2);
t2.setPriority(Thread.NORM_PRIORITY);
// start first t1 and then t2
t1.start( );
t2.start( );
} }
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
1st Run
Completed Thread : One
Completed Thread : Two
Its Priority : 5
Its Priority : 2
2nd Run
Completed Thread : One
Its Priority : 2
Completed Thread : Two
Its Priority : 5
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
// Program for multi-tasking using threads
class my_thread implements Runnable
{
String st;
my_thread(String str)
{
this.st = str;
// or st = str;
}
public void run()
{ for(int i=1; i<=4; i++)
{ System.out.println(st + " : " + i);
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
try
{ //suspend execution for 2000 milliseconds
// i.e. 1000 milliseconds = 1 second
Thread.sleep (2000);
}
catch(InterruptedException ie)
{ ie.printStackTrace(); }
} // loop close
} // run() close
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
class cinema
{
public static void main(String args[ ])
{
my_thread obj1 = new my_thread("Get the Ticket");
my_thread obj2 = new my_thread("Show the Seat");
Thread t1 = new Thread(obj1);
Thread t2 = new Thread(obj2);
t1.start( );
t2.start( );
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Output
Get the Ticket : 1
Show the Seat : 1
Get the Ticket : 2
Show the Seat : 2
Get the Ticket : 3
Show the Seat : 3
Get the Ticket : 4
Show the Seat : 4
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
// multiple threads acting on single object
class reservation implements Runnable
{
int avail = 2;
int wanted;
reservation(int a)
{
wanted = a;
}
public void run()
{
System.out.println("Available Seats =" + avail);
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
if(avail>=wanted)
{
String name = Thread.currentThread().getName();
System.out.println(wanted + " Seat Reserved for " + name);
try
{
Thread.sleep(1500);
avail = avail - wanted;
}
catch(InterruptedException ie) { }
}
else
System.out.println("Sorry, No seats Available");
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
class unsafe
{ public static void main(String args[ ])
{ reservation obj = new reservation(1);
Thread t1 = new Thread(obj);
Thread t2 = new Thread(obj);
Thread t3 = new Thread(obj);
t1.setName("Laxmi");
t2.setName("Ram");
t3.setName("Swati");
t1.start();
t2.start();
t3.start();
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Available Seats = 2
2 Seat Reserved for Laxmi
Available Seats = 2
2 Seat Reserved for Ram
Available Seats = 2
2 Seat Reserved for Swati
Note: Here all the three threads t1, t2, t3 act on the
same object obj. The available seats never be
updated after allotting to a particular person. This
kind of situation is known as Thread
Synchronization or Thread unsafe.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Thread Synchronization
When a thread is already acting on an object
preventing any other thread from acting on
the same object is called thread
synchronization.
The object on which the threads are
synchronized is called synchronized object.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Synchronized object is like a locked object, locked on a
thread.
Example:
If a room has one door and a person entered into the room
and locked. The second person who wants to enter the room
should wait till the first person opened the door and comes
out.
The same way an thread also locks the object after
entering it. Then the next thread cannot enter it till the 1st
thread comes out.
It means the object is locked mutually on threads. So this
object is called mutex (mutually exclusive lock).
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Thread Synchronization
Entered T2 thread is waiting till
thread T1 T1 comes out
OBJECT
The OBJECT is called MUTEX
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Two different ways an object can be
synchronized.
i. Using synchronized method:
A group of statements of the object are
kept in a synchronized block. That is these
statements are kept inside run() method.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Syntax: void run( )
{
synchronized (object_name)
{
// statement(s);
}
}
Here, object_name represents the object to be
locked or synchronized.
The statement(s) inside the synchronized block
are available to only one thread at a time.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
ii. Using synchronized keyword:
An entire method can be synchronized by using the
keyword synchronized.
Syntax:
synchronized void method_name( )
{
// statement (s);
}
Here the statement(s) present inside method_name( )
are available to only one thread at a time.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
// Program for multiple threads acting on single
// object using synchronization.
class reservation implements Runnable
{
int avail = 2;
int wanted;
reservation(int a)
{
wanted = a;
}
public void run( )
{
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
synchronized (this)
{
System.out.println("Available Seats =" + avail);
if(avail>=wanted)
{
String name = Thread.currentThread().getName();
System.out.println(wanted + " Seat Reserved for " +
name);
try
{
Thread.sleep(1500);
avail = avail - wanted;
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
catch(InterruptedException ie)
{ }
}
else
System.out.println("Sorry, No seats Available");
} // end of synchronized block
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
class safe
{ public static void main(String args[])
{
reservation obj = new reservation(1);
Thread t1 = new Thread(obj);
Thread t2 = new Thread(obj);
Thread t3 = new Thread(obj);
t1.setName("Kumar");
t2.setName("Sreedevi");
t3.setName("Rani");
t1.start(); t2.start(); t3.start();
}
}
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Available Seats = 2
1 Seat Reserved for Kumar
Available Seats = 1
1 Seat Reserved for Sreedevi Output
Available Seats = 0
Sorry, No seats Available
Available Seats = 2
1 Seat Reserved for Kumar
Available Seats = 1
Output 1 Seat Reserved for Rani
Available Seats = 0
Sorry, No seats Available
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Thread Deadlock
When a thread has locked an object and waiting for
another object to be released by another thread, and
the other thread is also waiting for the first thread to
release the first object.
So both the threads will continue waiting forever.
This is called Thread Deadlock.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Book a Ticket
TRAIN
OBJECT
COMPARTMENT
OBJECT
Cancel a Ticket
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Thread Group
Several threads can be grouped together
under a common name.
It can control the grouped threads by using
the thread group name.
Syntax:
ThreadGroup tg =
new ThreadGroup("group_name");
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Example:
Thread t;
ThreadGroup tg =
new ThreadGroup ("Hello");
t = new Thread (tg, targetobject,
"threadname");
Here the thread t belongs to the thread
group tg and acts on targetobject, which
is the target object for the thread.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
Adding a new thread group in an Existing thread
group:
ThreadGroup tg1 = new ThreadGroup(tg,
"groupname");
Here a new thread group called tg1 is created and
added to the existing thread group tg.
ThreadGroup tg.getParent( ): It returns the
parent of a thread or thread group .
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang
t.getThreadGroup( ): It returns the parent thread
group of a thread.
tg.activeCount( ): To know the number of threads
actively running in the thread group.
tg.setMaxPriority( ): To change the maximum
priority of a thread group.
3rd Semester B. Tech (CSE) OOP using Java IGIT, Sarang