Java (Mod 2)

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

JAVA Programming By Sourav Kumar Giri 2020

Chapter 4 CLASSES & OBJECTS


Class : A class is a user defined data type which binds data and function into a single unit and objects are the
instance of a class. A class is declared by use of the class keyword.

Syntax of class definition:


class class_name
{
type instance_variable1;
type instance_variable2;
type instance_variablen;
type methodname1(parameter_list)
{
// body of method
}
type methodname2(parameter_list)
{
// body of methodTHE JAVA LANGUAGE
}
type methodnamen(parameter_list)
{
// body of method
}
}

The data, or variables, defined within a class are called instance variables. The code is contained within
methods. Collectively, the methods and variables defined within a class are called members of the class.

Program 4.1 Write a program to calculate volume of a box with its width, height and depth initialized.
Solution:
class Box
{
double width;
double height;
double depth;
void volume()

58
JAVA Programming By Sourav Kumar Giri 2020

{
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}
class BoxDemo
{
public static void main(String args[])
{
Box mybox1 = new Box();//create an object mybox1 and allocates memory
Box mybox2 = new Box();//create an object mybox2 and allocates memory

mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;

mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;

mybox1.volume();
mybox2.volume();
}
}

Output:
Volume is 3000.0
Volume is 162.0

Explanation
The new operator dynamically allocates memory for an object. It has this general form:
class-var = new classname( );
Here, class-var is a variable of the class type being created. The classname is the name of the class that is
being instantiated. The class name followed by parentheses specifies the constructor for the class. A
constructor defines what occurs when an object of a class is created.

59
JAVA Programming By Sourav Kumar Giri 2020

Thus the statement:


Box mybox1 = new Box (); create an object mybox1 and allocate memory to it.
The above statement can be written in two steps:
Box mybox1; // declare reference to object
mybox1 = new Box (); // allocate memory to a Box object

Statement Effect

Null
Box mybox1

Width
mybox1=new Box()
Height
Depth

Constructor
 A constructor is a special member function whose name is same as the class name in which it is
declared.
 The constructor is automatically called immediately when the object is created.
 Constructors do not have any return type.
 Its purpose is to initialize the object of a class.
 Constructors are of three types:
Default Constructor: Constructor which takes no argument(s) is called Default Constructor.
Parameterized constructor: Constructor which takes argument(s) is called parameterized
Constructor.
Copy Constructor: Constructor which takes object as its argument is called copy constructor.
 When a single program contains more than one constructor, then the constructor is said to be
overloaded which is also known as constructor overloading.

Program 4.2: Write a program to illustrate constructor overloading in java.
Solution:
class Box
{
double width;
double height;
double depth;

60
JAVA Programming By Sourav Kumar Giri 2020

Box(double w, double h, double d) // Parameterized Constructor


{
width = w;
height = h;
depth = d;
}
Box() // Default Constructor
{
width = -1;
height = -1;
depth = -1;
}

Box(double len) // Parameterized Constructor


{
width = height = depth = len;
}
double volume()
{
return width * height * depth;
}
}
class Overload
{
public static void main(String args[])
{
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);

61
JAVA Programming By Sourav Kumar Giri 2020

vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}TH

Output:
Volume of mybox1 is 3000.0
Volume of mybox2 is -1.0
Volume of mycube is 343

Garbage Collection
Java garbage collection is the process by which Java programs perform automatic memory management. Java
programs compile to bytecode that can be run on a Java Virtual Machine, or JVM for short. When Java
programs run on the JVM, objects are created on the heap, which is a portion of memory dedicated to the
program. Eventually, some objects will no longer be needed. The garbage collector finds these unused
objects and deletes them to free up memory.
Java garbage collection is an automatic process. The programmer does not need to explicitly mark objects to
be deleted. The garbage collection implementation lives in the JVM. Each JVM can implement garbage
collection however it pleases; the only requirement is that it meets the JVM specification.
In some languages, such as C++, dynamically allocated objects must be manually released by use of a delete
operator. Java takes a different approach; it handles deallocation automatically. The technique that
accomplishes this is called garbage collection.

The finalize () method


By using this method, we can define specific actions that will occur when an object is just about to be
reclaimed by the garbage collector. The finalize ( ) method has this general form or syntax:
protected void finalize( )
{
// finalization code here
}

The static Keyword


The static keyword in Java is used for memory management mainly. We can apply java static keyword with
variables, methods, blocks and nested class. The static entities belong to the class rather than the object of
the class.

62
JAVA Programming By Sourav Kumar Giri 2020

The static keyword can be applied to variable, method or block as discussed below:
 Static variable (also known as a class variable)
 Static method (also known as a class method)
 Static block

Static variable
These are variables which are initialized only once during the course of program execution and their
declaration are preceded by the keyword static. These variables are used to represent the common property
of all objects of a class. Therefore static variables are also referred as class variable. Alternately, only one
copy of static variable exists for all the objects of a class. The static variable gets memory only once in the
class area at the time of class loading

Program 4.3: Write a program which demonstrate the use of instance variable & static variable
Solution:
class Counter
{
int count=0;//will get memory each time when an object is created
static int scount=0;//will get memory once
Counter()
{
count++; //incrementing instance or object variable
scount++; //incrementing static or class variable
System.out.println("count="+count+"\t scount="+scount);
}
public static void main(String args[])
{
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}
}

63
JAVA Programming By Sourav Kumar Giri 2020

Output:
count=1 scount=1
count=1 scount=2
count=1 scount=3

Static method
Any method declaration preceded by the keyword static is known as static method. The properties of static
methods are:
 A static method belongs to the class rather than the object of a class.
 A static method can be invoked without the need for creating an instance of a class.
 A static method can access static data member and can change the value of it.

Program 4.4: Write a program which demonstrates the use of static method in java.
Solution:
class Calculate
{
static int cube(int x)
{
return x*x*x;
}
public static void main(String args[])
{
int r=Calculate.cube(5);
System.out.println("Volume of cube is "+r);
}
}

Output:
Volume of cube is125

Restriction of static methods


Two main restrictions for the static method are:
 The static method cannot use non static data member or call non-static method directly.
 this and super cannot be used in static context.

64
JAVA Programming By Sourav Kumar Giri 2020

Below program demonstrate the illegal use of static methods:


class A
{
int a=40; //a is non static
public static void main(String args[])
{
System.out.println(a); // Compilation error !! a is non static
}
}

Java static block


Static block is used to initialize the static data member. It is executed before the main method at the time of
class loading.

Program 4.5: Write a program which demonstrates the use of static block in java.
Solution:

class A2
{
static
{
System.out.println("static block is invoked");
}
public static void main(String args[])
{
System.out.println("Hello main");
}
}

Output:
static block is invoked
Hello main

65
JAVA Programming By Sourav Kumar Giri 2020

The this Keyword


In java, this is a reference variable that refers to the current object. Several usages of java this keyword are:
 this can be used to refer current class instance variable.
 this can be used to invoke current class method (implicitly)
 this() can be used to invoke current class constructor.
 this can be passed as an argument in the method call.
 this can be passed as argument in the constructor call.
 this can be used to return the current class instance from the method.

Program 4.6: Write a program which demonstrates the use of this keyword in java.
Solution:
class Student
{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee)
{
this.rollno=rollno;
this.name=name;
this.fee=fee;
this.display();
}
void display()
{
System.out.println(rollno+"\t"+name+"\t"+fee);
}
}
class Test
{
public static void main(String args[])
{
Student s1=new Student(101,"Kabya",6000f);
Student s2=new Student(102,"Ram",5000f);
}

66
JAVA Programming By Sourav Kumar Giri 2020

Output:
101 Kabya 6000.0
102 Ram 5000.0

Access modifiers
There are two types of modifiers in Java: access modifiers and non-access modifiers. There are many non-
access modifiers, such as static, abstract, synchronized, native, volatile, transient, etc.
The access modifiers in Java specify the accessibility or scope of a field, method, constructor, or class. We
can change the access level of fields, constructors, methods, and class by applying the access modifier on it.
There are four types of Java access modifiers:
 Private: The access level of a private modifier is only within the class. It cannot be accessed from
outside the class.
 Default: The access level of a default modifier is only within the package. It cannot be accessed from
outside the package. If you do not specify any access level, it will be the default.
 Protected: The access level of a protected modifier is within the package and outside the package
through child class. If you do not make the child class, it cannot be accessed from outside the package.
 Public: The access level of a public modifier is everywhere. It can be accessed from within the class,
outside the class, within the package and outside the package.
Let's understand the access modifiers in Java by a simple table.

Access Modifier within class within package outside package by outside package
subclass only

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

Example of private access specifier


In the below example, class A contains private data member and private method. We are trying to access
these private members from outside the class, so there is a compile-time error.

67
JAVA Programming By Sourav Kumar Giri 2020

class A
{
private int data=40;
private void msg()
{
System.out.println("Hello java");
}
}
public class Simple
{
public static void main(String args[])
{
A obj=new A();
System.out.println(obj.data); //Compile Time Error
obj.msg(); //Compile Time Error
}
}

Example of default access specifier


If we don't use any modifier, it is treated as default by default. The default modifier is accessible only within
package. It cannot be accessed from outside the package. It provides more accessibility than private. But, it is
more restrictive than protected, and public. In the above example, the scope of class A and its method msg()
is default so it cannot be accessed from outside the package.

68
JAVA Programming By Sourav Kumar Giri 2020

package pack;
class A
{
void msg()
{
System.out.println("Hello");
}
}
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A(); //Compile Time Error
obj.msg(); //Compile Time Error
}
}

Example of protected access specifier


In the below example, we have created two packages pack and mypack. The class A of package pack is public,
so it can be accessed from outside the package. But msg method of this package is declared as protected, so it
can be accessed from outside the class only through inheritance.

69
JAVA Programming By Sourav Kumar Giri 2020

//A.java
package pack;
public class A
{
protected void msg()
{
System.out.println("Hello");
}
}
//B.java
package mypack;
import pack.*;
class B extends A
{
public static void main(String args[])
{
B obj = new B();
obj.msg();
}
}
Output: Hello

Example of public access specifier


The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.

//A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
} contd..

