001 Core 15 - Java Programming - III Sem
001 Core 15 - Java Programming - III Sem
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
IV PACKAGE IN JAVA 18
V JAVA – INTERFACES 26
VI EXCEPTION HANDLING 31
X MULTITHREADING 66
Page 1 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
CHAPTER – I
DATA TYPES, CLASS & METHODS
We will describe these data types in Java by specifying for each of them:
The domain:
The set of possible values that can be represented in the memory of the computer
by means of the primitive data type (note that this set will always be finite);
The set of operations: operators of the programming language that allow us to
perform elementary operations on values of the primitive data type (e.g., +, -, /, *, etc.)
The set of literals: symbols of the language that define values of the primitive data
type (e.g., 10, 3.14, ’A’, true, etc.)
Moreover, we will specify the size of the memory occupied by a value of a certain
data type, which will be significant for the numeric data types.
Type Int
Dimension 32 bit (4 byte)
Domain the set of integer numbers in the interval [−231, +231 −
1]
(more than 4 billion values)
Operations + Sum
- Difference
* Product
/ integer division
rest of the integer division
Example:
int a, b, c;// Declaration of variables of type int a = 1;// Use of literals
b = 2;
c = a + b;// Arithmetic expression that involves operators of the language
Page 2 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
Note: the symbol + can be used both for the sum of two numbers and to concatenate two
strings: "aaa" + "bbb" corresponds to "aaa".concat("bbb").
In
• the first statement, “+” is applied to two integers, and hence denotes the addition
operator. Hence, the argument 3+4 of println() is of type int.
In
• the second statement, , “+” is applied to a string and an integer, and hence denotes
string concatenation. More precisely, the integer 4 is first converted to the string "4", and
then concatenated to the string "3". Hence, the argument "3"+4 of println() is of type
String.
Both statements are correct, since the method println() is overloaded: the Java library
contains both the versions that accepts an integer as parameter, and a version that accepts
a string as parameter.
The smallest integer type is byte. This is a signed 8-bit type that has a range from –128 to
127. Variables of type byte are especially useful when you’re working with a stream of data
from a network or file.
Type Byte
Dimension 8 bit (1 byte)
Domain the set of integer numbers in the interval [−27, +27 − 1] =
[−128, +127]
Operations + Sum
- Difference
* Product
/ integer division
rest of the integer division
Example:
byte a, b, c; // Declaration of variables of type byte
a = 1; // Use of literals
b = Byte.parseByte("47"); // Conversion from String to byte c = a - b; // Arithmetic
Page 3 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
expression
Other primitive data types for integer numbers: short
Short is a signed 16-bit type. It has a range from –32,768 to 32,767. It is probably the least-
used Java type, since it is defined as having its high byte first (called big-endian format).
Type Short
Dimension 16 bit (2 byte)
Domain the set of integer numbers in the interval [−215, +215 − 1] =
[−32768, +32767]
Operations + Sum
- Difference
* Product
/ integer division
rest of the integer division
Example:
short a, b, c; // Declaration of variables of type short1
a = 11300; // Use of literals
b = Short.parseShort("22605");// Conversion from String to short c = b a;// Arithmetic
expression
Other primitive data types for integer numbers: long
long is a signed 64-bit type and is useful for those occasions where an int type is not large
enough to hold the desired value. The range of a long is quite large. This makes it useful
when big, whole numbers are needed.
Type Long
Dimension 64 bit (8 byte)
Domain the set of integer numbers in the interval [−263,
+263 − 1]
Operations + Sum
- Difference
* Product
/ integer division
rest of the integer division
Page 4 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
Example:
long a, b, c; // Declaration of variables of type long
a = 9000000000L;// Use of literals
b = Long.parseLong("9000000000l"); // Conversion from String to long c = b / 300000L
Type Double
Dimension 64 bit (8 byte)
Domain set of 264 Minimum absolute 1.79769313486231570 ·
positive and value 10−308
negative real Maximum absolute 2.250738585072014 ·
numbers value 10+308
Precision ∼ 15 decimal digits
Operations + sum
- difference
* product
/ Division
Literals sequences of digits with decimal dot optionally ending with a d
(or D)
denoting values of the domain (e.g., 3.14 or 3.14d)
representation in scientific notation (e.g., 314E-2 or 314E-2d)
Example:
double pi, p2; // Declaration of variables of type double pi = 3.14;// Use of literals
p2 = 628E-2d;// Use of literals
p2 = pi * 2;// Arithmetic expression
Static:
The static can be:
Static Variables
Static Methods
Static Blocks Of Code.
Page 6 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
Student s1 = new Student();
s1.showData();
Student s2 = new Student();
s2.showData();
//Student.b++;
//s1.showData();
}
}
class Student {
int a; //initialized to zero
static int b; //initialized to zero only when class is loaded not for each object created.
Student(){
//Constructor incrementing static variable b
b++;
}
public void showData(){
System.out.println("Value of a = "+a);
System.out.println("Value of b = "+b);
}
//public static void increment(){
//a++;
//}
}
Step 2: Save & Compile the code. Run the code as, java Demo.
Step 3: Expected output show below
Following diagram shows, how reference variables & objects are created and static
variables are accessed by the different instances.
Page 7 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
Step 4: It is possible to access a static variable from outside the class using the
syntax ClassName.Variable_Name. Uncomment line # 7 & 8 . Save , Compile & Run .
Observe the output.
Value of a = 0
Value of b = 1
Value of a = 0
Value of b = 2
Value of a = 0
Value of b = 3
class Test{
static {
//Code goes here
}
}
A static block helps to initialize the static data members, just like constructors help to
initialize instance members
Page 8 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
CHAPTER - II
INHERITANCE - SUPER KEYWORD
Super keyword in java
Super keyword in java is a reference variable that is used to refer parent class
object. Super is an implicit keyword creates by JVM and supply each and every java
program for performing important role in three places.
1. Super keyword At Variable Level
2. Super keyword At Method Level
3. Super keyword At Constructor Level
In order to differentiate between the data member of base class and derived class,
in the context of derived class the base class data members must be preceded by super
keyword.
Syntax
Super.baseclassdatamember name
If we are not writing super keyword before the base class data member name than
it will be referred as current class data member name and base class data member are
hidden in the context of derived class. Program without using super keyword
Example
classEmployee
{
float salary=10000;
}
class HR extendsEmployee
{
float salary=20000;
void display()
{
System.out.println("Salary: "+salary);//print current class salary
}
}
classSupervarible
{
publicstaticvoid main(String[]args)
Page 9 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
{
HR obj=new HR();
obj.display();
}
}
Output
Salary: 20000.0
classEmployee
{
float salary=10000;
}
class HR extendsEmployee
{
float salary=20000;
void display()
{
System.out.println("Salary: "+super.salary);//print base class salary
}
}
classSupervarible
{
publicstaticvoid main(String[]args)
{
HR obj=new HR();
obj.display();
}
}
classStudent
Page 10 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
{
void message()
{
System.out.println("Good Morning Sir");
}
}
classFacultyextendsStudent
{
void message()
{
System.out.println("Good Morning Students");
}
void display()
{
message();//will invoke or call current class message() method
super.message();//will invoke or call parent class message() method
}
publicstaticvoid main(Stringargs[])
{
Student s=newStudent();
s.display();
}
}
Output
In the above example Student and Faculty both classes have message() method if we call
message() method from Student class, it will call the message() method of Student class not of
Person class because priority of local is high.
In case there is no method in subclass as parent, there is no need to use super. In the
example given below message() method is invoked from Student class but Student class does
not have message() method, so you can directly call message() method.
classStudent
{
void message()
{
System.out.println("Good Morning Sir");
}
}
Page 11 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
classFacultyextendsStudent
{
void display()
{
message();//will invoke or call parent class message() method
}
publicstaticvoid main(Stringargs[])
{
Student s=newStudent();
s.display();
}
}
Output
To establish the connection between base class constructor and derived class
constructors JVM provides two implicit methods they are:
Super()
Super(...)
Super()
Super() It is used for calling super class default constructor from the context of derived class
constructors.
Super keyword used to call base class constructor
Syntax
classEmployee
{
Employee()
{
System.out.println("Employee class Constructor");
}
}
class HR extendsEmployee
{
HR()
{
super();//will invoke or call parent class constructor
System.out.println("HR class Constructor");
}
}
Page 12 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
classSupercons
{
publicstaticvoid main(String[]args)
{
HR obj=new HR();
}
}
Output
Super(...)
Super(...) It is used for calling super class parameterize constructor from the context of
derived class constructor.
Important rules
Whenever we are using either super() or super(...) in the derived class constructors
the superalways must be as a first executable statement in the body of derived class
constructor otherwise we get a compile time error.
Page 13 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
The following diagram use possibilities of using super() and super(........)
Page 14 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
CHAPTER- III
FINAL KEYBOARD & METHOD
Final Keyword In Java
The final keyword in java is used to restrict the user. The java final keyword can be used in
many context. Final can be:
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no value it is
called blank final variable or uninitialized final variable. It can be initialized in the constructor
only. The blank final variable can be static also which will be initialized in the static block only.
We will have detailed learning of these. Let's first learn the basics of final keyword.
1. Java final variable
If you make any variable as final, you cannot change the value of final variable(It
will be constant).
Page 15 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
3. Java final class
If you make any class as final, you cannot extend it.
Example of final class
a. final class Bike{}
b. class Honda1 extends Bike{
c. void run(){System.out.println("running safely with 100kmph");}
d.
e. public static void main(String args[]){
f. Honda1 honda= new Honda1();
g. honda.run();
h. }
i. }
a. class Bike{
b. final void run(){System.out.println("running...");}
c. }
d. class Honda2 extends Bike{
e. public static void main(String args[]){
f. new Honda2().run();
g. }
h. }
Output:running...
Q) What is blank or uninitialized final variable?
A final variable that is not initialized at the time of declaration is known as blank final
variable.
If you want to create a variable that is initialized at the time of creating object and once
initialized may not be changed, it is useful. For example PAN CARD number of an employee.
It can be initialized only in constructor.
Example of blank final variable
a. class Student{
b. int id;
c. String name;
d. final String PAN_CARD_NUMBER;
e. ...
f. }
Que) Can we initialize blank final variable?
Page 16 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
g. }
h.
i. public static void main(String args[]){
j. new Bike10();
k. }
l. }
Output: 70
Page 17 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
CHAPTER – IV
PACKAGE IN JAVA
Package in Java
A package is a collection of similar types of classes, interfaces and sub-packages.
Purpose of package
The purpose of package concept is to provide common classes and interfaces for any
program separately. In other words if we want to develop any class or interface which is
common for most of the java programs than such common classes and interfaces must be
place in a package.
Packages in Java are the way to organize files when a project has many modules. Same
like we organized our files in Computer. For example we store all movies in one folder and
songs in other folder, here also we store same type of files in a particular package for example
in awt package have all classes and interfaces for design GUI components.
Advantage of package
a. Package is used to categorize the classes and interfaces so that they can be easily
maintained
b. Application development time is less, because reuse the code
c. Application memory space is less (main memory)
d. Application execution time is less
e. Application performance is enhance (improve)
f. Redundancy (repetition) of code is minimized
g. Package provides access protection.
h. Package removes naming collision.
i.
Types of package
Package is classified into two types.
Page 18 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
1. Predefined or built-in package
2. User defined package
Page 19 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
Syntax
javac-d . className.java
Syntax
Explanations: In above syntax "-d" is a specific tool which is tell to java compiler create a
separate folder for the given package in given path. When we give specific path then it create a
new folder at that location and when we use . (dot) then it crate a folder at current working
directory.
Note: Any package program can be compile but can not be execute or run. These programs can
be executed through user defined program which are importing package program.
packagemypack;
publicclass A
{
publicvoid show()
{
System.out.println("Sum method");
}
}
importmypack.A;
publicclassHello
{
publicstaticvoid main(Stringarg[])
{
A a=new A();
a.show();
System.out.println("show() class A");
}
}
Explanations: In the above program first we create Package program which is save with A.java
and compiled by "javac -d . A.java". Again we import class "A" in class Hello using "import
mypack.A;" statement.
Page 20 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
Public, private and protected keywords while practising java programs, these are called
access modifiers. An access modifier restricts the access of a class, constructor, data member
and method in another class. In java we have four access modifiers:
Default
Private
Protected
Public
publicclassAddition{
/* Since we didn't mention any access modifier here, it would
* be considered as default.
*/
intaddTwoNumbers(int a,int b){
returna+b;
}
}
Test.java
packagexyzpackage;
Page 21 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
}
Output:
Exceptionin thread "main"java.lang.Error:Unresolved compilation problem:
The method addTwoNumbers(int,int)from the type Addition is not visible
at xyzpackage.Test.main(Test.java:12)
Addition.java
Package abcpackage;
Page 22 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
public class Addition{
protected int addTwoNumbers(int a,int b){
return a+b;
}
}
Test.java
Package xyzpackage;
Import abcpackage.*;
class Test extends Addition{
public static void main(String args[]){
Test obj=new Test();
System.out.println(obj.addTwoNumbers(11,22));
}
}
Output:
33
4. Public access modifier
The members, methods and classes that are declared public can be accessed from
anywhere. This modifier doesn’t put any restriction on the access.
Addition.java
Package abcpackage;
public class Addition{
public int addTwoNumbers(int a,int b){
returna+b;
}
}
Test.java
Package xyzpackage;
Import abcpackage.*;
Class Test{
Public static void main(String args[]){
Addition obj=new Addition();
System.out.println(obj.addTwoNumbers(100,1));
}
}
Output:
101
Page 23 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
————————————+———————+—————————+——————————----+—
————————----—+————————
public|Yes|Yes|Yes|Yes|Yes|
————————————+———————+—————————+—————————----—+—
————————----—+————————
protected|Yes|Yes|Yes|Yes|No|
————————————+———————+—————————+————————----——+—
———————----——+————————
default|Yes|Yes|Yes|No|No|
————————————+———————+—————————+————————----——+—
———————----——+————————
private|Yes|No|No|No|No|
------------+-------+---------+--------------+--------------+--------
Page 24 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
Page 25 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
CHAPTER – V
JAVA – INTERFACES
Java - Interfaces
An interface is a reference type in Java. It is similar to class. It is a collection of abstract
methods. A class implements an interface, thereby inheriting the abstract methods of the
interface.
Along with abstract methods, an interface may also contain constants, default methods,
static methods, and nested types. Method bodies exist only for default methods and static
methods.
Writing an interface is similar to writing a class. But a class describes the attributes and
behaviors of an object. And an interface contains behaviors that a class implements.
Unless the class that implements the interface is abstract, all the methods of the
interface need to be defined in the class.
Page 26 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
/* File name : Animal.java */
interfaceAnimal{
publicvoid eat();
publicvoid travel();
}
Implementing Interfaces
When a class implements an interface, you can think of the class as signing a contract,
agreeing to perform the specific behaviors of the interface. If a class does not perform all the
behaviors of the interface, the class must declare itself as abstract.
A class uses the implements keyword to implement an interface. The implements
keyword appears in the class declaration following the extends portion of the declaration.
Example
/* File name : MammalInt.java */
Public class Mammal Intimplements Animal{
publicintnoOfLegs(){
return0;
}
publicstaticvoid main(Stringargs[]){
MammalInt m =newMammalInt();
m.eat();
m.travel();
}
}
This will produce the following result –
Output
Mammal eats
Mammal travels
When overriding methods defined in interfaces, there are several rules to be followed:
a. Checked exceptions should not be declared on implementation methods other than the
ones declared by the interface method or subclasses of those declared by the interface
method.
b. The signature of the interface method and the same return type or subtype should be
maintained when overriding the methods.
c. An implementation class itself can be abstract and if so, interface methods need not be
implemented.
When implementation interfaces, there are several rules:
a. A class can implement more than one interface at a time.
b. A class can extend only one class, but implement many interfaces.
Page 27 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
c. An interface can extend another interface, in a similar way as a class can extend another
class.
Extending Interfaces
An interface can extend another interface in the same way that a class can extend
another class. The extends keyword is used to extend an interface, and the child interface
inherits the methods of the parent interface.
// Filename: Football.java
Public interface Football extends Sports{
Public void homeTeamScored(int points);
Public void visitingTeamScored(int points);
Public void endOfQuarter(int quarter);
}
// Filename: Hockey.java
Public interface HockeyextendsSports{
Public void homeGoalScored();
Public void visitingGoalScored();
Public void endOfPeriod(int period);
Public void overtimePeriod(intot);
}
The Hockey interface has four methods, but it inherits two from Sports; thus, a class
that implements Hockey needs to implement all six methods. Similarly, a class that implements
Football needs to define the three methods from Football and the two methods from Sports.
Tagging Interfaces
The most common use of extending interfaces occurs when the parent interface does not
contain any methods. For example, the MouseListener interface in the java.awt.event package
extended java.util.EventListener, which is defined as –
Example
Package java.util;
Page 28 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
public interface EventListener
{}
Creates a common parent: As with the EventListener interface, which is extended by dozens of
other interfaces in the Java API, you can use a tagging interface to create a common parent
among a group of interfaces. For example, when an interface extends EventListener, the JVM
knows that this particular interface is going to be used in an event delegation scenario.
Adds a data type to a class : This situation is where the term, tagging comes from. A class that
implements a tagging interface does not need to define any methods (since the interface does
not have any), but the class becomes an interface type through polymorphism.
Abstract
A Java abstract class is a class which cannot be instantiated, meaning you cannot create
new instances of an abstract class. The purpose of an abstract class is to function as a base for
subclasses. This Java abstract class tutorial explains how abstract classes are created in Java,
what rules apply to them. This tutorial gets into the purpose of abstract classes in Java in more
detail towards the end of this text.
}
That is all there is to declaring an abstract class in Java. Now you cannot create instances
ofMyAbstractClass. Thus, the following Java code is no longer valid:
MyAbstractClassmyClassInstance =
new MyAbstractClass(); //not valid
If you try to compile the code above the Java compiler will generate an error, saying that
you cannot instantiate MyAbstractClass because it is an abstract class.
Abstract Methods
An abstract class can have abstract methods. You declare a method abstract by adding
the abstractkeyword in front of the method declaration. Here is a Java abstract method
example:
public abstract class MyAbstractClass {
Page 29 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
If a class has an abstract method, the whole class must be declared abstract. Not all
methods in an abstract class have to be abstract methods. An abstract class can have a mixture
of abstract and non-abstract methods.
Subclasses of an abstract class must implement (override) all abstract methods of its
abstract superclass. The non-abstract methods of the superclass are just inherited as they are.
They can also be overridden, if needed.
The only time a subclass of an abstract class is not forced to implement all abstract
methods of its superclass, is if the subclass is also an abstract class.
Exception handling in java with examples
Exception handling is one of the most important feature of java programming that
allows us to handle the runtime errors caused by exceptions. In this guide, we will learn what is
an exception, types of it, exception classes and how to handle exceptions in java with examples
Page 30 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
CHAPTER – VI
EXCEPTION HANDLING
What is an exception?
An Exception is an unwanted event that interrupts the normal flow of the program.
When an exception occurs program execution gets terminated. In such cases we get a system
generated error message. The good thing about exceptions is that they can be handled in Java.
By handling the exceptions we can provide a meaningful message to the user about the issue
rather than a system generated message, which may not be understandable to a user.
Why an exception occurs?
There can be several reasons that can cause a program to throw exception. For
example: Opening a non-existing file in your program, Network connection problem, bad input
data provided by user etc.
Exception Handling
If an exception occurs, which has not been handled by programmer then program
execution gets terminated and a system generated error message is shown to the user. For
example look at the system generated exception below:
An exception generated by the system is given below
Exceptionin thread "main"java.lang.ArithmeticException:/by zero at
ExceptionDemo.main(ExceptionDemo.java:5)
ExceptionDemo:Theclass name
main :The method name
ExceptionDemo.java :The filename
java:5:Line number
This message is not user friendly so a user will not be able to understand what went
wrong. In order to let them know the reason in simple language, we handle exceptions. We
handle such conditions and then prints a user friendly warning message to user, which lets
them correct the error as most of the time exception occurs due to bad data provided by user.
ArrayIndexOutOfBoundsException - When you try to access the elements of an array out of its
bounds, for example array size is 5 (which means it has five elements) and you are trying to
access the 10th element.
Page 31 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
Types of exceptions
There are two types of exceptions in Java:
1.Checkedexceptions
2.Unchecked exceptions
Checked exceptions
All exceptions other than Runtime Exceptions are known as Checked exceptions as the
compiler checks them during compilation to see whether the programmer has handled them or
not. If these exceptions are not handled/declared in the program, you will get compilation
error. For example, SQLException, IOException, ClassNotFoundException etc.
Unchecked Exceptions
Runtime Exceptions are also known as Unchecked Exceptions. These exceptions are not
checked at compile-time so compiler does not check whether the programmer has handled
them or not but it’s the responsibility of the programmer to handle these exceptions and
provide a safe exit. For example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc.
Try block
The try block contains set of statements where an exception can occur. A try block is
always followed by a catch block, which handles the exception that occurs in associated try
block. A try block must be followed by catch blocks or finally block or both.
Page 32 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
Catch block
A catch block is where you handle the exceptions, this block must follow the try block. A
single try block can have several catch blocks associated with it. You can catch different
exceptions in different catch blocks. When an exception occurs in try block, the corresponding
catch block that handles that particular exception executes. For example if an arithmetic
exception occurs in try block then the statements enclosed in catch block for arithmetic
exception executes.
The generic exception handler can handle all the exceptions but you should place is at
the end, if you place it at the before all the catch blocks then it will display the generic message.
You always want to give the user a meaningful message for each type of exception rather then
a generic message..
classExample1{
public static void main(String args[]){
int num1, num2;
try{
/* We suspect that this block of statement can throw
* exception so we handled it by placing these statements
* inside try and handled the exception in catch block
*/
num1 =0;
num2 =62/ num1;
System.out.println(num2);
System.out.println("Hey I'm at the end of try block");
}
catch(ArithmeticException e){
/* This block will only execute if any Arithmetic exception
* occurs in try block
*/
System.out.println("You should not divide a number by zero");
}
catch(Exception e){
/* This is a generic Exception handler which means it can handle
Page 33 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
* all the exceptions. This will execute if the exception is not
* handled by previous catch blocks.
*/
System.out.println("Exception occurred");
}
System.out.println("I'm out of try-catch block in Java.");
}
}
Output:
You should not divide a number by zero
I'm out of try-catch block in Java.
2.A generic catch block can handle all the exceptions. Whether it is Array Index Out Of Bounds
Exception or Arithmetic Exception or Null Pointer Exception or any other type of exception, this
handles all of them. To see the examples of NullPointerException and
ArrayIndexOutOfBoundsException, refer this article: Exception Handling example programs..
catch(Exception e){
//This catch block catches all the exceptions
}
If you are wondering why we need other catch handlers when we have a generic that
can handle all. This is because in generic exception handler you can display a message but you
are not sure for which type of exception it may trigger so it will display the same message for all
the exceptions and user may not be able to understand which exception occurred. Thats the
reason you should place is at the end of all the specific exception catch blocks
3.If no exception occurs in try block then the catch blocks are completely ignored.
5.You can also throw exception, which is an advanced topic and I have covered it in separate
tutorials: user defined exception, throws keyword, throw vs throws.
Page 34 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Warning: ArrayIndexOutOfBoundsException");
}
catch(Exception e){
System.out.println("Warning: Some Other exception");
}
System.out.println("Out of try-catch block...");
}
}
Output:
Warning: ArithmeticException
Out of try-catch block...
In the above example there are multiple catch blocks and these catch blocks executes
sequentially when an exception occurs in try block. Which means if you put the last catch block
( catch(Exception e)) at the first place, just after try block then in case of any exception this
block will execute as it can handle all exceptions. This catch block should be placed at the last to
avoid such situations.
Finally block
java finally block. executes whether an exception occurs or not. You should place those
statements in finally blocks, that must execute whether exception occurs or not.
When a try catch block is present in another try block then it is called the nested try
catch block. Each time a try block does not have a catch handler for a particular exception, then
the catch blocks of parent try block are inspected for that exception, if match is found that that
catch block executes.
If neither catch block nor parent catch block handles exception then the system
generated message would be shown for the exception, similar to what we see when we don’t
handle exception.
Lets see the syntax first then we will discuss this with an example.
Page 35 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
}
catch(Exception e1){
//Exception Message
}
}
//Catch of Main(parent) try block
catch(Exception e3){
//Exception Message
}
classNestingDemo{
publicstaticvoid main(Stringargs[]){
//main try-block
try{
//try-block2
try{
//try-block3
try{
intarr[]={1,2,3,4};
/* I'm trying to display the value of
* an element which doesn't exist. The
* code should throw an exception
*/
System.out.println(arr[10]);
}catch(ArithmeticException e){
System.out.print("Arithmetic Exception");
System.out.println(" handled in try-block3");
}
}
catch(ArithmeticException e){
System.out.print("Arithmetic Exception");
System.out.println(" handled in try-block2");
}
}
catch(ArithmeticException e3){
System.out.print("Arithmetic Exception");
System.out.println(" handled in main try-block");
}
catch(ArrayIndexOutOfBoundsException e4){
System.out.print("ArrayIndexOutOfBoundsException");
System.out.println(" handled in main try-block");
}
Page 36 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
catch(Exception e5){
System.out.print("Exception");
System.out.println(" handled in main try-block");
}
}
}
Output:
ArrayIndexOutOfBoundsException handled in main try-block
As you can see that the ArrayIndexOutOfBoundsException occurred in the grand child
try-block3. Since try-block3 is not handling this exception, the control then gets transferred to
the parent try-block2 and looked for the catch handlers in try-block2. Since the try-block2 is
also not handling that exception, the control gets transferred to the main (grand parent) try-
block where it found the appropriate catch block for exception. This is how the the nesting
structure works.
Example 2: Nested try block
classNest{
publicstaticvoid main(Stringargs[]){
//Parent try block
try{
//Child try block1
try{
System.out.println("Inside block1");
int b =45/0;
System.out.println(b);
}
catch(ArithmeticException e1){
System.out.println("Exception: e1");
}
//Child try block2
try{
System.out.println("Inside block2");
int b =45/0;
System.out.println(b);
}
catch(ArrayIndexOutOfBoundsException e2){
System.out.println("Exception: e2");
}
System.out.println("Just other statement");
}
catch(ArithmeticException e3){
System.out.println("Arithmetic Exception");
System.out.println("Inside parent try catch block");
}
catch(ArrayIndexOutOfBoundsException e4){
System.out.println("ArrayIndexOutOfBoundsException");
System.out.println("Inside parent try catch block");
}
catch(Exception e5){
System.out.println("Exception");
System.out.println("Inside parent try catch block");
Page 37 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
}
System.out.println("Next statement..");
}
}
Output:
Inside block1
Exception: e1
Inside block2
ArithmeticException
Inside parent trycatch block
Next statement..
This is another example that shows how the nested try block works. You can see that
there are two try-catch block inside main try block’s body. I’ve marked them as block
1 and block 2 in above example.
Block1: I have divided an integer by zero and it caused an ArithmeticException, since the catch
of block1 is handling ArithmeticException "Exception: e1" displayed.
Block2: In block2, ArithmeticException occurred but block 2 catch is only handling Array Index
Out Of Bounds Exception so in this case control jump to the Main try-catch(parent) body and
checks for the ArithmeticException catch handler in parent catch blocks. Since catch of parent
try block is handling this exception using generic Exception handler that handles all exceptions,
the message “Inside parent try catch block” displayed as output.
Parent try Catch block: No exception occurred here so the “Next statement..” displayed.
The important point to note here is that whenever the child catch blocks are not handling any
exception, the jumps to the parent catch blocks, if the exception is not handled there as well
then the program will terminate abruptly showing system generated message.
import java.io.*;
Page 38 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
classExample{
publicstaticvoid main(Stringargs[])
{
FileInputStreamfis=null;
/*This constructor FileInputStream(File filename)
* throws FileNotFoundException which is a checked
* exception
*/
fis=newFileInputStream("B:/myfile.txt");
int k;
Output:
Exceptionin thread "main"java.lang.Error:Unresolved compilation problems:
Unhandled exception type FileNotFoundException
Unhandled exception type IOException
Unhandled exception type IOException
As we know that all three occurrences of checked exceptions are inside main() method
so one way to avoid the compilation error is: Declare the exception in the method using throws
keyword. You may be thinking that our code is throwing FileNotFoundException and
IOException both then why we are declaring the IOException alone. The reason is that
IOException is a parent class of FileNotFoundException so it by default covers that. If you want
you can declare them like this public static void main(String args[]) throws IOException,
FileNotFoundException.
import java.io.*;
classExample{
publicstaticvoid main(Stringargs[])throwsIOException
Page 39 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
{
FileInputStreamfis=null;
fis=newFileInputStream("B:/myfile.txt");
int k;
while(( k =fis.read())!=-1)
{
System.out.print((char)k);
}
fis.close();
}
}
Output:
File content is displayed on the screen.
The approach we have used above is not good at all. It is not the best exception
handling practice. You should give meaningful message for each exception type so that it would
be easy for someone to understand the error. The code should be like this:
import java.io.*;
class Example{
public static void main(String args[])
{
FileInputStreamfis=null;
try{
fis=newFileInputStream("B:/myfile.txt");
}catch(FileNotFoundExceptionfnfe){
System.out.println("The specified file is not "+
"present at the given path");
}
int k;
try{
while(( k =fis.read())!=-1)
{
System.out.print((char)k);
}
fis.close();
}catch(IOExceptionioe){
System.out.println("I/O error occurred: "+ioe);
}
}
}
This code will run fine and will display the file content.
Here are the few other Checked Exceptions –
SQLException
IOException
ClassNotFoundException
InvocationTargetException
Page 40 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
What are Unchecked exceptions?
Unchecked exceptions are not checked at compile time. It means if your program is
throwing an unchecked exception and even if you didn’t handle/declare that exception, the
program won’t give a compilation error. Most of the times these exception occurs due to the
bad data provided by user during the user-program interaction. It is up to the programmer to
judge the conditions in advance, that can cause such exceptions and handle them
appropriately. All Unchecked exceptions are direct sub classes of RuntimeException class.
Note: It doesn’t mean that compiler is not checking these exceptions so we shouldn’t handle
them. In fact we should handle them more carefully. For e.g. In the above example there should
be a exception message to user that they are trying to display a value which doesn’t exist in
array so that user would be able to correct the issue.
Class Example{
Public static void main(String args[]){
try{
int arr[]={1,2,3,4,5};
System.out.println(arr[7]);
}
Page 41 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
catch(ArrayIndexOutOfBoundsException e){
System.out.println("The specified index does not exist "+
"in array. Please correct the error.");
}
}
}
Output:
The specified index does not exist in array.Please correct the error.
Here are the few unchecked exception classes:
a. NullPointerException
b. ArrayIndexOutOfBoundsException
c. ArithmeticException
d. IllegalArgumentException
e. NumberFormatException
Page 42 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
}
Output:
Number should not be divided by zero
Thisisfinally block
Out of try-catch-finally
Few Important points regarding finally block
1. A finally block must be associated with a try block, you cannot use finally without a try block.
You should place those statements in this block that must be executed always.
2. Finally block is optional, as we have seen in previous tutorials that a try-catch block is
sufficient for exception handling, however if you place a finally block then it will always run
after the execution of try block.
3. In normal case when there is no exception in try block then the finally block is executed after
try block. However if an exception occurs then the catch block is executed before finally block.
4. An exception in the finally block, behaves exactly like any other exception.
5. The statements present in the finally block execute even if the try block contains control
transfer statements like return, break or continue.
Lets see an example to see how finally works when return statement is present in try block:
Page 43 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
CHAPTER – VII
FINALLY () & CLOSE () STATEMENT
Finally and Close()
close() statement is used to close all the open streams in a program. Its a good practice
to use close() inside finally block. Since finally block executes even if exception occurs so you
can be sure that all input and output streams are closed properly regardless of whether the
exception occurs or not.
For example:
....
try{
OutputStreamosf=newFileOutputStream("filename");
OutputStreamosb=newBufferedOutputStream(opf);
ObjectOutput op =newObjectOutputStream(osb);
try{
output.writeObject(writableObject);
}
finally{
op.close();
}
}
catch(IOException e1){
System.out.println(e1);
}
...
Finally block without catch
A try-finally block is possible without catch block. Which means a try block can be used
with finally without having a catch block.
...
InputStream input =null;
try{
input =newFileInputStream("inputfile.txt");
}
finally{
if(input !=null){
try{
in.close();
}catch(IOExceptionexp){
System.out.println(exp);
}
}
}
Finally block and System.exit()
Try-catch-finally block
Either a try statement should be associated with a catch block or with finally.
Since catch performs exception handling and finally performs the cleanup, the best
approach is to use both of them.
Syntax:
try{
//statements that may cause an exception
}
catch(…){
//error handling code
}
finally{
//statements to be executed
}
Page 45 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
Output:
First statement of try block
15
finally block
Out of try-catch-finally block
Example 2: This example shows the working of finally block when an exception occurs in try
block but is not handled in the catch block:
Class Example2{
Public static void main(String args[]){
try{
System.out.println("First statement of try block");
intnum=45/0;
System.out.println(num);
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("ArrayIndexOutOfBoundsException");
}
finally{
System.out.println("finally block");
}
System.out.println("Out of try-catch-finally block");
}
}
Output:
First statement of try block
finally block
Exceptionin thread "main"java.lang.ArithmeticException:/by zero
at beginnersbook.com.Example2.main(Details.java:6)
As you can see that the system generated exception message is shown but before that the
finally block successfully executed.
Example 3: When exception occurs in try block and handled properly in catch block
Class Example3{
Public static void main(String args[]){
try{
System.out.println("First statement of try block");
intnum=45/0;
System.out.println(num);
}
catch(ArithmeticException e){
System.out.println("ArithmeticException");
}
finally{
System.out.println("finally block");
}
System.out.println("Out of try-catch-finally block");
}
}
Output:
Page 46 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
First statement of try block
ArithmeticException
finally block
Out of try-catch-finally block
classExample1
{
publicstaticvoid main(Stringargs[])
{
int x =10;
int y =10;
try{
intnum= x/y;
System.out.println("next-statement: Inside try block");
}
catch(Exception ex)
{
System.out.println("Exception");
}
System.out.println("next-statement: Outside of try-catch");
}
}
Output:
next-statement:Insidetry block
next-statement:Outside of try-catch
In the above example exception didn’t occur in try block so catch block didn’t run.
First have a look at the example below and then we will discuss the output:
classExample1
{
publicstaticvoid main(String args[])
{
int x =0;
int y =10;
try{
intnum= y/x;
System.out.println("next-statement: Inside try block");
}
catch(Exception ex)
{
Page 47 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
System.out.println("Exception Occurred");
}
System.out.println("next-statement: Outside of try-catch");
}
}
Output:
ExceptionOccurred
next-statement:Outside of try-catch
Point to note in above example: There are two statements present inside try block. Since
exception occurred because of first statement, the second statement didn’t execute. Hence we
can conclude that if an exception occurs then the rest of the try block doesn’t execute and
control passes to catch block.
Page 48 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
try- first statement
start -myMethod
AnException
finally
Out of try/catch/finally- statement
Page 49 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
CHAPTER – VIII
THROW EXCEPTION IN JAVA
We can define our own set of conditions or rules and throw an exception explicitly using
throw keyword. For example, we can throw Arithmetic Exception when we divide number by 5,
or any other numbers, what we need to do is just set the condition and throw any exception
using throw keyword. Throw keyword can also be used for throwing custom exceptions, I have
covered that in a separate tutorial, see Custom Exceptions in Java.
For example:
thrownewArithmeticException("dividing a number by 5 is not allowed in this program");
Example of throw keyword
Lets say we have a requirement where we we need to only register the students when
their age is less than 12 and weight is less than 40, if any of the condition is not met then the
user should get an ArithmeticException with the warning message “Student is not eligible for
registration”. We have implemented the logic by placing the code in the method that checks
student eligibility if the entered student age and weight doesn’t met the criteria then we throw
the exception using throw keyword.
Output:
Page 50 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
Welcome to the Registration process!!Exceptionin thread "main"
java.lang.ArithmeticException:Studentisnot eligible for registration
at beginnersbook.com.ThrowExample.checkEligibilty(ThrowExample.java:9)
at beginnersbook.com.ThrowExample.main(ThrowExample.java:18)
In the above example we have throw an unchecked exception, same way we can
throw uncheckedand user-defined exception as well.
Example 1: How to throw your own exception explicitly using throw keyword
This example shows how to throw a custom exception using throw. Refer this guide to
understand how to create your own exceptions.
classMyOwnExceptionextendsException{
publicMyOwnException(Stringmsg){
super(msg);
}
}
Class EmployeeTest{
staticvoidemployeeAge(int age) throws MyOwnException{
if(age <0)
thrownewMyOwnException("Age can't be less than zero");
else
System.out.println("Input is valid!!");
}
publicstaticvoid main(String[]args){
try{
employeeAge(-2);
}
catch(MyOwnException e){
e.printStackTrace();
}
}
}
Output:
beginnersbook.com.MyOwnException:Age can't be less than zero
Note: Method call should be in try block as it is throwing an exception.
Page 51 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
publicstaticvoid main(Stringargs[]){
int res=sum(0,12);
System.out.println(res);
System.out.println("Continue Next statements");
}
}
Output:
Exceptionin thread main java.lang.ArithmeticException:
First parameter isnot valid
Similarly other exceptions, such as NullPointerException, ArrayIndexOutOfBoundsException etc.
can be thrown.
Here we will see few examples of throws keyword. To understand these programs you
should have the knowledge of throws keyword in java.
Example 2: When you don’t handle exception and instead declare it at all the places
The ideal way to use throws is by declaring the exceptions in method signature and
handle the exceptions using try-catch in calling method. Lets see what happens when we
declare the exception at both the places, in method signature as well as in calling method.
Class Exception Example{
Page 52 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
void method()throws Arithmetic Exception{
thrownew Arithmetic Exception("Arithmetic Exception Occurred");
}
}
Class Example1{
Public static void main(String args[]) throws ArithmeticException{
ExceptionExampleobj=newExceptionExample();
obj.method();
System.out.println("End Of Program");
}
}
Output:
Exceptionin thread "main"java.lang.ArithmeticException:
ArithmeticExceptionOccurred
at ExceptionExample.method(Example1.java:4)
at Example1.main(Example1.java:10)
On the other hand unchecked exception (Runtime) doesn’t get checked during
compilation. Throws keyword is used for handling checked exceptions . By using throws we can
declare multiple exceptions in one go.
What is the need of having throws keyword when you can handle exception using try-catch?
The throws does the same thing that try-catch does but there are some cases where you
would prefer throws over try-catch. For example:
Lets say we have a method myMethod() that has statements that can throw either
ArithmeticException or NullPointerException, in this case you can use try-catch as shown
below:
publicvoidmyMethod()
{
try{
// Statements that might throw an exception
}
catch(ArithmeticException e){
// Exception handling statements
}
catch(NullPointerException e){
// Exception handling statements
}
}
But suppose you have several such methods that can cause exceptions, in that case it
would be tedious to write these try-catch for each method. The code will become unnecessary
long and will be less-readable.
Page 53 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
One way to overcome this problem is by using throws like this: declare the exceptions in
the method signature using throws and handle the exceptions where you are calling this
method by using try-catch.
Another advantage of using this approach is that you will be forced to handle the
exception when you call this method, all the exceptions that are declared using throws, must be
handled where you are calling this method else you will get compilation error.
publicvoidmyMethod()throwsArithmeticException,NullPointerException
{
// Statements that might throw an exception
}
publicstaticvoid main(Stringargs[]){
try{
myMethod();
}
catch(ArithmeticException e){
// Exception handling statements
}
catch(NullPointerException e){
// Exception handling statements
}
}
Example of throws Keyword
In this example the method myMethod() is throwing two checked exceptions so we
have declared these exceptions in the method signature using throws Keyword. If we do not
declare these exceptions then the program will throw a compilation error.
import java.io.*;
classThrowExample{
voidmyMethod(intnum)throwsIOException,ClassNotFoundException{
if(num==1)
thrownewIOException("IOException Occurred");
else
thrownewClassNotFoundException("ClassNotFoundException");
}
}
publicclassExample1{
publicstaticvoid main(Stringargs[]){
try{
ThrowExampleobj=newThrowExample();
obj.myMethod(1);
}catch(Exception ex){
System.out.println(ex);
}
}
}
Output:
java.io.IOException:IOExceptionOccurred
Page 54 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
BY CHAITANYA SINGH | FILED UNDER: EXCEPTION HANDLING
Now lets change the code a little bit and see the change in output:
classExample{
publicstaticvoid main(Stringargs[]){
try{
intarr[]=newint[7];
arr[10]=10/5;
System.out.println("Last Statement of try block");
}
catch(ArithmeticException e){
System.out.println("You should not divide a number by zero");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Accessing array elements outside of the limit");
}
catch(Exception e){
System.out.println("Some Other Exception");
}
System.out.println("Out of the try-catch block");
}
}
Output:
Page 55 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
Accessing array elements outside of the limit
Out of the try-catch block
In this case, the second catch block got executed because the code throws Array Index
Out Of Bounds Exception. We are trying to access the 11th element of array in above program
but the array size is only 7.
What did we observe from the above two examples?
1. It is clear that when an exception occurs, the specific catch block (that declares that
exception) executes. This is why in first example first block executed and in second example
second catch.
2. Although I have not shown you above, but if an exception occurs in above code which is not
Arithmetic and ArrayIndexOutOfBounds then the last generic catch handler would execute.
Output:
Compile time error:Exceptionin thread "main"java.lang.Error:
Unresolved compilation problems:Unreachablecatch block forArithmeticException.
Itis already handled by the catch block forExceptionUnreachablecatch block
forArrayIndexOutOfBoundsException.Itis already handled by the catch block for
Exception at Example.main.
Page 56 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
CHAPTER – IX
INTRODUCTION OF THREADS IN JAVA
What are Java Threads?
A thread is a:
a. Facility to allow multiple activities within a single process
b. Referred as lightweight process
c. A thread is a series of executed statements
d. Each thread has its own program counter, stack and local variables
e. A thread is a nested sequence of method calls
f. Its shares memory, files and per-process state
Read: Multithreading in Java
Risk Factor
a. Proper co-ordination is required between threads accessing common variables [use of
synchronized and volatile] for consistence view of data
Threads in Java
Java threads facility and API is deceptively simple:
Every java program creates at least one thread [ main() thread ]. Additional threads are
created through the Thread constructor or by instantiating classes that extend the Thread class.
Example:
publicclassMyThreadextendsThread{
Page 57 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
publicvoid run(){
System.out.println("thread is running...");
}
publicstaticvoid main(String[]args){
MyThreadobj=newMyThread();
obj.start();
}
B.By Implementing Runnable interface
1. The class should implement the Runnable interface
2. The class should implement the run() method in the Runnable interface
3. The functionality that is expected by the Thread to be executed is put in the run()
method
Example:
Public class MyThreadimplementsRunnable{
publicvoid run(){
System.out.println("thread is running..");
}
publicstaticvoid main(String[]args){
Thread t =newThread(newMyThread());
t.start();
}
Extends Thread class vs Implements Runnable Interface?
Extending the Thread class will make your class unable to extend other classes, because
of the single inheritance feature in JAVA. However, this will give you a simpler code structure. If
you implement Runnable, you can gain better object-oriented design and consistency and also
avoid the single inheritance problems.
If you just want to achieve basic functionality of a thread you can simply implement
Runnable interface and override run() method. But if you want to do something serious with
thread object as it has other methods like suspend(), resume(), ..etc which are not available in
Runnable interface then you may prefer to extend the Thread class.
Ending Thread
A Thread ends due to the following reasons:
The thread ends when it comes when the run() method finishes its execution.
When the thread throws an Exception or Error that is not being caught in the program.
Java program completes or ends.
Another thread calls stop() methods.
Synchronization of Threads
In many cases concurrently running threads share data and two threads try to do
operations on the same variables at the same time. This often results in corrupt data as
two threads try to operate on the same data.
A popular solution is to provide some kind of lock primitive. Only one thread can acquire
a particular lock at any particular time. This can be achieved by using a keyword
“synchronized” .
Page 58 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
By using the synchronize only one thread can access the method at a time and a second
call will be blocked until the first call returns or wait() is called inside the synchronized
method.
Deadlock
Whenever there is multiple processes contending for exclusive access to multiple locks,
there is the possibility of deadlock. A set of processes or threads is said to be deadlocked when
each is waiting for an action that only one of the others can perform.
In Order to avoid deadlock, one should ensure that when you acquire multiple locks, you always
acquire the locks in the same order in all threads.
Although the main thread is automatically created when your program starts, it can be
controlled through a Thread object. To do so, you must obtain a reference to it by calling the
method named currentThread(), is a public static member of the Thread. Its general form is :
static Thread currentThread()
This method returns a reference to the thread in which it is called. And once you have a
reference to the main thread, you can control it just like any other thread.
class JavaProgram
{
public static void main(String args[])
{
Page 59 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
thr.setName("My Thread");
System.out.println("After name change : " + thr);
try {
for(int i=5; i>0; i--)
{
System.out.println(i);
Thread.sleep(1000);
}
System.out.println("stopped");
} catch(InterruptedException e) {
System.out.println("Main thread interrupted");
}
}
}
When above java program is compile and executed, it will produce the following output:
In the above program a reference to the current thread (main thread in this case) is
obtained by calling the current thread) method, and this reference is stored in the local variable
i.e. thr.next, the program displays the information about the thread. The program then calls set
Name() method to change the internal name of the thread. Data about the thread is then
redisplayed. Next, a loop counts down from five, pausing one second between each line. The
pause is executed by the sleep() specifies the delay period in milliseconds.
Notice here that the try catch block around this loop. The slep() method in the thread
might throw an interrupted exception. It will happen only if some other thread wanted to
interrupt this sleeping one. This program just prints a message.(as shown in above program) if it
gets interrupted.
Notice that the output produced when the is used as an argument to println().This
displays in order, the name of the thread and its priority and then the name of its group.
Page 60 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
By default the name of the main thread is main. And its priority is 5, which is the
default value, and main is also the name of the group of threads to which this thread belongs
to.
A thread group is a data structure that controls the state of a collection of threads as a
whole. After the name of the thread is altered the is again output. This time the new name of
the thread is displayed.
In the above program as you can see sleep() causes the thread from which it is called
to suspend execution for the given period of milliseconds. Its general from is:
The sleep() has a second form, shown next, allows you to specify the period in terms
of milliseconds and nanoseconds:
This second form of sleep() method is useful only in environments that allow timing
periods as short a nanoseconds.
As the preceding program shows, you can use set name() method to set the name of a
thread.
You can obtain the name of the thread by calling the method getname() this method
is not shown in the above program but you can try it. These methods are the members of the
thread class and are declared like this:
To create a thread in java you need to instatiate an object of type thread java provides two
ways to create a thread
A. By implementing the Runnable interface.
B. By extending the thread class.
Here we’ll look at both the ways of creating a thread in java.
One of the ways to create a thread in java is to implement the Runnable interface.
@functionlinterface
Page 61 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
InterfaceRunnable
publicabstractvoid();
Note the @Functional interface annotation on the top of the runnable interface. That
is a new annotation added in Java8. Read more about it here Functional interface annotation in
java 8
To implement runnable a class has to implement only the run() method inside run()
method we write the code for the new thread.
When using Runnable you have to explicitly create a thread class object by passing the
Runnable as parameter so that run() method of the thread can be executed. java thread class
defines several constructors, some of the commonly used are.
Thread()
Thread(String Name)
Thread(Runnable threadObi)
Thread(Runnable threadObi,String name)
You can use any of the last two in case of runnable to create a thread in java.
After the new thread is created, it will not start running until you call the start() method, which
is declared within thread class. As soon as start() method is called upon a thread object
following actions happen-
The thread’s state changes from New state to the runnable state.
Thread’s target run() method will execute (depends upon when thread gets the
CPU CYCLE).
publicclassThreadDemo{
publicstaticvoid main(String[]args){
// Passing runnable instance
Threadthread=newThread(newMyThread());
// Calling start method
thread.start();
}
}
Output
Entered run method Thread-0
Page 62 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
My Thread0
My Thread1
My Thread2
My Thread3
My Thread4
Finished with MyThread
Here we are using the constructor Thread(Runnable threadObj) while creating a thread object -
Thread thread = new Thread(new MyThread());.
Calling start() method on the thread will execute the run method where it will print numbers
along with the thread name.
Creating thread by extending Thread class
Another way to create a thread in Java is to create a class that extends Thread class and then
create an instance of that class. The extending class has to override the run() method and also
needs to call start() method to start execution of the new thread.
Thread creation Example by extending Thread class
Class MyThread extends Thread{
@Override
publicvoid run(){
System.out.println("Entered run method "+Thread.currentThread().getName());
for(int i =0; i <5; i++){
System.out.println("My Thread"+ i);
}
System.out.println("Finished with MyThread");
}
}
Page 63 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
}
System.out.println("Finished with Inner Thread");
}
};
// starting the thread, which will start execution of run method
t.start();
}
}
publicclassThreadDemo{
publicstaticvoid main(String[]args){
InnerThread thread =newInnerThread("MyThread");
}
}
Here we are implementing the run method using an anonymous class. Note that Thread class is
not explicitly extended here and the implementation of the run() method is provided when an
instance of the thread is created.
Implementing Runnable as an anonymous class
If you want to do it using runnable interface run() method implementation it will only be a small
change.
classInnerThread{
Thread t;
// Constructor
publicInnerThread(String name){
// Anonymous class with run method implemented
// using Runnable interface
Thread t =newThread(newRunnable(){
@Override
publicvoid run(){
System.out.println("Entered run method "+Thread.currentThread().getName());
for(int i =0; i <5; i++){
System.out.println(name + i);
}
System.out.println("Finished with Inner Thread");
}
}, name);// Name of the thread, second param
// starting the thread, which will start execution of run method
t.start();
}
}
Implementing Runnable as Java Lambda expression
Java 8 onward it is also possible to use lambda expression to provide implementation of the run
method of the runnable interface. Runnable interface has a single abstract method run() thus it
can be considered as a functional interface. Lambda expression can be used to provide
implementation of that abstract method.
classLambdaThread{
publicLambdaThread(String name){
// Lambda block - code inside the lambda block will
// be the implementation of the run method.
Runnable r =()->{
Page 64 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
System.out.println("Entered run method "+Thread.currentThread().getName());
for(int i =0; i <5; i++){
System.out.println("Lambda thread "+ i);
}
System.out.println("Finished with Lambda Thread");
};
//starting thread with the constructor of the thread class
// that takes runnable instance and String as parameters
newThread(r, name).start();
}
}
publicclassThreadDemo{
publicstaticvoid main(String[]args){
LambdaThread thread =newLambdaThread("LambdaThread");
}
}
Here we have used the lambda expression to provide implementation of the run method of the
runnable interface. Lambda block provides the implementation of the run() method of the
runnable interface. It is possible because runnable interface is a functional interface and
provided target type for the lambda expression.
Page 65 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
CHAPTER - X
MULTITHREADING
2. Threads are lightweight sub-processes, they share the common memory space. In
Multithreaded environment, programs that are benefited from multithreading, utilize the
maximum CPU time so that the idle time can be kept to minimum.
Before we begin with the programs(code) of creating threads, let’s have a look at
these methods of Thread class. We have used few of these methods in the example below.
Example 2:
Class CountextendsThread
{
Count()
{
super("my extending thread");
System.out.println("my thread created"+this);
start();
}
publicvoid run()
{
try
{
for(int i=0;i<10;i++)
{
System.out.println("Printing the count "+ i);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("my thread interrupted");
Page 67 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
}
System.out.println("My thread run is over");
}
}
Class ExtendingExample
{
publicstaticvoid main(Stringargs[])
{
Countcnt=newCount();
try
{
while(cnt.isAlive())
{
System.out.println("Main thread will be alive till the child thread is live");
Thread.sleep(1500);
}
}
catch(InterruptedException e)
{
System.out.println("Main thread interrupted");
}
System.out.println("Main thread's run is over");
}
}
Output:
my thread createdThread[my runnable thread,5,main]
Main thread will be alive till the child thread is live
Printing the count 0
Printing the count 1
Main thread will be alive till the child thread is live
Printing the count 2
Main thread will be alive till the child thread is live
Printing the count 3
Printing the count 4
Main thread will be alive till the child thread is live
Printing the count 5
Main thread will be alive till the child thread is live
Printing the count 6
Printing the count 7
Main thread will be alive till the child thread is live
Printing the count 8
Main thread will be alive till the child thread is live
Printing the count 9
mythread run is over
Main thread run is over
Page 68 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
System.out.println("My thread is in running state.");
}
publicstaticvoid main(Stringargs[]){
MultithreadingDemoobj=newMultithreadingDemo();
Threadtobj=newThread(obj);
tobj.start();
}
}
Output:
My thread isin running state.
Example Program 2:
Observe the output of this program and try to understand what is happening in this
program. If you have understood the usage of each thread method then you should not face
any issue, understanding this example.
Class CountimplementsRunnable
{
Threadmythread;
Count()
{
mythread=newThread(this,"my runnable thread");
System.out.println("my thread created"+mythread);
mythread.start();
}
publicvoid run()
{
try
{
for(int i=0;i<10;i++)
{
System.out.println("Printing the count "+ i);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("my thread interrupted");
}
System.out.println("mythread run is over");
}
}
classRunnableExample
{
publicstaticvoid main(Stringargs[])
{
Countcnt=newCount();
try
{
while(cnt.mythread.isAlive())
{
Page 69 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
System.out.println("Main thread will be alive till the child thread is live");
Thread.sleep(1500);
}
}
catch(InterruptedException e)
{
System.out.println("Main thread interrupted");
}
System.out.println("Main thread run is over");
}
}
Output:
my thread createdThread[my runnable thread,5,main]
Main thread will be alive till the child thread is live
Printing the count 0
Printing the count 1
Main thread will be alive till the child thread is live
Printing the count 2
Main thread will be alive till the child thread is live
Printing the count 3
Printing the count 4
Main thread will be alive till the child thread is live
Printing the count 5
Main thread will be alive till the child thread is live
Printing the count 6
Printing the count 7
Main thread will be alive till the child thread is live
Printing the count 8
Main thread will be alive till the child thread is live
Printing the count 9
mythread run is over
Main thread run is over
Thread priorities
Thread priorities are the integers which decide how one thread should be treated with
respect to the others.
Thread priority decides when to switch from one running thread to another, process is
called context switching
A thread can voluntarily release control and the highest priority thread that is ready to
run is given the CPU.
A thread can be preempted by a higher priority thread no matter what the lower
priority thread is doing. Whenever a higher priority thread wants to run it does.
To set the priority of the thread setPriority() method is used which is a method of the
class Thread Class.
In place of defining the priority in integers, we can
use MIN_PRIORITY, NORM_PRIORITY or MAX_PRIORITY.
Page 70 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
CHAPTER – XI
THREAD METHODS & APPLETS
Methods: isAlive() and join()
In all the practical situations main thread should finish last else other threads which
have spawned from the main thread will also finish.
To know whether the thread has finished we can call isAlive() on the thread which
returns true if the thread is not finished.
Another way to achieve this by using join() method, this method when called from the
parent thread makes parent thread wait till child thread terminates.
These methods are defined in the Thread class.
We have used isAlive() method in the above examples too.
Synchronization
Multithreading introduces asynchronous behavior to the programs. If a thread is writing
some data another thread may be reading the same data at that time. This may bring
inconsistency.
When two or more threads need access to a shared resource there should be some way
that the resource will be used only by one resource at a time. The process to achieve
this is called synchronization.
To implement the synchronous behavior java has synchronous method. Once a thread is
inside a synchronized method, no other thread can call any other synchronized method
on the same object. All the other threads then wait until the first thread come out of the
synchronized block.
When we want to synchronize access to objects of a class which was not designed for
the multithreaded access and the code of the method which needs to be accessed
synchronously is not available with us, in this case we cannot add the synchronized to
the appropriate methods. In java we have the solution for this, put the calls to the
methods (which needs to be synchronized) defined by this class inside a synchronized
block in following manner.
The process of testing a condition repeatedly till it becomes true is known as polling.
Polling is usually implemented with the help of loops to check whether a particular condition is
true or not. If it is true, certain action is taken. This waste many CPU cycles and makes the
implementation inefficient.
For example, in a classic queuing problem where one thread is producing data and other is
consuming it.
To avoid polling, Java uses three methods, namely, wait(), notify() and notifyAll().
All these methods belong to object class as final so that all classes have them. They must be
used within a synchronized block only.
wait()-It tells the calling thread to give up the lock and go to sleep until some other
thread enters the same monitor and calls notify().
notify()-It wakes up one single thread that called wait() on the same object. It should be
noted that calling notify() does not actually give up a lock on a resource.
notifyAll()-It wakes up all the threads that called wait() on the same object.
This program might only run in offline IDEs as it contains taking input at several points.
filter_none
edit
play_arrow
brightness_4
// Java program to demonstrate inter-thread communication
// (wait(), join() and notify()) in Java
importjava.util.Scanner;
publicclassthreadexample
{
Page 72 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
Public static void main(String args[])
Throws InterruptedException
{
finalPC pc = newPC();
// t1 finishes before t2
t1.join();
t2.join();
}
Page 73 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
// consume() methods.
Public static class PC
{
// Prints a string and waits for consume()
publicvoidproduce()throwsInterruptedException
{
// synchronized block ensures only one thread
// running at a time.
synchronized(this)
{
System.out.println("producer thread running");
// Sleeps for some time and waits for a key press. After key
// is pressed, it notifies produce().
publicvoidconsume()throwsInterruptedException
{
// this makes the produce thread to run first.
Thread.sleep(1000);
Scanner s = newScanner(System.in);
// Sleep
Thread.sleep(2000);
}
}
}
}
Output:
producer thread running
Waiting for return key.
Page 74 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
Return key pressed
Resumed
As monstrous as it seem0073, it really is a piece of cake if you go through it twice.
1. In the main class a new PC object is created.
2. It runs produce and consume methods of PC object using two different threads
namely t1 and t2 and wait for these threads to finish.
Lets understand how our produce and consume method works.
First of all, use of synchronized block ensures that only one thread at a time runs. Also since
there is a sleep method just at the beginning of consume loop, the produce thread gets a kickstart.
When the wait is called in produce method, it does two things. Firstly it releases the lock it holds
on PC object. Secondly it makes the produce thread to go on a waiting state until all other threads have
terminated, that is it can again acquire a lock on PC object and some other method wakes it up by
invoking notify or notifyAll on the same object.
Therefore we see that as soon as wait is called, the control transfers to consume thread and it
prints -“Waiting for return key”
After we press the return key, consume method invokes notify(). It also does 2 things- Firstly,
unlike wait(), it does not releases the lock on shared resource therefore for getting the desired result, it
is advised to use notify only at the end of your method. Secondly, it notifies the waiting threads that
now they can wake up but only after the current method terminates.
As you might have observed that even after notifying, the control does not immediately passes
over to the produce thread. The reason for it being that we have called Thread.sleep() after notify(). As
we already know that the consume thread is holding a lock on PC object, another thread cannot access
it until it has released the lock. Hence only a 0fter the consume thread finishes its sleep time and
thereafter terminates by itself, the produce thread cannot take back the control.
If you are still confused as to why we have used notify in consume thread, try removing
it and running your program again. As you must have noticed now that the program never
terminates.
The reason for this is straightforward-When you called wait on produce thread, it went
on waiting and never terminated. Since a program runs till all its threads have terminated, it
runs on and on.
There is a second way round this problem. You can use a second variant of wait().
void wait(long timeout)
Sometimes, suspending the execution of a thread is useful. For example, a separate thread can
be used to display the time of day. If user does not want a clock, then its thread can be suspended.
Whatever the case, suspending a thread is a simple matter. Once suspended, restarting the thread is
also a simple matter.
Page 75 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
The mechanisms to suspend, resume, and stop threads differ between early versions of Java,
such as Java 1.0, and modern versions, beginning with Java 2. Prior to Java 2, a program used
the suspend(), resume(), and stop() methods, which are defined by the Thread, to pause, restart, and
stop the execution of a thread. Although these methods seem to be a perfectly reasonable and
convenient approach to managing the execution of threads, they must not be used for new Java
programs.
Assume that a thread has obtained locks on the critical data structures. If that thread is
suspended at that point, those locks are not relinquished. Other threads that may be waiting for those
resources can be deadlocked.
Assume that a thread is writing to a critically important data structure and has
completed only part of its changes. If that thread is stopped at that point, that data structure
might be left in a corrupted state. The trouble is that, the stop() causes any lock the calling
thread holds to be released. Thus, the corrupted data might be used by another thread that is
waiting on the same lock.
The following example illustrates how wait() and notify() methods that are inherited from
the Object can be used to control the execution of a thread. Let's consider its operation.
The NewThread class contains a boolean instance variable named suspendFlag which is used to control
the execution of the thread. It is initialized to false by the constructor. The run() method contains
a synchronized statement block that checks suspendFlag. If that variable is true, the wait() method is
invoked to suspend the execution of the thread. The mysuspend() method sets suspendFlag to true.
The myresume() method sets suspendFlag to false and invokes notify() to wake up the thread. Finally,
the main() method has been modified to invoke the mysuspend() and myresume()methods.
Page 76 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
String name; //name of thread
Thread thr;
booleansuspendFlag;
NewThread(String threadname)
{
name = threadname;
thr = new Thread(this, name);
System.out.println("New thread : " + thr);
suspendFlag = false;
thr.start(); // start the thread
}
Page 77 of 78
STUDY MATERIAL FOR BCA
JAVA PROGRAMMING
SEMESTER - III, ACADEMIC YEAR 2020 - 2021
v
class SuspendResumeThread
{
public static void main(String args[])
{
try
{
Thread.sleep(1000);
obj1.mysuspend();
System.out.println("Suspending thread One...");
Thread.sleep(1000);
obj1.myresume();
System.out.println("Resuming thread One...");
obj2.mysuspend();
System.out.println("Suspending thread Two...");
Thread.sleep(1000);
obj2.myresume();
System.out.println("Resuming thread Two...");
}
catch(InterruptedException e)
{
System.out.println("Main thread Interrupted..!!");
}
Page 78 of 78