Java (Mod 2)
Java (Mod 2)
Java (Mod 2)
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
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
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.
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
64
JAVA Programming By Sourav Kumar Giri 2020
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
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
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
}
}
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
}
}
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
//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
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
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
72
JAVA Programming By Sourav Kumar Giri 2020
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
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
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
75
JAVA Programming By Sourav Kumar Giri 2020
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
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
}
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
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.
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
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
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.
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.
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-
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.
*************
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
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)
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
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.
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);
}
}
Sl Method Description
4 static String format(Locale l, String format, Object... args) returns formatted string with given
locale.
96
JAVA Programming By Sourav Kumar Giri 2020
6 String substring(int beginIndex, int endIndex) returns substring for given begin
index and end index.
17 String[] split(String regex, int limit) returns a split string matching regex
and limit.
20 int indexOf(int ch, int fromIndex) returns the specified char value
index starting with given 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.
Constructor Description
StringBuffer() creates an empty string buffer with the initial capacity of 16.
StringBuffer(int capacity) creates an empty string buffer with the specified capacity as length.
98
JAVA Programming By Sourav Kumar Giri 2020
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 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)
99
JAVA Programming By Sourav Kumar Giri 2020
100
JAVA Programming By Sourav Kumar Giri 2020
101
JAVA Programming By Sourav Kumar Giri 2020
102
JAVA Programming By Sourav Kumar Giri 2020
Constructor Description
StringBuilder() creates an empty string Builder with the initial capacity of 16.
StringBuilder(int length) creates an empty string Builder with the specified capacity as length.
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 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.
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
}
}
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
}
}
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, 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.
String nextToken() returns the next token from the StringTokenizer object.
String nextToken(String delim) returns the next token based on the delimeter.
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.
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
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)
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()
110
JAVA Programming By Sourav Kumar Giri 2020
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
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.
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
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
114
JAVA Programming By Sourav Kumar Giri 2020
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
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
}
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
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
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
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
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
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.
Try block
finally
123
JAVA Programming By Sourav Kumar Giri 2020
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
Object
Throwable
Error Exception
125
JAVA Programming By Sourav Kumar Giri 2020
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.
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
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.
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
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
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
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.
New
Runnable
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.
135
JAVA Programming By Sourav Kumar Giri 2020
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:
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
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
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.
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
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.
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
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]
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
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