70
JAVA Programming By Sourav Kumar Giri 2020

//B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Output: Hello

************

71
JAVA Programming By Sourav Kumar Giri 2020

Practice Questions

1. Choose the most appropriate answer:


a) Which one of the following is an instance of a class?
a) field b) method
c) object d) None of theses

b) Collection of similar objects is termed as


a) class b) array
c) structure d) Both a) and c)

c) Technique used in java for memory release is known as


a) Destructor b) Free
c) Constructor d) Garbage collection

d) Which one of the following is used for memory allocation in java?


a) Constructor b) Garbage collection
c) both a) and b) d) Destructor

e) Fields which are initialized only once and only one copy of it exists for all the object are
a) static fields b) private fields
c) public fields d) All of these

f) The property of OOPs by which an entity can acquire multiple forms is known as
a) Inheritance b) Polymorphism
c) Encapsulation d) Data Aggregation

g) Which variables are known as class variables?


a) public b) static
c) private d) final

h) The act of hiding data and methods from external world with the help of access modifier is
known as
a) Data Hiding b) Polymorphism
c) Data Encapsulation d) Data Abstraction

i) The object pointer which point to the recent object through which a method is invoked is
known as
a) this pointer b) static pointer
c) final pointer d) None of these

j) What is the syntax to create an object in java?


a) class_name instance=new class_name;
b) class_name instance=new() class_name;
c) class_name instance=new class_name[];

72
JAVA Programming By Sourav Kumar Giri 2020

d) class_name instance=new class_name();

k) Which of the following is not true about constructor?


a) don’t have return type b) name is same as class name
c) can’t be overloaded d) called automatically

Short Type
2. Answer briefly
a) Define class.
b) Define constructor.
c) What is Garbage collection?
d) Name the method which is called prior to garbage collection.
e) Can a static method access non static variable?
f) What is this keyword in java?
g) Name the technique by which memory is de-allocated in java?
h) How do we create objects in java?

Long Type
3. Answer in details
a) Define constructor. What are its characteristics? Explain different types of constructor with proper
programming examples.
b) Explain various access modifiers available in java with proper examples.
c) Explain static methods with the help of proper example.
d) Explain the use of static block in java with proper example.

*************

73
JAVA Programming By Sourav Kumar Giri 2020

Chapter 5 INHERITANCE
Inheritance
It is the process by which object of one class can acquire the properties of object of another class. The class,
from which properties are inherited to another class, is known as super class. The class, to which properties
are inherited from an existing class, is known as sub class. A sub class inherits all non-private variables and
methods defined by the super class and add its own, unique elements. To derive a sub class from super class,
we use extends keyword.

Super Class
Sub class
acquires the
properties of
super class

Sub Class

Advantages of using inheritance


 Inheritance allows the creation of hierarchical classifications of classes.
 It allows code reusability feature.
 The sub class extends the properties of super classes to create more dominant objects.
Let us take very simple example of inheritance shown below. Here Programmer and Office_Boy are two
classes which inherit properties from the class Employee. Both these class will have attributes like name,
salary, date_of_joining along with their own attributes.

Employee
name: String
salary: float
date_of_joining:
Date

Programmer Office_Boy
project_title:String section: String
incentives: float bonus: float

74
JAVA Programming By Sourav Kumar Giri 2020

The syntax of a class declaration that inherits a super class is:

class subclass-name extends superclass-name


{
// body of class
}

Point to Remember: A sub class can access all the public and protected members of a super class, not the
private members. (By default, the variable or functions of a class are public in nature)

Types of Inheritance
Java supports following types of inheritance:
 Single Inheritance
 Hierarchical Inheritance
 Multiple Inheritance (not supported using class, but supported through interface)
 Multilevel Inheritance
 Hybrid Inheritance (may not be supported using class, but supported through interface)

Single Inheritance
In single inheritance, we have only one super class and one sub class. The subclass inherits properties from
the only super class. A single inheritance can be shown as:

Super
Class

Sub
Class

Syntax of single inheritance:


class superClass
{
// Body of super class
}
class subclass extends superClass
{
// body of sub class
}

75
JAVA Programming By Sourav Kumar Giri 2020

Program 5.1: Write a program to demonstrate single inheritance in java.


Solution:
class Rectangle
{
int l, b;
void disp_lb()
{
System.out.println("l= " +l+", b="+b);
}
}
class Cuboid extends Rectangle
{
int h;
void disp_h()
{
System.out.println("h= " +h);
}
void find_volume()
{
System.out.println ("Volume= "+l*b*h);
}
}

class SimpleInheritance
{
public static void main(String args[])
{
Cuboid c=new Cuboid();
c.l=9;
c.b=7;
c.h=3;
c.disp_lb();
c.disp_h();
c.find_volume();
}
}

Output:
l=9, b=7
h=3
Volume=189

Explanation: Here sub class cuboid is able to access data l, b and method disp_lb() of super class Rectangle
through single inheritance.

76
JAVA Programming By Sourav Kumar Giri 2020

Hierarchical Inheritance
In hierarchical inheritance, two or more subclass inherits properties from a single super class. For example
in a family, a son and a daughter of a single father inherit properties from the father. A hierarchical
inheritance can be show as:

super
class

sub sub
class 1 class 2

Syntax of hierarchical inheritance:


class superClass
{
// Body of super class
}
class subclass1 extends superClass
{
// body of sub class 1
}
class subclass2 extends superClass
{
// body of sub class 2
}

Program 5.2: Write a program to demonstrate hierarchical inheritance in java.


Solution:
class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void bark()

77
JAVA Programming By Sourav Kumar Giri 2020

{
System.out.println("barking...");
}
}
class Cat extends Animal
{
void meow()
{
System.out.println("meowing...");
}
}
class HierarchicalInheritance
{
public static void main(String args[])
{
Cat c=new Cat();
c.meow();
c.eat();
}
}

Output:
meowing…
eating…

Multiple Inheritance
In multiple inheritance, one subclass inherits properties from two or more super class. For example in a
family, a father and mother having a, where the son inherits properties from both father and mother. A
multiple inheritance can be show as:
:
super super
class 1 class 2

sub
class

78
JAVA Programming By Sourav Kumar Giri 2020

Remember:
In Java, multiple inheritance is not supported using classes due to ambiguity problem. Ambiguity is a
situation where compiler cannot predicate to inherit which field out of identical fields present in multiple
super classes. But same can be achieved using the concept of interface.
Therefore, following syntax is illegal in java:
class superClass1
{
// Body of super class 1
}
class superClass2
{
// Body of super class 2
}
class subClass extends superClass1, superClass1 //Illegal
{
// body of sub class 2
}

Multi level Inheritance


In multi level inheritance, a number of classes are represented at different level as shown in the below
diagram. For example, in a family, a father inherits properties from grandfather and son inherits properties
from father.
: super
class 1

super
class 2

sub
class

Note: Here super class 2 inherits properties from super class 1 and subclass inherits properties from super
class 2.

79
JAVA Programming By Sourav Kumar Giri 2020

Syntax of multilevel inheritance:


class superClass1
{
// Body of super class 1
}
class superClass2 extends superClass1
{
// body of super class 2
}
class subClass extends superClass2
{
// body of sub class
}

Program 5.3: Write a program to demonstrate multilevel inheritance in java.


Solution:
class Shape
{
public void display()
{
System.out.println("Inside display");
}
}
class Rectangle extends Shape
{
public void area()
{
System.out.println("Inside area");
}
}
class Cube extends Rectangle
{
public void volume()
{
System.out.println("Inside volume");
}
}
public class Tester
{
public static void main(String[] arguments)
{
Cube cube = new Cube();
cube.display();
cube.area();
cube.volume();
}

80
JAVA Programming By Sourav Kumar Giri 2020

Output:
Inside display
Inside area
Inside volume

Hybrid Inheritance
It is the combination of all the above inheritance.

How constructor of a super class gets called ?


A subclass constructor can call or invoke the constructor of its super class in two ways:
 A subclass constructor invokes the default or non parameterized constructor of its super class
implicitly or automatically.
 A subclass constructor can invoke the parameterized constructor of its super class explicitly by using
the “super” statement.
Note: In a class hierarchy, constructors are called in order of derivation, from super class to subclass. super()
must be the first statement to be executed in a subclass constructor to call the parameterized constructor of
super class.. If super() is not used, then the default constructor of super class will be called.
Program 5.4: Write a program to demonstrate subclass constructor invoking the constructor of the
super class implicitly.
Solution:
class A
{
A()
{
System.out.println("Inside A's constructor.");
}
}
class B extends A
{
B()
{
System.out.println("Inside B's constructor.");
}
}

81
JAVA Programming By Sourav Kumar Giri 2020

class C extends B
{
C()
{
System.out.println("Inside C's constructor.");
}
}
class CallingCons
{
public static void main(String args[])
{
C c = new C();
}
}

Output:
Inside A's constructor.");
Inside B's constructor.");
Inside C's constructor.");

Program 5.5: Write a program to demonstrate subclass constructor invoking the parameterized
constructor of the super class explicitly by using super keyword.
Solution:
class Rect
{
int length, breadth;
Rect (int l, int b)
{
length=l;
breadth=b;
}
}
class Cuboid extends Rect
{
double height;

82
JAVA Programming By Sourav Kumar Giri 2020

Cuboid (int l, int b, int h)


{
super(l, b);
height=h;
}
void volume()
{
System.out.println (length*breadth*height);
}
}THE JAVA LANGUAGE
class Vol
{
public static void main(String args[]) {
Cuboid v=new Cuboid(1, 2, 3);
v.volume();
}
}

Output:
6.0

*************

83
JAVA Programming By Sourav Kumar Giri 2020

Practice Questions
1. Choose the most appropriate answer:
a) Advantage(s) of inheritance is/are
a) Code reusability b) Hierarchical representation of classes
c) Both a) and b) d) None

b) Keyword used to achieve inheritance in java is


a) extend b) extends
c) inherit d) inherits

c) Which inheritance is not supported in java through classes?


a) Single b) Multiple
c) Hierarchical d) Multilevel

d) A system of three classes where two classes inherits properties from a class is known as
__________ inheritance.
a) Single b) Multiple
c) Hierarchical d) Hybrid

e) Which keyword is used to call the parameterized constructor of a super class from sub class
constructor?
a) final b) sup
c) super d) call

f) The technique by which one class acquires the properties of another class is known as
a) Inheritance b) Polymorphism
c) Encapsulation d) Data Aggregation

Short Type
2. Answer briefly
a) Define inheritance?
b) List different types of inheritance in java.
c) Which inheritance is not supported in java & why?
d) What is hierarchical inheritance in java?
e) What is multilevel inheritance?

Long Type
3. Answer in details
a) Define inheritance. Explain different types of inheritance with their syntax.
b) Explain how a sub class constructor can call the constructors of its super class

*************

84
JAVA Programming By Sourav Kumar Giri 2020

Chapter 6 Polymorphism
Polymorphism
The word polymorphism means having many forms (Poly means many and morph means forms). In simple
words, we can define polymorphism as the ability of an entity to exhibit multiple behaviors or definitions
depending upon the working environment. Polymorphism is of two types:
 Static polymorphism: If the polymorphism is achieved during program compilation, it is known as
static polymorphism. It is therefore also known as compile time polymorphism or early binding.
 Dynamic polymorphism: If the polymorphism is achieved during program execution, it is known as
dynamic polymorphism. It is therefore also known as run time polymorphism or late binding.

Method Overloading
If a class has multiple methods having same name but different signatures i.e. different no and types of
arguments, it is known as Method Overloading. A method in java can be overloaded in two ways:
 By changing number of arguments
 By changing the data type

Program 6.1: Write a program to demonstrate method overloading in java by changing the no of
arguments.
Solution:
class Adder
{
static int add(int a,int b)
{
return a+b;
}
static int add(int a,int b,int c)
{
return a+b+c;
}
}
class OverloadP
{
public static void main(String[] args)
{
System.out.println(Adder.add(10,20));

85
JAVA Programming By Sourav Kumar Giri 2020

System.out.println(Adder.add(10,20,30));
}
}

Output:
30
60

Program 6.2: Write a program to demonstrate method overloading in java by changing the types of
arguments.
Solution:
class Adder
{
static int add(int a, int b)
{
return a+b;
}
static double add(double a, double b)
{
return a+b;
}
}
class OverloadT
{
public static void main(String[] args)
{
System.out.println(Adder.add(10,20));
System.out.println(Adder.add(10.3,12.8));
}
}

Output:
30
23.1

86
JAVA Programming By Sourav Kumar Giri 2020

Note: It is not possible to overload methods by simply changing their return types as it leads to
compilation error due to ambiguity problem. It is also possible to overload main() method in a java
program, but compiler call that function which takes string array as its arguments.

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

A real example of Java Method Overriding


Consider a scenario where Bank is a class that provides functionality to get the rate of interest. However, the
rate of interest varies according to banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7%, and
9% rate of interest.

Program 6.3: Write a program to demonstrate method overriding in java.


Solution:
class A
{
void callme()
{
System.out.println("Inside A's callme method");
}
}
class B extends A
{
void callme()
{
System.out.println("Inside B's callme method");
}
}
class Overriding
{
public static void main(String args[])

87
JAVA Programming By Sourav Kumar Giri 2020

{
B b = new B();
b.callme(); // calls B's version of callme
}
}

Output:
Inside B’s callme method

Explanation: When callme ( ) is invoked on an object of type B, the version of callme ( ) defined within B is
used. That is, the version ofcallme ( ) inside B overrides the version declared in A. If we wish to access the
super class version of an overridden function, we you can do so by using super.

Note: A static method cannot be overridden. It is because the static method is bound with class whereas
instance method is bound with an object. Static belongs to the class area, and an instance belongs to the
heap area. The main is a static method, hence it cannot be overridden.

Dynamic Method Dispatch


Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time,
rather than compile time. Dynamic method dispatch is important because this is how Java implements run-
time polymorphism.
Program 6.4: Write a program to demonstrate the use of dynamic method dispatch.
Solution:
class A
{
void callme()
{
System.out.println("Inside A's callme method");
}
}
class B extends A
{
void callme()
{
System.out.println("Inside B's callme method");

88
JAVA Programming By Sourav Kumar Giri 2020

}
}
class C extends A
{
void callme()
{
System.out.println("Inside C's callme method");
}
}
class DMD
{
public static void main(String args[])
{
A a = new A();
B b = new B();
C c = new C();
A r; // obtain a reference of type A
r = a; // r refers to an A object
r.callme(); // calls A's version of callme
r = b; // r refers to a B object
r.callme(); // calls B's version of callmeVA LANGUAGE
r = c; // r refers to a C object
r.callme(); // calls C's version of callme
}
}

Output:
Inside A's callme method
Inside B's callme method
Inside C's callme method

Abstract class
Abstract classes are the class which contains method without providing a complete implementation (or
without having background details). It is not possible create object of an abstract class. Abstract classes can
include methods having all details.

89
JAVA Programming By Sourav Kumar Giri 2020

Program 6.5: Write a program to demonstrate the use of abstract class in java.
Solution:
abstract class A
{
abstract void callme();
// concrete methods are still allowed in abstract classes
void callmetoo()
{
System.out.println("This is a concrete method.");
}
}
class B extends A
{
void callme()
{
System.out.println("B's implementation of callme.");
}
}
class AbstractDemo
{
public static void main(String args[])
{
B b = new B();
b.callme();
b.callmetoo();
}
}

Output:
B's implementation of callme.
This is a concrete method.

Although abstract classes cannot be used to instantiate objects, they can be used to create object references,
because Java’s approach to run-time polymorphism is implemented through the use of super class

90
JAVA Programming By Sourav Kumar Giri 2020

references. Thus, it must be possible to create a reference to an abstract class so that it can be used to point
to a subclass object.
Uses of final Keyword
The keyword final has three uses:
 First, it can be used to create constant variable whose value cannot be changed.
 To disallow method Overriding
 To prevent inheritance

Final variable
The value of a variable declared as final cannot be changed. Below code depicts the use of final keyword
against a variable.
final int x=7;
x++; // Compilation error, x is final
System.out.println(x); // Compilation error, x is final
Here x is declared as final, hence its value cannot be modified.

final method
While method overriding is one of Java’s most powerful features, there will be times where we will want to
prevent it from occurring. To disallow a method from being overridden, specify final as a modifier at the start
of its declaration. Methods declared as final cannot be overridden.
Final methods can’t be overridden
class A
{
final void meth()
{
System.out.println("This is a final method.");
}
}
class B extends A
{
void meth()
{
System.out.println("Illegal!");
}
}
Because meth ( ) is declared as final, it cannot be overridden in B. If you attempt to do so, a compile-

91 time error will result.


JAVA Programming By Sourav Kumar Giri 2020

final class
Sometimes we want to prevent a class from being inherited. To do this, precede the class declaration with
the keyword final. Declaring a class as final implicitly declares all of its methods as final, too.

Final class can’t be inherited


final class A
{
// ...
}
// The following class is illegal.
class B extends A
{
// ERROR! Can't subclass A
// ...
}
**********
As the comments imply, it is illegal for B to inherit A since A is declared as final.

*************

92
JAVA Programming By Sourav Kumar Giri 2020

Practice Questions
1. Choose the most appropriate answer:
a) Static polymorphism is also known as
a) Compile time polymorphism b) Early binding
c) both a) and b) d) None of these

b) Dynamic polymorphism is also known as


a) Run time polymorphism b) late binding
c) both a) or b) d) None of these

c) Method overloading is an example of


a) Static polymorphism b) Structure
c) Inheritance d) Polymorphism

d) Which one of the following is/ are examples of low level language?
a) Assembly language b) Machine Language
c) JAVA d) Both a) and b)

e) Which one of the following is/ are OOPs characteristics?


a) Inheritance b) Data hiding
c) Encapsulation d) All of these

f) The property of OOPs by which an entity can acquire multiple forms is known as
a) Inheritance b) Polymorphism
c) Encapsulation d) Data Aggregation

g) The act of representing essential feature of a class without specifying its complete details is
known as
a) Inheritance b) Polymorphism
c) Data Encapsulation d) Data Abstraction

h) The act of wrapping data and methods into a single unit is known as
a) Inheritance b) Polymorphism
c) Data Encapsulation d) Data Abstraction

i) The technique by which object of one class acquires the properties of object of some other
class is known as
a) Inheritance b) Polymorphism
c) Data Encapsulation d) Data Abstraction

j) What is use of interpreter?


a) They convert byte code to machine language code
b) They read high level code and execute them
c) They are intermediated between JIT and JVM
d) It is a synonym for JIT

93
JAVA Programming By Sourav Kumar Giri 2020

k) The technique by which object of one class acquires the properties of object of some other
class is known as
a) Inheritance b) Polymorphism
c) Data Encapsulation d) Data Abstraction

Short Type
2. Answer briefly
a) What is polymorphism?
b) Define early binding. How it can be achieved?
c) Define late binding. How it can be achieved?
d) Can we inherit a final class?
e) What is abstract class?

Long Type
3. Answer in details
a) What is polymorphism? Explain with a programming example how dynamic method dispatch (DMD)
is used in java to achieve dynamic polymorphism.
b) What is method overriding? Explain with the help of a suitable example.
c) What is method overloading? Explain with the help of a programming example.
d) With the help of suitable examples, explain the uses of final keyword in java.

************

94
JAVA Programming By Sourav Kumar Giri 2020

Chapter 7 String
String
In Java, string is basically an object that represents sequence of char values. An array of characters works
same as Java string.
For example:
char[] ch={'j','a','v','a' };
String s=new String(ch); is same as
String s="java";
Java String class provides a lot of methods to perform operations on string such as compare(), concat(),
equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.
The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.

CharSequence Interface
The CharSequence interface is used to represent the sequence of characters. String, StringBuffer and
StringBuilder classes this interface it. It means, we can create strings in java by using these three classes.
Note: The Java String is immutable which means it cannot be changed. Whenever we change any string, a
new instance is created. For mutable strings, we can use StringBuffer and StringBuilder classes.

What is String in java?


Generally, String is a sequence of characters. But in Java, string is an object that represents a sequence of
characters. The java.lang.String class is used to create a string object. There are two ways to create String
object:
 By string literal
 By new keyword

String Literal
Java String literal is created by using double quotes. For Example:
String s="welcome";
Each time we create a string literal, the JVM checks the "string constant pool" first. If the string already exists
in the pool, a reference to the pooled instance is returned. If the string doesn't exist in the pool, a new string
instance is created and placed in the pool. For example:
String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance
In the above example, only one object will be created. Firstly, JVM will not find any string object with the
value "Welcome" in string constant pool, that is why it will create a new object. After that it will find the

95
JAVA Programming By Sourav Kumar Giri 2020

string with the value "Welcome" in the pool, it will not create a new object but will return the reference to
the same instance.
By new keyword
String s=new String ("Welcome"); //creates two objects and one reference variable
In such case, JVM will create a new string object in normal (non-pool) heap memory, and the literal
"Welcome" will be placed in the string constant pool. The variable s will refer to the object in a heap (non-
pool).
public class StringExample
{
public static void main(String args[])
{
//creating string by java string literal
String s1="java";
char ch[]={'s','t','r','i','n','g','s'};
//converting char array to string
String s2=new String(ch);
//creating java string by new keyword
String s3=new String("example");
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
}

Java String class methods


The java.lang.String class provides many useful methods to perform operations on sequence of char values.

Sl Method Description

1 char charAt(int index) returns char value for the particular


index

2 int length() returns string length

3 static String format(String format, Object... args) returns a formatted string.

4 static String format(Locale l, String format, Object... args) returns formatted string with given
locale.

96
JAVA Programming By Sourav Kumar Giri 2020

5 String substring(int beginIndex) returns substring for given begin


index.

6 String substring(int beginIndex, int endIndex) returns substring for given begin
index and end index.

7 boolean contains(CharSequence s) returns true or false after matching


the sequence of char value.

8 static String join(CharSequence delimiter, returns a joined string.


CharSequence... elements)

9 static String join(CharSequence delimiter, Iterable<? returns a joined string.


extends CharSequence> elements)

10 boolean equals(Object another) checks the equality of string with the


given object.

11 boolean isEmpty() checks if string is empty.

12 String concat(String str) concatenates the specified string.

13 String replace(char old, char new) replaces all occurrences of the


specified char value.

14 String replace(CharSequence old, CharSequence new) replaces all occurrences of the


specified CharSequence.

15 static String equalsIgnoreCase(String another) compares another string. It doesn't


check case.

16 String[] split(String regex) returns a split string matching regex.

17 String[] split(String regex, int limit) returns a split string matching regex
and limit.

18 String intern() returns an interned string.

19 int indexOf(int ch) returns the specified char value


index.

20 int indexOf(int ch, int fromIndex) returns the specified char value
index starting with given index.

21 int indexOf(String substring) returns the specified substring index.

97
JAVA Programming By Sourav Kumar Giri 2020

22 int indexOf(String substring, int fromIndex) returns the specified substring index
starting with given index.

23 String toLowerCase() returns a string in lowercase.

24 String toLowerCase(Locale l) returns a string in lowercase using


specified locale.

25 String toUpperCase() returns a string in uppercase.

26 String toUpperCase(Locale l) returns a string in uppercase using


specified locale.

27 String trim() removes beginning and ending


spaces of this string.

28 static String valueOf(int value) converts given type into string. It is


an overloaded method.

Why string objects are immutable in java?


String objects are immutable in java because java uses the concept of string literal. Suppose there are 5
reference variables, all refers to one object "Java". If one reference variable changes the value of the
object, it will be affected to all the reference variables. That is why string objects are immutable in java.

Java StringBuffer class


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

Constructor Description

StringBuffer() creates an empty string buffer with the initial capacity of 16.

StringBuffer(String str) creates a string buffer with the specified string.

StringBuffer(int capacity) creates an empty string buffer with the specified capacity as length.

Important methods of StringBuffer class

98
JAVA Programming By Sourav Kumar Giri 2020

Modifier and Type Method Description

public synchronized append(String s) is used to append the specified string with this string.
StringBuffer The append() method is overloaded like append(char),
append(boolean), append(int), append(float),
append(double) etc.

public synchronized insert(int offset, String is used to insert the specified string with this string at
StringBuffer s) the specified position. The insert() method is
overloaded like insert(int, char), insert(int, boolean),
insert(int, int), insert(int, float), insert(int, double) etc.

public synchronized replace(int startIndex, is used to replace the string from specified startIndex
StringBuffer int endIndex, String and endIndex.
str)

public synchronized delete(int startIndex, is used to delete the string from specified startIndex
StringBuffer int endIndex) and endIndex.

public synchronized reverse() is used to reverse the string.


StringBuffer

public int capacity() is used to return the current capacity.

public void ensureCapacity(int is used to ensure the capacity at least equal to the given
minimumCapacity) minimum.

public char charAt(int index) is used to return the character at the specified position.

public int length() is used to return the length of the string i.e. total
number of characters.

public String substring(int is used to return the substring from the specified
beginIndex) beginIndex.

public String substring(int is used to return the substring from the specified
beginIndex, int beginIndex and endIndex.
endIndex)

What is mutable string?


A string that can be modified or changed is known as mutable string. StringBuffer and StringBuilder classes
are used for creating mutable string.

99
JAVA Programming By Sourav Kumar Giri 2020

StringBuffer append() method


The append() method concatenates the given argument with this string.
class StringBufferExample
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}

StringBuffer insert() method


The insert() method inserts the given string with this string at the given position.
class StringBufferExample2
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}

StringBuffer replace() method


The replace() method replaces the given string from the specified beginIndex and endIndex.
class StringBufferExample3
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}

100
JAVA Programming By Sourav Kumar Giri 2020

StringBuffer delete() method


The delete() method of StringBuffer class deletes the string from the specified beginIndex to endIndex.
class StringBufferExample4
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}

StringBuffer reverse() method


The reverse() method of StringBuilder class reverses the current string.
class StringBufferExample5
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}

StringBuffer capacity() method


The capacity() method of StringBuffer class returns the current capacity of the buffer. The default capacity of
the buffer is 16. If the number of character increases from its current capacity, it increases the capacity by
(oldcapacity*2)+2. For example if our current capacity is 16, it will be (16*2)+2=34.
class StringBufferExample6
{

101
JAVA Programming By Sourav Kumar Giri 2020

public static void main(String args[])


{
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}

StringBuffer ensureCapacity() method


The ensureCapacity() method of StringBuffer class ensures that the given capacity is the minimum to the
current capacity. If it is greater than the current capacity, it increases the capacity by (oldcapacity*2)+2. For
example if your current capacity is 16, it will be (16*2)+2=34.
class StringBufferExample7
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity()); //default 16
sb.append("Hello");
System.out.println(sb.capacity()); //now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity()); //now (16*2)+2=34
sb.ensureCapacity(10); //now no change
System.out.println(sb.capacity()); //now 34
sb.ensureCapacity(50); //now (34*2)+2
System.out.println(sb.capacity()); //now 70
}
}

Java StringBuilder class


Java StringBuilder class is used to create mutable (modifiable) string. The Java StringBuilder class is same as
StringBuffer class except that it is non-synchronized. It is available since JDK 1.5.

102
JAVA Programming By Sourav Kumar Giri 2020

Important Constructors of StringBuilder class

Constructor Description

StringBuilder() creates an empty string Builder with the initial capacity of 16.

StringBuilder(String str) creates a string Builder with the specified string.

StringBuilder(int length) creates an empty string Builder with the specified capacity as length.

Important methods of StringBuilder class

Method Description

public StringBuilder is used to append the specified string with this string. The append()
append(String s) method is overloaded like append(char), append(boolean),
append(int), append(float), append(double) etc.

public StringBuilder insert(int is used to insert the specified string with this string at the specified
offset, String s) position. The insert() method is overloaded like insert(int, char),
insert(int, boolean), insert(int, int), insert(int, float), insert(int,
double) etc.

public StringBuilder replace(int is used to replace the string from specified startIndex and endIndex.
startIndex, int endIndex, String
str)

public StringBuilder delete(int is used to delete the string from specified startIndex and endIndex.
startIndex, int endIndex)

public StringBuilder reverse() is used to reverse the string.

public int capacity() is used to return the current capacity.

public void ensureCapacity(int is used to ensure the capacity at least equal to the given minimum.
minimumCapacity)

public char charAt(int index) is used to return the character at the specified position.

public int length() is used to return the length of the string i.e. total number of
characters.

103
JAVA Programming By Sourav Kumar Giri 2020

public String substring(int is used to return the substring from the specified beginIndex.
beginIndex)

public String substring(int is used to return the substring from the specified beginIndex and
beginIndex, int endIndex) endIndex.

Let's see the examples of different methods of StringBuilder class.


StringBuilder append() method
The StringBuilder append() method concatenates the given argument with this string.
class StringBuilderExample
{
public static void main(String args[])
{
StringBuilder sb=new StringBuilder("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}

StringBuilder insert() method


The StringBuilder insert() method inserts the given string with this string at the given position.
class StringBuilderExample2
{
public static void main(String args[])
{
StringBuilder sb=new StringBuilder("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}

StringBuilder replace() method


The StringBuilder replace() method replaces the given string from the specified beginIndex and endIndex.
class StringBuilderExample3

104
JAVA Programming By Sourav Kumar Giri 2020

{
public static void main(String args[])
{
StringBuilder sb=new StringBuilder("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}

StringBuilder delete() method


The delete() method of StringBuilder class deletes the string from the specified beginIndex to endIndex.
class StringBuilderExample4
{
public static void main(String args[])
{
StringBuilder sb=new StringBuilder("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}

StringBuilder reverse() method


The reverse() method of StringBuilder class reverses the current string.
class StringBuilderExample5
{
public static void main(String args[])
{
StringBuilder sb=new StringBuilder("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}

StringBuilder capacity() method

105
JAVA Programming By Sourav Kumar Giri 2020

The capacity() method of StringBuilder class returns the current capacity of the Builder. The default capacity
of the Builder is 16. If the number of character increases from its current capacity, it increases the capacity
by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.
class StringBuilderExample6
{
public static void main(String args[])
{
StringBuilder sb=new StringBuilder();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}

StringBuilder ensureCapacity() method


The ensureCapacity() method of StringBuilder class ensures that the given capacity is the minimum to the
current capacity. If it is greater than the current capacity, it increases the capacity by (oldcapacity*2)+2. For
example if your current capacity is 16, it will be (16*2)+2=34.
class StringBuilderExample7
{
public static void main(String args[])
{
StringBuilder sb=new StringBuilder();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
sb.ensureCapacity(10);//now no change
System.out.println(sb.capacity());//now 34
sb.ensureCapacity(50);//now (34*2)+2
System.out.println(sb.capacity());//now 70

106
JAVA Programming By Sourav Kumar Giri 2020

}
}

StringTokenizer in Java
The java.util.StringTokenizer class allows you to break a string into tokens. It is simple way to break string.
It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like StreamTokenizer
class. There are 3 constructors defined in the StringTokenizer class.

Constructor Description

StringTokenizer(String str) creates StringTokenizer with specified string.

StringTokenizer(String str, String delim) creates StringTokenizer with specified string and delimeter.

StringTokenizer(String str, String delim, creates StringTokenizer with specified string, delimeter and
boolean returnValue) returnValue. If return value is true, delimiter characters are
considered to be tokens. If it is false, delimiter characters
serve to separate tokens.

Methods of StringTokenizer class


The 6 useful methods of StringTokenizer class are as follows:

Public method Description

boolean hasMoreTokens() checks if there is more tokens available.

String nextToken() returns the next token from the StringTokenizer object.

String nextToken(String delim) returns the next token based on the delimeter.

boolean hasMoreElements() same as hasMoreTokens() method.

Object nextElement() same as nextToken() but its return type is Object.

int countTokens() returns the total number of tokens.

Wrapper Classes in Java


A Wrapper class is a class whose object wraps or contains a primitive data types. When we create an object
to a wrapper class, it contains a field and in this field, we can store a primitive data types. In other words, we
can wrap a primitive value into a wrapper class object.
Need of Wrapper Classes

107
JAVA Programming By Sourav Kumar Giri 2020

 They convert primitive data types into objects. Objects are needed if we wish to modify the
arguments passed into a method (because primitive types are passed by value).
 The classes in java.util package handles only objects and hence wrapper classes help in this case also.
 Data structures in the Collection framework, such as ArrayList and Vector, store only objects
(reference types) and not primitive types.
 An object is needed to support synchronization in multithreading.

Primitive Data types and their Corresponding Wrapper class


Primitive Data Type Wrapper Class
char Character
byte Byte
short Short
int Integer
float Float
double Double
boolean Boolean

Autoboxing
The automatic conversion of primitive data type into its corresponding wrapper class is known as
autoboxing, for example, byte to Byte, char to Character, int to Integer, long to Long, float to Float, boolean to
Boolean, double to Double, and short to Short.
Since Java 5, we do not need to use the valueOf() method of wrapper classes to convert the primitive into
objects.
//Autoboxing example of int to Integer
public class WrapperExample1
{
public static void main(String args[])
{
//Converting int into Integer
int a=20;
Integer i=Integer.valueOf(a);//converting int into Integer explicitly
Integer j=a;//autoboxing
System.out.println(a+" "+i+" "+j);
}

108
JAVA Programming By Sourav Kumar Giri 2020

Unboxing
The automatic conversion of wrapper type into its corresponding primitive type is known as unboxing. It is
the reverse process of autoboxing. Since Java 5, we do not need to use the intValue() method of wrapper
classes to convert the wrapper type into primitives.
//Unboxing example of Integer to int
public class WrapperExample2
{
public static void main(String args[])
{
//Converting Integer to int
Integer a=new Integer(3);
int i=a.intValue();//converting Integer to int explicitly
int j=a;//unboxing, now compiler will write a.intValue() internally
System.out.println(a+" "+i+" "+j);
}
}

*************

109
JAVA Programming By Sourav Kumar Giri 2020

Practice Questions
1. Choose the most appropriate answer:
a) Which of the following object is immutable?
a) String b) StringBuffer
c) StringBuilder d) All of these

b) The automatic conversion of wrapper type into its corresponding primitive type is known as
a) Unboxing b) Autoboxing
c) Either a) or b) d) None of these

c) Wrapper class of the data type int is


a) Integer b) Int
c) INT d) Number

d) The automatic conversion of primitive data type into its corresponding wrapper class is
known as
a) Unboxing b) Autoboxing
c) Either a) or b) d) None of these

e) Which one of the following classe(s) is/are used to create mutable string?
a) String b) StringBuffer
c) StringBuilder d) Both b) and c)

f) Which of this class is superclass of String and StringBuffer class?


a) java.io b) java.util
c) java.lang d) java.awt

g) What is the output?


class String_demo
{
public static void main(String args[])
{
int ascii[] = { 65, 66, 67, 68};
String s = new String(ascii, 1, 3);
System.out.println(s);
}
}
a) ABC b) BCD
c) ABCD d) DBC

h) Which of this method of class String is used to obtain a length of String object?
a) length() b) strlen()
c) lengthof() d) len()

i) Class used to convert primitive data types into object is called


a) Wrapper class b) Abstract class

110
JAVA Programming By Sourav Kumar Giri 2020

c) Adapter class d) None of these

j) What is package contains StringTokenizer class?


a) java.io b) java.util
c) java.lang d) java.awt

k) Which of the following String class method is used to remove all leading and trailing white
spaces?
a) trim() b) remove()
c) remw() d) delete()

Short Type
2. Answer briefly
a) Define string.
b) Why java String is immutable?
c) Name the classes used to create mutable string in java.
d) Define autoboxing and unboxing.
e) What is wrapper class? What are the needs of a wrapper class?
f) Differentiate between StringBuffer and StringBuilder class
g) Write the uses of StringTokenizer class

Long Type
3. Answer in details
a) What are wrapper classes in java? Explain autoboxing & unboxing in java with the help of suitable
programming example.
b) Define string. Explain different methods used in java to create strings. Which methods are used to
create mutable string?

*************

111
JAVA Programming By Sourav Kumar Giri 2020

Chapter 8 PACKAGE AND INTERFACE


Package
 Packages are containers for classes that are used to keep the class name space compartmentalized.
 For example, a package allows us to create a class named List, which we can store in our own package
without concern that it will collide with some other class named List stored elsewhere.
 Packages are stored in a hierarchical manner and are explicitly imported into new class definitions.

Defining a Package
Creating a package is a quite easy task. Simply include a package command as the first statement in a Java
source file. Any classes declared within that file will belong to the specified package.
The package statement defines a name space in which classes are stored. If we omit the package statement,
the class names are put into the default package, which has no name (This is why we haven’t had to worry
about packages before now).
While the default package is fine for short, sample programs, it is inadequate for real applications. Most of
the time, we will define a package for our code.

Syntax to create a package:


package package_name;
Here, package_name is the name of the package.

Program 8.1: Write a program to define a package.


Solution:
package MyPackage;
package MyPack;
class Balance
{
String name;
double bal;
Balance(String n, double b)
{
name = n;
bal = b;
}
void show()
{

112
JAVA Programming By Sourav Kumar Giri 2020

if(bal<0)
System.out.print("--> "); JAVA LANGUAGE
System.out.println(name + ": $" + bal);
}
}
class AccountBalance
{
public static void main(String args[])
{
Balance current[] = new Balance[3];
current[0] = new Balance("Kabya", 123.23);
current[1] = new Balance("Adrika", 157.02);
current[2] = new Balance("Kaju", -12.33);
for(int i=0; i<3; i++)
current[i].show();
}
}

Output:
Kabya: 123.23
Adrika: 157.02
--> Kaju: -12.33

How to run above program


Call this file AccountBalance.java, and put it in a directory called MyPack. Next, compile the file. Make sure
that the resulting .class file is also in the MyPack directory. Then try executing the AccountBalance class,
using the following command line:
java MyPack.AccountBalance

Remember, we will need to be in the directory above MyPack when we execute this command, or to have our
CLASSPATH environmental variable set appropriately. As explained, AccountBalance is now part of the
package MyPack. This means that it cannot be executed by itself. That is, we cannot use this command line:
java AccountBalance
AccountBalance must be qualified with its package name.

113
JAVA Programming By Sourav Kumar Giri 2020

Access Protection

Below table depicts the accession protection of classes used in package


Below table depicts the access protection of class from another class or package.
Private Default Protected Public
No Modifier

Same class Yes Yes Yes Yes


Same package subclass No Yes Yes Yes
Same package non-subclass No Yes Yes Yes
Different package subclass No No Yes Yes
Different package non-subclass No No No Yes

Importing user defined packages


Given that packages exist and are a good mechanism for compartmentalizing diverse classes from each other,
it is easy to see why all of the built-in Java classes are stored in packages.
In a Java source file, import statements occur immediately following the package statement (if it exists) and
before any class definitions.

Syntax of import statement:


import pkg1 [.pkg2].(classname|*);

Program 8.2: Write a program to demonstrate the use of import statement.


Solution:
//Package definition program
package MyPack;
public class Balance
{
String name;
double bal;
public Balance(String n, double b)
{
name = n;
bal = b;
}

114
JAVA Programming By Sourav Kumar Giri 2020

public void show()


{
if(bal<0)
System.out.print("--> ");
System.out.println(name + ": $" + bal);
}
}
As we can see, the Balance class is now public. Also, its constructor and its show( ) method are public, too.
This means that they can be accessed by any type of code outside the MyPack package.
For example, here TestBalance imports MyPack and is then able to make use of the Balance class:
//Driver program to import above package
import MyPack.*;
class TestBalance
{
public static void main(String args[])
{
Balance test = new Balance("J. J. Jaspers", 99.88);
test.show(); // you may also call show()
}
}

Output:
J. J. Jaspers: 99.88

Interface
 An interface is a collection of abstract methods (i.e. methods without having definition).
 A class that implements an interface inherits abstract methods of the interface.
 An interface is not a class.
 Writing an interface is similar to writing a class, but they differ in concepts.
 A class describes both attributes (i.e. variables) and behaviors (i.e. methods) of an object.
 An interface contains only behaviors (i.e. methods) that a class implements.
 If a class (provided it is not abstract) implements an interface, then all the methods of interface need to
be defined in it.

115
JAVA Programming By Sourav Kumar Giri 2020

Syntax to declare an interface:


public interface NameOfInterface
{
//Any number of final, static variables
//Any number of abstract method declarations
}

Properties of an interface
 An interface is implicitly (i.e. by default) abstract. We do not need to use the abstract keyword when
declaring an interface.
 Each method in an interface is also implicitly (i.e. by default) abstract, so the abstract keyword is not
needed.
 Methods in an interface are implicitly (i.e. by default) public.
 A class can implement more than one interface at a time.
 A class can extend only one class, but can implement many interfaces.
 An interface itself can extend another interface.

The general form of a class that includes the implements clause looks like this:
class classname extends superclass implements interface1, interface2...
{
// class-body
}

Program 8.3: Write a program to demonstrate the use of interface.


Solution:
interface Message
{
void message1();
void message2();
}
class A implements Message
{
void message1()
{
System.out.println("Good Morning");

116
JAVA Programming By Sourav Kumar Giri 2020

}
void message2()
{
System.out.println("Good Evening");
}
public static void main(String args[])
{
A a=new A();
a.message1();
a.message2();
}
}

Output:
Good Morning
Good Evening

Similarities between class and interface


 Both class and interface can contain any number of methods.
 Both class and interface are written in a file with a .java extension, with the name of the interface
matching the name of the file.
 The bytecode of both class and interface appears in a .class file.

Dissimilarities between class and interface


 We cannot instantiate (i.e. create object) an interface but we can instantiate a class.
 An interface does not contain any constructors but a class may contain any constructors.
 All the methods in an interface are abstract (i.e. without definitions) but in a class method may or may
not be abstract.
 An interface cannot contain variables. The only variable that can appear in an interface must be declared
both static and final. But a class can contain any variable.
 An interface is not extended by a class; it is implemented by a class.
 An interface can extend multiple interfaces (i.e. multiple inheritances can be achieved through it). But a
class cannot extend multiple classes (i.e multiple inheritance can not be achieved).

117
JAVA Programming By Sourav Kumar Giri 2020

Variables in Interfaces
 We can use interfaces to import shared constants into multiple classes by simply declaring an interface
that contains variables which are initialized to the desired values.
 When we include that interface in a class (that is, when we “implement” the interface), all of those
variable names will be in scope as constants. This is similar to using a header file in C/C++ to create a
large number of #defined constants or const declarations.
Note: If an interface contains no methods, then any class that includes such an interface doesn’t actually
implement anything.

Program 8.4: Write a program to demonstrate the use of interface without any abstract methods.
Solution:
interface SharedConstants
{
int X = 0;
int Y = 1;
}
class A implements SharedConstants
{
static void show()
{
System.out.println(“X=”+x+”and Y=”+y);
}
public static void main(String args[])
{
A a = new A();
show();
}
}

Output:
X=0 and Y=1

118
JAVA Programming By Sourav Kumar Giri 2020

Interfaces Can Be Extended


 One interface can inherit another by use of the keyword extends. The syntax is the same as for inheriting
classes.
 When a class implements an interface that inherits another interface, it must provide implementations
for all methods defined within the interface inheritance chain. This feature can be used to achieve
multiple inheritance in java through interfaces.
Program 8.5: Write a program to demonstrate the use of interface extending another interface.
Solution:
interface A
{
void meth1();
void meth2();
}
interface B extends A
{
void meth3();
}
class MyClass implements B
{
public void meth1()
{
System.out.println("Implement meth1().");
}
public void meth2()
{
System.out.println("Implement meth2().");
}
public void meth3()
{
System.out.println("Implement meth3().");
}
}
class IFExtend
{
public static void main(String arg[])

119
JAVA Programming By Sourav Kumar Giri 2020

{
MyClass ob = new MyClass();AVA LANGUAGE
ob.meth1();
ob.meth2();
ob.meth3();
}
}

Output:
Implement meth1().
Implement meth1().
Implement meth1().

**************

120
JAVA Programming By Sourav Kumar Giri 2020

Practice Questions
1. Choose the most appropriate answer:
a) Which of these keywords is used to define packages in Java?
a) pkg b) Pkg
c) package d) Package

b) Which of this access specifies can be used for a class so that its members can be accessed by a
different class in the same package?
a) Public b) Protected
c) No Modifier d) All of the mentioned

c) Which of these access specifiers can be used for a class so that its members can be accessed by
a different class in the different package?
a) Public b) Protected
c) Private d) No Modifier

d) Which of the following is the correct way of importing an entire package ‘pkg’?
a) import pkg. b) Import pkg.
c) import pkg.* d) Import pkg.*

e) Which of these can be used to fully abstract a class from its implementation?
a) Objects b) Packages
c) Interfaces d) None of the Mentioned

f) Which of these access specifiers can be used for an interface?


a) Public b) Protected
c) private d) All of the mentioned

g) Which of these keywords is used by a class to use an interface defined previously?


a) import b) Import
c) implements d) Implements

h) Which of the following is the correct way of implementing an interface salary by class
manager?
a) class manager extends salary {}
b) class manager implements salary {}
c) class manager imports salary {}
d) none of the mentioned

i) ava What type of methods an interface contain by default?


a) abstract b) static
c) final d) private

121
JAVA Programming By Sourav Kumar Giri 2020

Short Type
2. Answer briefly
a) Define package.
b) Define Interface.
c) Is the following interface valid?
public interface Marker
{
}
d) Which package is always imported by default in a java program?

Long Type
3. Answer in details
a) Discuss the difference between a class and an interface.
b) Differentiate between interface and abstract class.
c) Java supports multiple inheritances through interface. Discuss.
d) Explain the usage of Java packages.
*************

122
JAVA Programming By Sourav Kumar Giri 2020

Chapter 9 EXCEPTION HANDLING


Error & Exception
 Error occurred in a program can be of two types: syntax error and logical error.
 Syntax errors are also known as compile time error which mainly occurs during the compilation of a
program. These arises mainly due to improper syntax in our program like missing semi colon,
misbalanced parenthesis, wrongly spelled keywords, illegal identifiers etc.
 Logical errors are also known as run time errors or exceptions. An exception is an abnormal condition
that arises in a code sequence at run time.
 A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a
piece of code.
 Exception Handling is a mechanism by which exception occurred in a program is handled.
 Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.
Keyword/Block Meaning
try block The statements which are expected to throw exception are kept inside try block.

catch block If an exception occurs within the try block, it is throws an exception to the catch
block which handle it in some rational manner.

throw To manually throw an exception, use the keyword throw.


throws A throws clause lists the types of exceptions that a method might throw.
finally Any code that absolutely must be executed before a method returns is put in a
finally block.

Execution Flow of the try, catch and finally block

Try block

finally Catch block

finally

123
JAVA Programming By Sourav Kumar Giri 2020

The general form of an exception handling block is:


try
{
// block of code to monitor for errors
}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb)
{
// exception handler for ExceptionType2
}


finally
{
// block of code to be executed before try block ends
}

Checked vs Unchecked Exceptions in Java


In Java, there are two types of exceptions: checked & unchecked.
Checked Exception
Checked Exceptions are the exceptions that are checked at compile time. If some code within a method
throws a checked exception, then the method must either handle the exception or it must specify the
exception using throws keyword.
For example, consider the following Java program that opens file at location “C:\test\a.txt” and prints the
first three lines of it. The program doesn’t compile, because the function main() uses FileReader() and
FileReader() throws a checked exception FileNotFoundException. It also uses readLine() and close()
methods, and these methods also throw checked exception IOException.

Unchecked Exception
Unchecked exceptions are the exceptions that are not checked at compiled time. In C++, all exceptions are
unchecked, so it is not forced by the compiler to either handle or specify the exception. It is up to the
programmers to be civilized, and specify or catch the exceptions.
In Java exceptions under Error and RuntimeException classes are unchecked exceptions, everything else
under throwable is checked.

124
JAVA Programming By Sourav Kumar Giri 2020

Java’s Built-in Exceptions


Inside the standard package java.lang, Java defines several exception classes. The most general of these
exceptions,are subclasses of the standard type RuntimeException. Since java.lang is implicitly,imported into
all Java programs, most exceptions derived from RuntimeException are automatically available.
All exception types are subclasses of the built-in class Throwable. Thus, Throwable is at the top of the
exception class hierarchy. The Throwable class has two subclasses Error and Exception.
Error and Exception classes are used for handling errors in java.

Object

Throwable

Error Exception

AWT Error SQL Exception Runtime Exception

Thread ClassNotFoundException ArithmaticEception


Death
… … Number Format

Below table depicts a partial list of java’s built-in exception:


Exception Meaning
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException Assignment to an array element of an incompatible type.
ClassCastException Invalid cast.
IllegalArgumentException Illegal argument used to invoke a method.
IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked
thread.
IllegalStateException Environment or application is in incorrect state.
IllegalThreadStateException Requested operation not compatible with current thread state
IndexOutOfBoundsException Some type of index is out-of-bounds.
NegativeArraySizeException Array created with a negative size.

125
JAVA Programming By Sourav Kumar Giri 2020

Program 9.1: Write a java program to demonstrate uncaught exception.


Solution:
class E
{
public static void main(String args[])
{
int x = 0;
int y = 1 / x;
}
}

Output
Exception in thread “main” java.lang.ArithmeticException: / by zero

Program 9.2: Write a program to demonstrate division by zero exception using try catch block.
Solution:
class Ex
{
public static void main(String args[])
{
int x, y;
try
{
x = 0;
y= 1/ x;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e)
{
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}

126
JAVA Programming By Sourav Kumar Giri 2020

Output:
Division by zero.
After catch statement.

Notice that the call to println ( ) inside the try block is never executed. Once an exception is thrown, program
control transfers out of the try block into the catch block. Put differently, catch is not “called,” so execution
never “returns” to the try block from a catch. Thus, the line “This will not be printed.” is not displayed. Once
the catch statement has executed, program control continues with the next line in the program following the
entire try/catch mechanism.

Multiple catch blocks


In some cases, more than one exception could be raised by a single piece of code. To handle this type of
situation, you can specify two or more catch clauses, each catching a different type of exception. When an
exception is thrown, each catch statement is inspected in order, and the first one whose type matches that of
the exception is executed. After one catch statement executes, the others are bypassed, and execution
continues after the try/catch block. The following example traps two different exception types:

Program 9.3: Write a program to demonstrate the use of multiple catch blocks in exception handling.
Solution:
class MultiCatch
{
public static void main(String args[])
{
try
{
int a = args.length;
System.out.println("a = " + a);
int b = 1 / a;
int c[] = { 1 };
c[42] = 99;
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}

127
JAVA Programming By Sourav Kumar Giri 2020

catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}
This program will cause a division-by-zero exception if it is started with no command line parameters, since
a will equal zero. It will survive the division if you provide a command-line argument, setting a to something
larger than zero. But it will cause an ArrayIndexOutOfBoundsException, since the int array c has a length
of 1, yet the program attempts to assign a value to c[42].

Output:
C:\>java MultiCatch
a=0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.
C:\>java MultiCatch TestArg
a=1
Array index oob: java.lang.ArrayIndexOutOfBoundsException
After try/catch blocks.

throw statement
So far, you have only been catching exceptions that are thrown by the Java run-time system. However, it is
possible for our program to throw an exception explicitly, using the throw statement. The general form of
throw is shown here:
throw ThrowableInstance;
Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable.

Program 9.4: Write a program to demonstrate the use throw statement in exception handling.
Solution:
class ThrowDemo
{
public static void main(String args[])
{

128
JAVA Programming By Sourav Kumar Giri 2020

int x=2, y=0;


try
{
if(y==0)
throw new ArithmeticException();
}
catch(ArithmeticException e)
{
System.out.println("Exception Occurred: Division by 0 " + e);
}
}
}
Output:
Exception Occurred: Division by 0 java.lang.ArithmeticException

throws statement
If a method is capable of causing an exception that it does not handle, it must specify this behavior so that
callers of the method can guard themselves against that exception. We do this by including throws clause in
the method's declaration. A throws clause lists the types of exceptions that a method might throw.

Syntax a method declaration that includes a throws clause:


return_type method-name (parameter-list) throws exception-list
{
//body of method
}

Program 9.5: Write a program to demonstrate the use throws statement in exception handling.
Solution:
class ThrowsDemo
{
static void throwOne() throws IllegalAccessException
{
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}

129
JAVA Programming By Sourav Kumar Giri 2020

public static void main(String args[])


{
try
{
throwOne();
}
catch (IllegalAccessException e)
{
System.out.println("Caught " + e);
}
}
}

Output:
Inside throwOne.
Caught java.lang.IllegalAccessException:demo

finally block
 finally creates a block of code that will be executed after a try/catch block has completed and before the
code following the try/catch block.
 The finally block will execute whether or not an exception is thrown.
 If an exception is thrown, the finally block will execute even if no catch statement matches the exception.
Program 9.6: Write a program to demonstrate the use finally block in exception handling.
Solution:
class Ex
{
public static void main(String args[])
{
int x, y;
try
{
x = 0;
y= 1/ x;
System.out.println("This will not be printed.");
}

130
JAVA Programming By Sourav Kumar Giri 2020

catch (ArithmeticException e)
{
System.out.println("Division by zero.");
}
finally
{
System.out.println("End of Try/Catch Block");
}
}
}

Output:
Division by zero.
End of Try/catch Block

User Defined Exceptions


Although Java’s built-in exceptions handle most common errors, we will probably want to create our own
exception types to handle situations specific to your applications.
This is quite easy to do: just define a subclass of Exception (which is, of course, a subclass of Throwable).

Program 9.7: Write a program to demonstrate user defined exception in java.


Solution:
class MyException extends Exception
{
private int detail;
MyException(int a)
{
detail = a;
}
public String toString()
{
return "MyException[" + detail + "]";
}
}
class ExceptionDemo

131
JAVA Programming By Sourav Kumar Giri 2020

{
static void compute(int a) throws MyException
{
System.out.println("Called compute(" + a + ")");
if(a > 10)
throw new MyException(a);
System.out.println("Normal exit");
}
public static void main(String args[])
{
try
{
compute(1);
compute(20);
}
catch (MyException e)
{
System.out.println("Caught " + e);
}
}
}

Output:
Called compute(1)
Normal exit
Called compute(20)
Called MyException[20]

**********

132
JAVA Programming By Sourav Kumar Giri 2020

Practice Questions
1. Choose the most appropriate answer:
a) Which of these keywords is not a part of exception handling?
a) try b) finally
c) thrown d) catch

b) Which of these keywords is used to manually throw an exception?


a) try b) finally
c) throw d) catch

c) Which of these keywords must be used to monitor for exceptions?


a) try b) finally
c) throw d) catch

d) Error & Exception are the sub class of


a) Throwable b) Object
c) Error d) Exception

Short Type
2. Answer briefly
a) Differentiate error and exception.
b) What is exception handling mechanism?
c) Can a try block stand alone? Explain with an example.
d) Name the super class of error and exception class.
e) What are Java’s built-in exceptions?
f) Name 5 keywords used to handle exception in java.
g) Differentiate between final, finalize and finally.
h) What is ArrayIndexOutOfBoundsException?
i) Which block is always executed, no matter whether exception occurs or not?
a) try b) catch c)finally d)finalize

Long Type
3. Answer in details
a) Discuss exception handling mechanism.
b) Write a program to evaluate x/y, where x and y are integers using exception handling mechanism.
c) Discuss user defined exception in java with an example.
d) Explain the meaning of each keyword: try, catch, throw, throws and finally.
*************

133
JAVA Programming By Sourav Kumar Giri 2020

Chapter 10 MULTITHREADING
Thread
 A multithreaded program contains two or more parts that can run concurrently. Each part of such a
program is called a thread, and each thread defines a separate path of execution. Thus, multithreading is
a specialized form of multitasking.
 There are two distinct types of multitasking: process-based and thread-based.
 A process-based multitasking is the feature that allows our computer to run two or more programs
concurrently. For example, process-based multitasking enables us to run the Java compiler at the same
time that we are using a music player.
 In a thread-based multitasking environment, the thread is the smallest unit of dispatchable code. This
means that a single program can perform two or more tasks simultaneously.
 Multitasking threads require less overhead than multitasking processes.
 Multithreading enables us to write very efficient programs that make maximum use of the CPU, because
idle time can be kept to a minimum.

Life Cycle of a Thread


A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then
dies. Following diagram shows complete life cycle of a thread.

New

Runnable

Waiting Timed Waiting Terminated

New: A new thread begins its life cycle in the new state. It remains in this state until the program starts the
thread. It is also referred to as a born thread.
Runnable: After a newly born thread is started, the thread becomes runnable. A thread in this state is
considered to be executing its task.
Waiting: Sometimes a thread transitions to the waiting state while the thread waits for another thread to
perform a task. A thread transitions back to the runnable state only when another thread signals the waiting
thread to continue executing.

134
JAVA Programming By Sourav Kumar Giri 2020

Timed waiting: A runnable thread can enter the timed waiting state for a specified interval of time. A thread
in this state transition back to the runnable state when that time interval expires or when the event it is
waiting for occurs.
Terminated: A runnable thread enters the terminated state when it completes its task or otherwise
terminates.

Thread Priority
 Java assigns to each thread a priority that determines how that thread should be treated with respect to
the others.
 Thread priorities are integers that specify the relative priority of one thread to another.
 Java priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant
of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5).
 Threads with higher priority are more important to a program and should be allocated processor time
before lower-priority threads. However, thread priorities cannot guarantee the order in which threads
execute and very much platform dependentant.
 A thread’s priority is used to decide when to switch from one running thread to the next. This is called a
context switch.

The rules that determine when a context switch takes place are:
 A thread can voluntarily relinquish control. This is done by explicitly yielding, sleeping, or blocking on
pending I/O. In this scenario, all other threads are examined, and the highest-priority thread that is
ready to run is given the CPU.
 A thread can be preempted by a higher-priority thread. In this case, a lower-priority thread that does not
yield the processor is simply preempted—no matter what it is doing—by a higher-priority thread.
Basically, as soon as a higher-priority thread wants to run, it does. This is called preemptive multitasking.

How to create Thread


Java defines two ways in which a thread can be created:
 Implementing the Runnable interface
 Extending the Thread class

Creating Thread by Implementing Runnable interface


The easiest way to create a thread is to create a class that implements the Runnable interface.
To implement Runnable, a class need only implement a single method called run( ), which is declared like
this:

135
JAVA Programming By Sourav Kumar Giri 2020

public void run( )

We will define the code that constitutes the new thread inside run() method. It is important to understand
that run() can call other methods, use other classes, and declare variables, just like the main thread can.
After we create a class that implements Runnable, you will instantiate an object of type Thread from within
that class. Thread defines several constructors. The one that we will use is shown here:

Thread(Runnable threadOb, String threadName)

Here threadOb is an instance of a class that implements the Runnable interface and the name of the new
thread is specified by threadName.
After the new thread is created, it will not start running until you call its start( ) method, which is declared
within Thread. The start( ) method is shown here:

void start( );

Program 10.1: Write a program in java to create thread by implementing Runnable interface.
Solution:
class NewThread implements Runnable
{
Thread t;
NewThread()
{
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start();
}
public void run()
{
try
{
for(int i = 5; i > 0; i--)
{
System.out.println("Child Thread: " + i);
Thread.sleep(500);

136
JAVA Programming By Sourav Kumar Giri 2020

}
}
catch (InterruptedException e)
{
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class ThreadDemo
{
public static void main(String args[])
{
new NewThread();
try
{
for(int i = 5; i > 0; i--)
{
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
Output

137
JAVA Programming By Sourav Kumar Giri 2020

Creating Thread by Extending Thread class


The second way to create a thread is to create a new class that extends Thread, and then to create an
instance of that class. The extending class must override the run () method, which is the entry point for the
new thread. It must also call start () to begin execution of the new thread.
Program 10.2: Write a program in java to create thread by extending Thread class.
Solution:
class NewThread extends Thread
{
NewThread()
{
super("Demo Thread");
System.out.println("Child thread: " + this);
start();
}
public void run()
{
try
{
for(int i = 5; i > 0; i--)
{
System.out.println("Child Thread: " + i);
Thread.sleep(500);

138
JAVA Programming By Sourav Kumar Giri 2020

}
}
catch (InterruptedException e)
{
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class ExtendThread
{
public static void main(String args[])
{
new NewThread();
try
{
for(int i = 5; i > 0; i--)
{
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}

139
JAVA Programming By Sourav Kumar Giri 2020

How to create Multiple Threads


So far, you have been using only two threads: the main thread and one child thread. However, our program
can spawn as many threads as it needs.
Program 10.3: Write a program in java to create multiple threads by implementing Runnable interface.
Solution:
class NewThread implements Runnable
{
String name;
Thread t;
NewThread(String threadname)
{
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
public void run()
{
try
{
for(int i = 5; i > 0; i--)
{
System.out.println(name + ": " + i);
Thread.sleep(1000);

140
JAVA Programming By Sourav Kumar Giri 2020

}
}
catch (InterruptedException e)
{
System.out.println(name + "Interrupted");
}
System.out.println(name + " exiting.");
}
}
class MultiThreadDemo
{
public static void main(String args[])
{
new NewThread("One");
new NewThread("Two");
new NewThread("Three");
try
{
Thread.sleep(10000);
}
catch (InterruptedException e)
{
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}

141
JAVA Programming By Sourav Kumar Giri 2020

Output

As we can see, once started, all three child threads share the CPU. Notice the call to sleep (10000) in main( ).
This causes the main thread to sleep for ten seconds and ensures that it will finish last.

Using isAlive( ) and join( )


Two ways exist to determine whether a thread has finished. First, we can call isAlive( ) on the thread. This
method is defined by Thread, and its general form is shown here:
final boolean isAlive( )
The isAlive( ) method returns true if the thread upon which it is called is still running. It returns false
otherwise. While isAlive( ) is occasionally useful, the method that we will more commonly use to wait for a
thread to finish is called join( ), shown here:

final void join ( ) throws InterruptedException

142
JAVA Programming By Sourav Kumar Giri 2020

This method waits until the thread on which it is called terminates. Its name comes from the concept of the
calling thread waiting until the specified thread joins it. Additional forms of join () allow us to specify a
maximum amount of time that we want to wait for the specified thread to terminate.
Program 10.43 Write a program in java to illustrate isAlive() and join() method in java.
Solution:
class NewThread implements Runnable
{
String name;
Thread t;
NewThread(String threadname)
{
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start();
}
public void run()
{
try
{
for(int i = 5; i > 0; i--)
{
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println(name + " interrupted.");
}
System.out.println(name + " exiting.");
}
}
class DemoJoin

143
JAVA Programming By Sourav Kumar Giri 2020

{
public static void main(String args[])
{
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");
NewThread ob3 = new NewThread("Three");
System.out.println("Thread One is alive: "+ ob1.t.isAlive());
System.out.println("Thread Two is alive: "+ ob2.t.isAlive());
System.out.println("Thread Three is alive: "+ ob3.t.isAlive());
try
{
System.out.println("Waiting for threads to finish.");
ob1.t.join();
ob2.t.join();
ob3.t.join();
}
catch (InterruptedException e)
{
System.out.println("Main thread Interrupted");
}
System.out.println("Thread One is alive: "+ ob1.t.isAlive());
System.out.println("Thread Two is alive: "+ ob2.t.isAlive());
System.out.println("Thread Three is alive: "+ ob3.t.isAlive());
System.out.println("Main thread exiting.");
}
}

Output:
New thread: Thread[One,5,main]
New thread: Thread[Two,5,main]
New thread: Thread[Three,5,main]
Thread One is alive: true
Thread Two is alive: true
Thread Three is alive: true

144
JAVA Programming By Sourav Kumar Giri 2020

Waiting for threads to finish.


One: 5
Two: 5
Three: 5
One: 4
Two: 4
Three: 4
One: 3
Two: 3
Three: 3
One: 2
Two: 2
Three: 2
One: 1
Two: 1
Three: 1
Two exiting.
Three exiting.
One exiting.
Thread One is alive: false
Thread Two is alive: false
Thread Three is alive: false
Main thread exiting.

Synchronization
When two or more threads need access to a shared resource, they need some way to ensure that the
resource will be used by only one thread at a time. The process by which this is achieved is called
synchronization.
Key to synchronization is the concept of the monitor (also called a semaphore). A monitor is an object that is
used as a mutually exclusive lock, or mutex. Only one thread can own a monitor at a given time. When a
thread acquires a lock, it is said to have entered the monitor. All other threads attempting to enter the locked
monitor will be suspended until the first thread exits the monitor. These other threads are said to be waiting
for the monitor. A thread that owns a monitor can reenter the same monitor if it so desires.

Thread synchronization using synchronized Methods

145
JAVA Programming By Sourav Kumar Giri 2020

Synchronization is easy in Java, because all objects have their own implicit monitor associated with them. To
enter an object’s monitor, just call a method that has been modified with the synchronized keyword. While a
thread is inside a synchronized method, all other threads that try to call it (or any other synchronized
method) on the same instance have to wait. To exit the monitor and relinquish control of the object to the
next waiting thread, the owner of the monitor simply returns from the synchronized method.

Program 10.43 Write a program to illustrate thread synchronization using synchronized method.
Solution:
class Callme
{
synchronized void call(String msg)
{
System.out.print("[" + msg);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("Interrupted");
}
System.out.println("]");
}
}
class Caller implements Runnable
{
String msg;
Callme target;
Thread t;
public Caller(Callme targ, String s)
{
target = targ;
msg = s;
t = new Thread(this);

146
JAVA Programming By Sourav Kumar Giri 2020

t.start();
}
public void run()
{
target.call(msg);
}
}
class Synch
{
public static void main(String args[])
{
Callme target = new Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");
// wait for threads to end
try
{
ob1.t.join();
ob2.t.join();
ob3.t.join();
}
catch(InterruptedException e)
{
System.out.println("Interrupted");
}
}
}
Output
[Hello]
[Synchronized]
[World]

147
JAVA Programming By Sourav Kumar Giri 2020

Thread synchronization using synchronized Statement


While creating synchronized methods within classes that you create is an easy and effective means of
achieving synchronization, it will not work in all cases. To understand why, consider the following. Imagine
that you want to synchronize access to objects of a class that was not designed for multithreaded access.
That is, the class does not use synchronized methods. Further, this class was not created by you, but by a
third party and you do not have access to the source code. Thus, you can’t add synchronized to the
appropriate methods within the class. How can access to an object of this class be synchronized? Fortunately,
the solution to this problem is quite easy: You simply put calls to the methods defined by this class inside a
synchronized block.

The general form of the synchronized statement is:


synchronized (object)
{
// statements to be synchronized
}

Here, object is a reference to the object being synchronized. A synchronized block ensures that a call to a
method that is a member of object occurs only after the current thread has successfully entered object’s
monitor.

Program 10.5: Write a program to illustrate thread synchronization using synchronized statement.
Solution:
class Callme
{
void call(String msg)
{
System.out.print("[" + msg);
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
System.out.println("Interrupted");
}
System.out.println("]");

148
JAVA Programming By Sourav Kumar Giri 2020

}
}
class Caller implements Runnable
{
String msg;
Callme target;
Thread t;
public Caller(Callme targ, String s)
{
target = targ;
msg = s;
t = new Thread(this);
t.start();
}
public void run()
{
synchronized(target)
{
target.call(msg);
}
}
}
class Synch1
{
public static void main(String args[])
{
Callme target = new Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");
try
{
ob1.t.join();
ob2.t.join();

149
JAVA Programming By Sourav Kumar Giri 2020

ob3.t.join();
}
catch(InterruptedException e)
{
System.out.println("Interrupted");
}
}
}
Output:
[Hello]
[Synchronized]
[World]

Wait(), notify() and notifyAll() methods


 wait() tells the calling thread to give up the monitor and go to sleep until some other thread enters the
same monitor and calls notify(). Its description is given by:
final void wait() throws InterruptedException

 notify() wakes up the first thread that called wait() on the same object. Its description is given by:
final void notify()

 notifyAll() wakes up all the threads that called wait() on the same object. The highest priority thread will
run first. Its description is given by:
final void notifyAll()
***********

150
JAVA Programming By Sourav Kumar Giri 2020

Practice Questions
1. Choose the most appropriate answer:
a) In java, threads are implemented by
a) Implementing runnable interface
b) Extending Thread class
c) Both a) and b) d) None of these

b) Thread priority in Java is _________


a) integer b) float
c) character d) double

c) Which What is multithreaded programming?


a) It’s a process in which two different processes run simultaneously
b) It’s a process in which two or more parts of same process run simultaneously
c) It’s a process in which many different process are able to access same information
d) It’s a process in which a single process can access information from many sources

d) Which of these are types of multitasking?


a) Process based b) Thread based
c) Process and Thread based d) None of the mentioned

e) Which of these statements is incorrect?


a) By multithreading CPU idle time is minimized, and we can take maximum use of it
b) By multitasking CPU idle time is minimized, and we can take maximum use of it
c) Two thread in Java can have the same priority
d) A thread can exist only in two states, running and blocked

Short Type
2. Answer briefly
a) Define thread. Differentiate between thread based multi tasking and process based multi tasking.
b) Why thread priorities are set?
c) Define race condition.
d) Define thread synchronization.
e) How a thread is implemented in java?
f) Differentiate between wait () and sleep() method.
g) Differentiate between notify() and notifyAll().

151
JAVA Programming By Sourav Kumar Giri 2020

Long Type
3. Answer in details
a) Define thread. Discuss the life cycle of a thread with neat diagram.
b) Discuss the importance of thread priorities with examples.
c) Discuss how synchronization in threads is achieved using synchronized method.
d) Explain how a thread is created by implementing Runnable interface.
e) Explain how a thread is created by extending thread class.
f) Write Short notes on following:
a. isAlive()
b. join()
c. notify()
d. notifyAll()
e. wait()
f. sleep()
*************

152

You might also like