SlideShare a Scribd company logo
UNIT II
12 hours
Defining a Package – Packages and Member Access – Importing Packages –
Defining, Implementing, Applying Interfaces – Interfaces Can Be Extended –
#Default Interface Methods# – Use static Methods in an Interface – Exception
Handling Fundamentals – Exception Types – Using try and catch – Multiple
catch Clauses – Nested try Statements – throw – throws – finally – Java’s Built-
in Exceptions – Creating Own Exception Subclasses – The Java Thread Model –
Creating a Thread – Creating Multiple Threads-Thread Priorities –
Synchronization – Interthread Communication.
Packages and Interfaces
PACKAGES
 A package can be defined as collection used for grouping a variety of classes and interfaces based
on their functionality.
 Classes and interfaces are grouped together in containers called packages.
 A package represents a directory that contains related group of classes and interfaces.
Advantages of using a package
1. Preventing naming conflicts. For example there can be two classes with name Employee in two
packages, college.staff.aided.Employee and college.staff.sf.Employee. These two classes can be
used in the same program and distinguished using the fully-qualified class name - package
name plus class name. This mechanism is called Namespace Management.
2. Making searching/locating and usage of classes, interfaces easier
3. Providing controlled access: protected and default have package level access control. A
protected member is accessible by classes in the same package and its subclasses. A default
member (without any access specifier) is accessible by classes in the same package only.
4. Packages can be considered as data encapsulation (or data-hiding).
5. Reusability: A class once developed can be reused by any number of programs wishing to
incorporate the class in that particular program.
Packages are divided into two categories:
1. Built-in Packages (packages from the Java API)
2. User-defined Packages (create your own
packages) - It is a collection of predefined
classes and interfaces
Java API Packages
Java APl (Application Program Interface) provides a large numbers of classes grouped into
different packages according to functionality.
1. java.lang – Core Classes and interfaces of Java Language(automatically imported in
all programs. )
2. java.util – Utility classes like Date, Calendar and Collections etc.
3. java.io – Classes and Interfaces for accessing Files and Streams
4. java.net – Classes and Interfaces for Network Programming
5. java.applet – Classes and Interfaces for Applet Programming
6. java.awt – Abstract Windowing Toolkit (AWT) for basic GUI
7. javax.swing – Swing Based Classes for Advanced and Platform Independent GUI
8. java.sql – Classes and Interfaces for database access (JDBC API)
9. javax.sql - the package that provides server-side database capabilities such as
connection
10.java.rmi— the package that lets Java applications make remote method invocations
on Java objects
How to check Pre defined methods in pre defined class
Syntax:
javap <fully qualified name>
Example:
•If we want to see all the methods present in
String class.
The command javap java.lang.String
Displays all the methods in the string class.
Example: Built-in packages
Example: java.util.Arrays class:
This class contains various methods for manipulating arrays (such as sorting
and searching).
import java.util.Arrays;
class JavaUtilExample {
public static void main(String args []) {
int[] intArray = {10,30,20,50,40};
Arrays.sort(intArray);
System.out.printf("Sorted array : %s",
Arrays.toString(intArray));
}
}
F:>java JavaUtilExample
Sorted array : [10, 20, 30, 40, 50]
User-defined packages or Defining a Package
• The users of the Java language
can also create their own
packages.
• They are called user-defined
packages.
• User defined packages can also
be imported into other classes &
used exactly in the same way as
the Built in packages.
Defining a Package:
SYNTAX:
package package name;
Example :
package packexample;
public class ClassinPackage
{ // body of the class
}
We must first declare the name of the
package using the package keyword followed
by the package name.
while declaring the package every
character must be in lower case.
The source file allow to declare only one
package and it must be the first statement in
a Java source file.
Then define a classes as normally as define
a class.
If you omit the package statement, the
class names are put into the default
package, which has no name.
More than one file can include the same
package statement.
The package statement simply specifies to
which package the classes defined in a file
belong.
Package Hierarchy
 Remember that packages are normal folders in the file system
 Java also supports the concept of package hierarchy.
 A set of packages shall be arranged in a hierarchal manner.
 This is done by specifying multiple names in a package statement, separated
by dots.
The general form of a multileveled package statement is shown here:
package pkg1[.pkg2[.pkg3]];
 All predefined packages are arranged in this manner.
java.awt.event.MouseEvent;
 Here awt package contains the event package and the event package contains
the MouseEvent class.
 Similarly the user defined packages all so be arranged in a hierarchal manner.
ex: college. compdept. mca. secondyear;
 Each package should be stored in a separate sub directory. The name of the
sub directory should be same as the name of the package.
 The source files for the package secondyear should be placed in a directory
named
college compdept mca secondyear;
 By convention name of each package should start with a lower case letter.
Java Packages and CLASSPATH
 Classpath is used for storing the path of the user-defined classes.
 Whenever we compile/execute any class file, jdk tools(javac and
java) search the package/class file in the current directory by
default.
 If the classes are not in the current directory, then we need to set
the classpath.
 CLASSPATH is an environment variable that tells the Java runtime
system where the classes are present
 (ie) classpath environment variable is used to specify the location
of the .class file
 When a packages is not created, all classes are stored in the
default package
 The default package is stored in the current directory.
 The current directory is the default directory for CLASSPATH.
Java Packages and CLASSPATH
 w.k.t, It is not mandatory that the main program and the package(s) to be at
the same location.
 How does the java run-time system know where to look for packages that you
create?
There are three options:
For example, consider the following package specification.
package mypackage;
1. Placing the package in the current working directory.
By default Java compiler and JVM searches the current working directory for
specified package(s) like mypackage.
Java Packages and CLASSPATH
2. Specifying the package(s) path using CLASSPATH environment variable.
Let’s assume that our package mypackage is stored at following location:
D:packagesmypackage
Then we can set the CLASSPATH environment variable (in command prompt) to
the location of the package as shown below:
set CLASSPATH = .;D:packages
The dot (.) before the path specifies the current working directory and multiple
paths can be separated using semi-colon (;)
3. Using the -classpath or -cp options with javac and java commands.
We can also use -classpath or -cp options (option 3) with javac and java
commands as
shown below:
javac -classpath .;D:packages Driver.java
Or
javac -cp .;D:packages Driver.java
In the above example, Driver.java is a main program which utilizes the classes in
the package mypackage.
compiling and executing packages
The java source file can be saved in any directory.
How to compile java package?
 To compile the Java programs with package statements, you have to use -d option as shown below.
Syntax:
javac -d Destination_folder file_name.java
Then a folder with the given package name is created in the specified destination, and the compiled
class files will be placed in that folder.
The -d option with javac command is used to specify the directory where the .class files needs to be
stored.
How to run a Java program with package?
We need to use fully qualified name
java packagename.classname
Example:
To Compile: javac -d . Simple.java
To Run: java mypack.Simple
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination. The .
represents the current folder.
Example:
package mypack;
class MyPackageClass {
public static void main(String[] args) {
System.out.println("This is my first
package!");
}
}
To compile and store the .class file in
the working directory
F:>javac -d . MyPackageClass.java
To run the MyPackageClass.java file,
F:>java mypack.MyPackageClass
output
This is my first package!
If we want to store the .class file
E:pack1mypack
Then we have to compile like
F:>javac -d e:pack1 MyPackageClass.java
To run the package from the root directory, we
have to set a path like this
F:>set classpath= .;E:pack1
F:>java mypack.MyPackageClass
This is my first package!
Example;
package empPack;
class EmpClass
{
String empName;
double salary;
EmpClass(String name, double sal)
{
empName = name;
salary = sal;
}
void display()
{
System.out.println(empName + " : $"+salary);
}
}
class EmpSal
{
public static void main(String args[])
{
EmpClass emp[] = new EmpClass[4];
emp[0] = new EmpClass("A.D Tedd",450.20);
emp[1] = new EmpClass("D.M Scott",725.93);
emp[2] = new EmpClass("B.W TayLor",630.80);
emp[3] = new EmpClass("T.N Blair",545.60);
for (int i=0; i<4; i++) emp[i].display();
}
}
F:>javac -d . EmpSal.java
F:>java empPack.EmpSal
A.D Tedd : $450.2
D.M Scott : $725.93
B.W TayLor : $630.8
T.N Blair : $545.6
Packages and Member Access
Packages act as containers for classes and other subordinate packages. Classes act as
containers for data and code.
 The class is Java’s smallest unit of abstraction. Because of the interplay between classes and
packages, Java addresses four categories of visibility for class members:
1.Subclasses in the same package.
2.Non-subclasses in the same package.
3.Subclasses in different packages.
4.Classes that are neither in the same package nor subclasses.
 A class has only two possible access levels: default and public.
Packages and Member Access
 Public - Anything declared public can be accessed from
anywhere.
 Private - Anything declared private cannot be seen outside of
its class.
 Package - When a member does not have an explicit access
specification, it is visible to subclasses as well as to other
classes in the same package. - This is the default access.
 Protected - If you want to allow an element to be seen
outside your current package, but only to classes that
subclass your class directly
Class Member Access
type Public Private default protected
Same class yes Yes yes yes
Same
package sub
class
yes no yes yes
Same
package non
sub class
yes no yes Yes
Diff.package
sub class
yes no no yes
Diff package
non sub class
yes no no no
Importing or Using Packages
 An import statement is used to access the classes that are stored in other packages.
 An import statement must appear after the package statement but before any class declaration.
 There are three ways of accessing the classes stored in a package.
1.Selected classes in packages can be imported:
Syntax:
import packagename.classname;
Examples:
1.java.awt.Colour;
2. import mypackage1.Square;
2. All classes in packages can be imported:
Syntax:
import packagename.*;
Examples:
1. import java.awt.*;
2. import mypackage1.*;
Importing or Using Packages
3. using fully qualified name (Accessing package without import keyword)
We can access the class of a package without importing it. In that case we will have to use the name of
class with it's package name
For example,consider the example,
import java.util.*;
class MyDate extends Date {
}
The same example without the import statement looks like this:
class MyDate extends java.util.Date {
}
Here, Date is fully-qualified
Example2:
mypackage1.Square s = new mypackage1.Square();
Note:
If you use fully qualified name then only declared class of this package will be accessible. Now there is no
need to import. But you need to use fully qualified name every time when you are accessing the class or
interface.
 All of the standard Java classes included with Java are stored in a package called java.
 The basic language functions are stored in a package inside of the java package called java.lang. Since
Java is useless without much of the functionality in java.lang, it is implicitly imported by the compiler for
all programs.
 If a class with the same name exists in two different packages that you import using the star form, the
compiler will remain silent, unless you try to use one of the classes.
Subpackages
Package inside the package is called the subpackage.
Subpackage can also be designed in hierarchy, i.e. one package can be a part of another package.
This can be achieved by specifying multiple names of the packages at various levels of hierarchy,
separated by dots(.).
For e.g.
package rootPackage.subPackage;
Example:
1.java.awt.event.MouseEvent;
2.college. compdept. mca. secondyear;
Note
When a package is imported any of its sub packages will not be imported.
Example: import java.awt.*;
When this statement in used in the program all the classes and interfaces that are defined in the
package awt such as Graphics class will be imported but the classes and interfaces that are defined in
any sub packages of the awt such as the event sub package will not be imported.
Example: if you want import classes and interfaces in the event sub package we have to write the
import statement as
import java.awt.event.*
Example:
package pack1; // sub directory name pack1
public class add1 // source file add1.java
{
public int add(int m,int n)
{
return(m+n);
}
}
Compile this file using
F:>javac -d . add1.java
package pack2; // sub directory name pack2
public class sub1// source file sub1.java
{
public int sub(int m,int n)
{
return(m-n);
}
}
Compile this using
F:>javac -d . sub1.java
// in the root directory
import pack1.*;
import pack2.*;
class math// source file name math.java
{
public static void main(String args[])
{
int b,c;
add1 a=new add1();
sub1 s=new sub1();
b=a.add(10,5);
c=s.sub(10,5);
System.out.println("add 10+5="+b);
System.out.println("sub 10-5="+c);
}
}
Output:
------------
F:>javac math.java
F:>java math
add 10+5=15
sub 10-5=5
 It is not necessary to import a class, if it resides in the
same physical directory.
package p;
class B //B.java
{
void display()
{ System.out.println("I am in B");
}
}
class C //C.java
{
void display()
{ System.out.println("I am in C");
}
}
class packDemo1 //packDemo1.java
{
public static void main(String args[])
{
B b=new B();
b.display();
C c=new C();
c.display();
}
F:>javac -d . packDemo1.java
F:>java p.packDemo1
I am in B
I am in C
Example of package by import fully qualified name
Without using import statement, you can still access classes and interfaces stored in a
separate package by using their fully qualified name.
But this is not considered a good practice, and you should avoid using it.
//Save as Square.java
package mypackage1;
public class Square
{
public void area(int side)
{
System.out.println("Area of square =
"+side*side);
}
}
//Save as Test.java
package mypackage2;
class Test
{
public static void main(String args[])
{
mypackage1.Square s = new mypackage1.Square();
//access classes using their fully qualified name.
s.area(5);
}
}
Output
F:>javac -d . Square.java
F:>javac -d . Test.java
F:>java mypackage2.Test
Area of square = 25
Interfaces
 The interfaces are extension of abstract classes
 The abstract class contains abstract methods & normal methods
 Interfaces are used to declare the functionality declarations but not definition.
 Interfaces are used to achieve full abstraction.
 Java Does not support Multiple Inheritance directly.
 Multiple inheritance can be achieved in java by the use of interfaces.
Defining an Interface
 An interfaces is a collection of abstract methods and final fields.
 Therefore, it is the responsibility of the class that implements an interface to supply the code for
methods.
 A class can implement any number of interfaces, but cannot extend more than one class at a time.
 We cannot create an object for an interface but we can create references.
 Once it is defined, any number of classes can implement an interface.
 Also, one class can implement any number of interfaces.
 The methods in interface are abstract by default.
 The variables in interface are final by default.
Reasons for using interfaces
There are mainly two reasons to use interface.
1. It is used to achieve abstraction.
2. By interface, we can support the functionality of multiple inheritance.
Defining an Interface
General form of an Interface
An interface is defined much like a class.
interface InterfaceName
{
final type var_name1 = vlaue;
final type var_name2 = vlaue;
...............
return_type method_name1(parameter-list);
return_type method_name2(parameter-list);
...............
}
Here Interface is the key word and InterfaceName is any valid java
variable(Just like class names).
Examples:
1.interface Area
{
final static double pi= 3.142;
float compute (float x,float y);
void show ();
}
2.public interface IArea
{
double PI = 3.142;
void area();
}
CLASS INTERFACE
1. The members of a class can be constant or
variables
1. The members of an interface are always
declared as constant.
2. The class definition can contain the code for
each of its methods
2. The methods in interface are abstract in nature
i.e. there is no code associated with them.
3. It can be instantiated by declaring objects 3. It cannot be used to declare objects
4. It can use various specifiers like public, private,
protected
4. It can only use the public access specifier
Differences between Class and Interface
Differences between an abstract class and an interface
Abstract class Interface
An abstract class contains some abstract
methods and also some concrete
methods.
An interface contains only abstract
methods.
An abstract class contain instance
variables also.
An interface cannot contain instance
variables. It contains only constants.
All the abstract methods of the abstract
class should be implemented in its sub
classes.
All the (abstract) methods of the
interface should be implemented in its
implementation classes.
Abstract class is declared by using the
keyword abstract.
Interface is declared using the keyword
interface.
Implementing Interfaces
Classes implement interfaces using the implements keyword
Once an interface has been defined, one or more classes can implement that
interface.
To implement an interface, include the implements clause in a class definition,
and then create the methods defined by the interface.
The general form of a class that includes the implements clause looks like this:
access class classname [extends superclass] [implements interface [,interface...]] {
// class-body
}
Here, access is either public or not used.
If a class implements more than one Interface, the interfaces are separated with
a comma.
The methods that implement an interface must be declared public.
Also, the type signature of the implementing method must match exactly the
type signature specified in the interface definition.
Example: implementing
interfaces
interface Shape2D
{
double computeArea( );
}
class Circle implements Shape2D
{
int radius;
Circle(int radius)
{
this.radius = radius;
}
public double computeArea( )
{
return 3.14 * radius * radius;
}
}
class CircleDemo
{
public static void main(String[ ] args)
{
Circle obj = new Circle(10);
System.out.println(obj. computeArea( ));
}
}
Output
314.0
Example2:
interface Calculator {
int add(int a,int b);
int subtract(int a,int b);
int multiply(int a,int b);
int divide(int a,int b);
}
class Normal_Calculator implements Calculator
{
public int add(int a,int b){ return a+b;}
public int subtract(int a,int b){ return a-b;}
public int multiply(int a,int b){return a*b;}
public int divide(int a,int b){return a/b;}
}
class intefacetest
{
public static void main(String args[])
{ Normal_Calculator c=new Normal_Calculator();
System.out.println("Value after addition = "+c.add(5,2));
System.out.println("Value after Subtraction = "+c.subtract(5,2));
System.out.println("Value after Multiplication = "+c.multiply(5,2));
System.out.println("Value after division = "+c.divide(5,2));
}
F:>javac intefacetest.java
F:>java intefacetest
Value after addition = 7
Value after Subtraction = 3
Value after Multiplication = 10
Value after division = 2
Accessing Implementations Through Interface References
The following example calls the callback( ) method via
an interface reference variable:
interface MyInterface {
void callback(int param);
}
class Client implements MyInterface{
// Implement Callback's interface
public void callback(int p) {
System.out.println("callback called with " + p);
}
}
public class Main {
public static void main(String args[]) {
MyInterface c = new Client();
c.callback(42);
}
}
We can create a reference for an
interface then again we can assign
that reference to the implemented
class object and then this
reference can be used to access
the method version disfigured in
the implemented class.
 This is one of the key features
of the interface. This process is
similar of using the super class
references for accessing the sub
class overridden methods.
Output:
callback called with 42
Nested Interfaces
An interface defined inside another interface or class is known as nested interface. Nested interface is also
known as inner interfaces or member interfaces.
Syntax:
interface OuterInterfaceName {
interface InnerInterfaceName {
// constant declarations
// Method declarations
}
}
 A nested interface can be declared as public, private, or protected. This differs from a top-level
interface, which must either be declared as public or use the default access level.
 When a nested interface is used outside of its enclosing scope, it must be qualified by the name of the
class or interface of which it is a member.
 Thus, outside of the class or interface in which a nested interface is declared, its name must be fully
qualified.
Nested Interfaces - Example
interface MyInterface {
void calculateArea();
interface MyInnerInterface {
int id = 20;
void print();
}
}
class NestedInterface implements MyInterface.MyInnerInterface
{
public void print() {
System.out.println("Print method of nested interface");
} }
class nestedinterDemo
{
public static void main(String args []) {
NestedInterface obj = new NestedInterface();
obj.print();
System.out.println(obj.id);
}
}
F:>javac nestedinterDemo.java
F:>java nestedinterDemo
Print method of nested interface
20
 Just as classes can be inherited, interfaces can also be inherited
 One interface can extend one or more interfaces using the keyword extends
 The syntax is the same as for inheriting classes.
 When a class implements an interface that inherits another interface, it must
provide implementations for all methods defined within the interface inheritance chain.
Note: 1.An interface can extend only one interface.(like a class can extend only one class)
2.It cannot extend a class.
3.A class can implement more than one interface and extend only one class
4. An interface cannot implement an interface.
Interfaces Can Be Extended
// One interface can extend another.
interface A {
void meth1();
void meth2();
}
// B now includes meth1() and meth2() -- it adds meth3().
interface B extends A {
void meth3();
}
// This class must implement all of A and B
class MyClass implements B {
public void meth1() {
System.out.println("Implement meth1().");
}
public void meth2() {
System.out.println("Implement
meth2().");
}
public void meth3() {
System.out.println("Implement
meth3().");
}
}
class IFExtend {
public static void main(String arg[]) {
MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}
}
Output:
Implement meth1().
Implement meth2().
Implement meth3().
Multiple Inheritance
 A class derived from more than one superclass is called multiple inheritance.
 Java doesn’t support multiple inheritance directly.
For instance a definition like
class A extends B extends C
{
…………..
…………..
} is not permitted in java.
 Java provide an alternate approach to implement multiple inheritance by interface.
class A extends B implements C // C is an interface
{
…………..
…………..
} is permitted in java.
 Although a java class cannot be a subclass of more than one super class ,it can be implement
more than one interface
 Multiple inheritance by interface occurs if a class implements multiple interfaces or also if an
interface itself extends multiple interfaces.
Example :Extending one class and implementing one
interface.
interface shape2
{
double getArea();
}
class shape
{
Void display()
{
System.out.println(“Name of the shape is circle”);
}
}
class circle extends shape implements shape2 //multiple
inheritance
{
int radius;
circle (int radius)
{
this.radius=radius;
}
public getArea()
{
retrun Math.PI*radius*radius;
}
}
class Demo
{
public static void main(String args[])
{
circle c=new circle(10);
c.display();
System.out.println(“The area of the circle”
+c.getArea());
}
}
Multiple Inheritance Using Interface
Example Program
interface vehicleone{
int speed=90;
public void distance();
}
interface vehicletwo{
int distance=100;
public void speed();
}
class Vehicle implements
vehicleone,vehicletwo{
public void distance(){
int distance=speed*100;
System.out.println("distance travelled is
"+distance);
}
public void speed(){
System.out.println("speed is "+speed);
}
}
class MultipleInheritinterface
{
public static void main(String args[])
{
System.out.println("Vehicle");
Vehicle obj = new Vehicle();
obj.distance();
obj.speed();
}
}
F:>javac MultipleInheritinterface.java
F:>java MultipleInheritinterface Vehicle
distance travelled is 9000
speed is 90
Exception Handling
There are basically 3 types of errors in a java
program:
1.Compile-time errors
2.Run-time errors
3.Logical errors.
1.Compile-time errors:
 All syntax errors will be detected and displayed by the Java compiler and these errors
are known as compiler-time errors.
 Whenever the compiler displays an error, it will not create the .class file.
The most common compile time errors are:
 Missing semicolons
 Missing brackets in classes and methods
 Misspelling of identifiers and keywords
Example:
class CError{
public static void main(String args[]){
System.out.println(“Compilation Error…..”)
}
}
D:>javac Cerror.java
CError.java:4: ';' expected
}
^
1 error
2.Run-time errors:
 A program may compile successfully creating a .class file but may not run properly.
 Such programs may produce wrong results due to wrong logic or may terminate such as stack
overflow.
Most common run time errors are:
 Dividing an integer by zero.
 Accessing an element that is out of bound of in an array.
 Trying to store a value into an array of an incompatible class or type.
 Passing a parameter that is not in a valid range or value for a method
Example:
class RError{
public static void main(String args[]){
int a=10,b=0;
System.out.println(“a/b: ”+(a/b));
}
}
D:>javac RError.java
D:>java RError
Exception in thread "main" java.lang.ArithmeticException: / by zero
at RError.main(RError.java:4)
3.Logical errors:
 A logic error (or logical error) is a mistake in a program's source code that results in
incorrect or unexpected behavior.
 Logical errors means the logic of the program is wrong and these are identified after
observing the output.
 These errors depict flaws in the logic of the program.
 The programmer might be using a wrong formula or the design of the program itself is
wrong.
 Logical errors are not detected either by the java compiler or JVM.
 The programmer is solely responsible for them.
class LError{
int sum(int a,int b){
return a-b;
}
public static void main(String args[]){
LError le=new LError();
System.out.println("Sum is: "+le.sum(20,10));
}
}
D:>javac LError.java
D:>java LError
Sum is: 10
What is an Exception?
 An Exception is an abnormal situation (or) unexpected situation in the normal flow of
the program execution.
(ie) unexpected event that disturbs normal flow of the program is
called exception.
 An exception is an abnormal condition that arises in a code sequence at run
time. In other words, an exception is a run-time error.
Because of Exceptions the flow of program execution is getting disturbed so that program
execution may continue (or) may not be continued.
 Examples
Division by zero
Attempts to use an array index out of bounds.
Number input in wrong format
Unable to write output to file
Missing input file
Exception Handling
 Exception Handling is a mechanism to handle runtime errors
Meaning of exception handling
Exception handling doesn't mean repairing an exception. We have to define alternative way to
continue rest of the program normally. This way of defining alternative is nothing but exception
handling.
Objective of Exception handling
It is highly recommended to handle exceptions. The main objective of exception
handling is to maintain the normal flow of the Java program.
In a language without exception handling
When an exception occurs, control goes to the operating system, where a message is displayed
and the program is terminated.
In a language with exception handling
Programs are allowed to trap some exceptions, thereby providing the possibility of fixing the problem
and continuing
Exception-Handling Fundamentals
 A Java exception is an object that describes an exceptional condition that has
occurred in a piece of code.
 When an exceptional condition arises, an object representing that exception
is created and thrown in the method that caused the error.
 Exceptions needs to be handled so that appropriate actions can be taken.
 Programmer can also provide exception handling code. However if there is no
exception handling code present during runtime and exception occurs, then java
interpreter provides default exception handler.
 Default Exception Handler displays the name of the exception object in string
form and stops the execution of the program.
 However , programmer can provide exception handling code and program’s
execution can continue even after the occurrence of exception.
Java exception handling is managed by via five keywords: try, catch, throw, throws, and
finally.
1) try – Java try block is used to enclose the code that might throw an exception.
2) catch – Java catch block is used to handle the Exception. It must be used after the
try block only
3) finally – Java finally block is always executed whether exception is handled or
not. Java finally block follows try or catch block.
4) throw –throw keyword is used to manually create and throw an exception
object.
5) throws – If a method which raises exceptions doesn’t want to handle them, they
can be thrown to parent method or the Java run-time using the throws keyword.
Difference between Exception and Error
 An exception is an error which can be handled. It means an exception happens, the
programmer can do something to avoid any harm.
 But an error is an error which cannot be handled, it happens and the programmer
cannot do anything.
• General form of an exception-handling
block
try{
// block of code to monitor for errors
}
catch (ExceptionType1 exOb){
// exception handler for
ExceptionType1
}
catch (ExceptionType2 exOb){
// exception handler for
ExceptionType2
}
//…
finally{
// block of code to be executed before try
block ends
}
Note:
Once an exception is
thrown , program control
transfers out of the try
block into the catch block.
Once the catch statement
is executed program
control continues with the
next line following the
entire try/catch
mechanism.
…
Java Exception Class Hierarchy or Exception Types
Object
Error
Throwable
Exception
VirtualMachineError
Ex: Stack overflow
IOException
…
RuntimeException
…
ArithmeticException
NullPointerException
IndexOutOfBoundsException
Unchecked
Checked
NoSuchElementException
FileNotFoundException
EOFException
…
Exceptions are recoverable. Most of the cases
exceptions are raised due to program code only.
Errors are non-recoverable. Most of the cases
errors are due to lack of system resources but not
due to our programs.
 All exception types are subclasses of the built-in class Throwable
 Throwable class has two direct subclasses named Exception and Error
1.Exception . The Exception class has subclasses that describe problems
encountered during execution. These subclasses include
ClassNotFoundException, NoSuchFieldException,
NoSuchMethodException, and RuntimeException.
The RuntimeException class has additional subclasses like
ArithmeticException, ArrayIndexOutOfBoundsException,
NullPointerException, and NumberFormatException
2. Error The Error class represents problems within the virtual machine.
This includes memory exhaustion error, stack overflow error, illegal
access error and other serious problems. Error classes are generally
not caught and result in program termination.
 The Throwable class defines two useful methods
like getMessage() and printStackTrace(), that can be used to handle
exceptions.
Uncaught Exceptions or Default Exception Handling
class Exc0 {
public static void main(String args[])
{
int d = 0;
int a = 42 / d;
}
}
class Exc1 {
static void subroutine() {
int d = 0;
int a = 10 / d;
}
public static void main(String args[]) {
Exc1.subroutine();
}
}
java.lang.ArithmeticException: / by zero
at Exc0.main(Exc0.java:4)
java.lang.ArithmeticException: / by zero
at Exc1.subroutine(Exc1.java:4)
at Exc1.main(Exc1.java:7)
 When the Java run-time system detects the attempt to divide by zero, it constructs a new
exception object and then throws this exception.
 This causes the execution of Exc0 to stop, because once an exception has been thrown, it must
be caught by an exception handler and dealt with immediately.
 In this example, we haven’t supplied any exception handlers of our own, so the exception is
caught by the default handler provided by the Java run-time system.
 Any exception that is not caught by your program will ultimately be processed by the default
handler.
 The default handler displays a string describing the exception, prints a stack trace from the
point at which the exception occurred, and terminates the program.
There are two drawbacks in the default exception handling Mechanism.
1) Always reports the exception in a predefined formats.
2) After reporting an exception, it immediately terminates the execution of the program.
 The overcome these drawbacks programmer can provide exception handling code and
program’s execution can continue even after the occurrence of exception.
Using try and catch
Handling an exception has two benefits,
1) It allows you to fix the error
2) It prevents the program from automatically terminating.
 To guard against and handle a run-time error, simply enclose the code that you
want to monitor inside a try block.
 Immediately following the try block, include a catch clause that specifies the
exception type that you wish to catch.
 Once an exception is thrown, program control transfer out of the try block into
the catch block
 Once the catch statement has executed, program control continues with the
next line in the program following the entire try/catch mechanism
 To illustrate how easily this can be done, the following program includes a try
block and a catch clause which processes the ArithmeticException generated
by the division-by-zero error:
Using try and catch - Example
Without try catch
class Testexcep
{
public static void main(String[] args){
System.out.println("statement1:This will
be printed");
System.out.println(42/0);
System.out.println("statement3:This will
not be printed");
}
}
output
F:>javac Testexcep.java
F:>java Testexcep
statement1:This will be printed
Exception in thread "main"
java.lang.ArithmeticException: / by
zero
at Testexcep.main(Testexcep.java:5)
With try catch
class Testexep1
{
public static void main(String[] args){
System.out.println("statement1:This will be printed");
try{
System.out.println(42/0);
}
catch(ArithmeticException e){
System.out.println(42/2);
}
System.out.println("statement3:This will also be
printed");
}}
output
F:>javac Testexep1.java
F:>java Testexep1
statement1:This will be printed
21
statement3:This will also be printed
Example2:
class Exc2 {
public static void main(String args[]) {
int d, a;
try { // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e) { // catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
Output:
Division by zero.
After catch statement.
Method to Print Exception Information
Throwable class defines the following methods to print exception
information to the console.
1.getMessage(): Returns a string that describes the exception that
occurred.
If we use getMessage() method then print only i)description
2.toString(): Returns a string made up of the specific exception class
name and the error message.
If we use toString() method then it will i) print name of exception and
ii) description .
3.printStackTrace(): Displays the sequence of method calls that led to
the exception to the standard error stream
If we use printStackTrace() method then it will i)print name of
exception, ii) description and iii)where exception occur.
Example 2:Printing exception message – getMessage() and printStackTrace()
An exception message can be printed in three ways. The first way is printing the
exception object thrown by the JVM. The other two are using the methods of
Throwable class – getMessage() and printStackTrace().
1. Printing exception object.
class printmessage {
public static void main(String[]
args)
{ try {
System.out.println(10/0); }
catch(ArithmeticException e) {
System.out.println(e);
}
} }
H:>javac printmessage.java
H:>java printmessage
java.lang.ArithmeticException: /
by zero
2. Using getMessage()
class printmessage1 {
public static void
main(String[] args)
{
try {
System.out.println(10/0); }
catch(ArithmeticException e) {
System.out.println(e.getMess
age());
}
} }
H:>javac printmessage1.java
H:>java printmessage1
/ by zero
3. Using printStackTrace()
class printmessage2 {
public static void
main(String[] args) {
try {
System.out.println(10/0); }
catch(ArithmeticException
e) { e.printStackTrace();
}
} }
H:>javac
printmessage2.java
H:>java printmessage2
java.lang.ArithmeticExceptio
n: / by zero at
printmessage2.main(printme
ssage2.java:3)
 The above three screenshots can infer you the following information.
 System.out.println(e) prints the exception class name
(java.lang.ArithmeticException) and also the exception message ( / by
zero).
 System.out.println(e.getMessage()) prints exception message ( / by
zero) only indicating the cause of exception.
 e.printStackTrace() prints the exception class name with the message
particulars and also the line number where the problem arises (traces
the actual problem).
When more than one exception can be raised by a single piece
of code, several catch clauses can be used with one try block:
each catch catches a different kind of exception
when an exception is thrown, the first one whose type matches that
of the exception is executed
after one catch executes, the other are bypassed and the execution
continues after the try/catch block
Multiple Catch Clauses
Example
class MultiCatch {
public static void main( String args[] ) {
int num1, num2;
try {
num1 = Integer.parseInt(args[0]);
num2 = Integer.parseInt(args[1]);
System.out.println("The quotient is " +
(num1/num2));
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Invalid Number of
arguments!");
System.out.println("the error is "+ e );
}
catch (NumberFormatException e) {
System.out.println("Please enter integers!");
System.out.println("the error is "+ e );
}
catch (ArithmeticException e) {
System.out.println("Error in denominator!");
System.out.println("division by zero!");
System.out.println("the error is "+ e );
}
finally {
System.out.println("Thank you for using this
program.");
}
}
}
output
J:>javac MultiCatch.java
J:>java MultiCatch 5 2
The quotient is 2
Thank you for using this program.
J:>java MultiCatch 23.2 5
Please enter integers!
the error is java.lang.NumberFormatException:
For input string: "23.2"
Thank you for using this program.
J:>java MultiCatch 25 0
Error in denominator!
division by zero!
the error is java.lang.ArithmeticException: / by
zero
Thank you for using this program.
J:>java MultiCatch 25
Invalid Number of arguments!
the error is
java.lang.ArrayIndexOutOfBoundsException:
1
Thank you for using this program.
Single catch
 Single catch can handle multiple exceptions
 The catch statement in the next example catches exception
objects of Exception and all its subclasses.
Example – single catch
public class CatchException2 {
public static void main( String args[] ) {
int num1, num2;
try {
num1 = Integer.parseInt(args[0]);
num2 = Integer.parseInt(args[1]);
System.out.println("The sum is " + (num1+num2));
}
catch (Exception e) {
System.out.println("The error : " + e.toString());
System.out.println(
"Usage : java AddTwoIntegers <num1>
<num2>");
}
}
}
>java CatchException2
The error : java.lang.ArrayIndexOutOfBoundsException: 0
Usage : java AddTwoIntegers <num1> <num2>
>java CatchException2 A B
The error : java.lang.NumberFormatException: For input
string: "A"
Usage : java AddTwoIntegers <num1> <num2>
Message stored in the
Exception object e
Nested try Statements
 Some times, a part of one block may cause an exception and the
entire block may cause another exception.
 In such a case, exception handlers have to be nested.
 That is, a try statement can be inside the block of another try.
 When nested try blocks are used, inner try block is executed first.
 If no matching catch block is encountered, catch blocks of outer try
blocks are inspected until all nested try statements are executed.
 If no catch statement matches, then the Java run-time system will
handle the exception.
Example
class Nested_Try
{
public static void main (String args [ ] )
{
try
{
int a = Integer.parseInt (args [0]);
int b = Integer.parseInt (args [1]);
int quot;
try
{
quot = a / b;
System.out.println(quot);
}
catch (ArithmeticException e)
{
System.out.println("divide by zero");
}
}
catch (NumberFormatException e)
{
System.out.println ("Incorrect argument type");
}
}
output
F:>java Nested_Try 24 6
4
F:>java Nested_Try 24 a
Incorrect argument type
F:>java Nested_Try 24 0
divide by zero
throw statement or throwing exceptions
 We have seen earlier in all the programs of exception handling that Java runtime
system was responsible for identifying exception class, creating its object, and
throwing that object.
 JVM automatically throws system generated exceptions. All those exceptions are
called implicit exceptions.
 If we want to throw an exception manually or explicitly, for this, Java provides a
keyword throw.
 (ie) The keyword “throw” is used to hand over user created exception objects to the
JVM (Java Virtual Machine) manually. If “throw” is not used to throw an exception
instance and the exception occurs, then the runtime system internally throws the
exception instance to JVM and the program terminates abnormally.
 Throw in Java is a keyword that is used to throw a built-in exception or a user
defined exception explicitly or manually.
 Using throw keyword, we can throw either checked or unchecked exceptions in java
programming.
throw statement or throwing exceptions
 When an exception occurs in the try block, throw keyword transfers the
control of execution to the caller by throwing an object of exception.
 Only one object of exception type can be thrown by using throw keyword at a
time.
 Throw keyword can be used inside a method or static block provided that
exception handling is present.
 The throw keyword is mainly used to throw custom exception. We will see custom
exceptions later.
The general form of throw is shown here:
throw ThrowableInstance;
 Here, ThrowableInstance must be an object of type Throwable or a subclass of
Throwable.
Note:
• The flow of execution stops immediately after the throw statement; any
subsequent statements are not executed.
• The nearest enclosing try block is inspected to see if it has a catch
statement that matches the type of exception. If it does find a match,
control is transferred to that statement.
• If not, then the next enclosing try statement is inspected, and so on. If
no matching catch is found, then the default exception handler halts the
program and prints the stack trace.
The result of following 2 programs are exactly same
class Ex
{
public static void main(String[] args)
{
System.out.println(50/0);
}
}
F:>javac Ex.java
F:>java Ex
Exception in thread "main"
java.lang.ArithmeticException: / by zero
at Ex.main(Ex.java:4)
Note:
In this case ArithmeticException object created
implicitly and handover to the JVM
automatically by the main method.
class ExwithThrow
{
public static void main(String[] args)
{
throw new ArithmeticException("/ by zero");
}
}
F:>javac ExwithThrow.java
F:>java ExwithThrow
Exception in thread "main"
java.lang.ArithmeticException: / by zero
at ExwithThrow.main(ExwithThrow.java:5)
Note:
In this case we created exception object
explicitly using throw keyword and
handover that object to the JVM manually.
 There are two ways you can obtain a Throwable object:
1. creating one with the new operator.
The general form is
throw new Exception( message);
here the message is optional
Example:
if(secondNumber == 0) throw new ArithmeticException("Error in denominator");
2. using a parameter into a catch clause
The general form is
throw exceptionReference;
Example:
catch ( ArithmeticException e)
{
System.out.println(“Arithmetic error has occurred”);
throw e; // rethrow the exception
}
Example -throw Statement
class Testthrow{
void validate(int age)
{
if(age<18)
throw new ArithmeticException(" age not valid");
else
System.out.println("welcome to vote");
}
}
class testexception {
public static void main(String args[]){
Testthrow t = new Testthrow();
t. validate(Integer.parseInt (args[0]));
System.out.println("rest of the code...");
}
}
F:>javac testexception.java
Note: when we enter age<18 an ArithmeticException
is raised and thrown to the user. Because, We are
not properly handle the exception, therefore JVM
handles the exception in its own way.
(ie) In this case we are creating exception object
explicitly and handover to the JVM manually.
F:>java testexception 13
Exception in thread "main"
java.lang.ArithmeticException: age not valid
at Testthrow.validate(testexception.java:5)
at testexception.main(testexception.java:14)
when we enter age>18 an ArithmeticException is not
raised, the program executed fully.
F:>java testexception 34
welcome to vote
rest of the code...
Example -throw Statement with try catch
class Testthrow{
void validate(int age)
{
if(age<18)
throw new ArithmeticException(" age not
valid");
else
System.out.println("welcome to vote");
}
}
class testexception1 {
public static void main(String args[]){
Testthrow t = new Testthrow();
try{
t. validate(Integer.parseInt (args[0]));
}
catch(ArithmeticException ae){
System.out.println(ae);
//throw ae; // rethrow the exception
}
System.out.println("rest of the code...");
}
}
Note:
Here we handle the exception with try catch block,
Therefore the program executed completely.
F:>javac testexception1.java
F:>java testexception1 34
welcome to vote
rest of the code...
F:>java testexception1 13
java.lang.ArithmeticException: age not valid
rest of the code...
Note1:
we can use try catch in the validate method also like
void validate(int age)
{
if(age<18)
try{throw new ArithmeticException(" age not valid");}
catch(ArithmeticException ae){
System.out.println(ae);
}
else
System.out.println("welcome to vote");
}
}
Example -throw Statements
public int division(int firstNumber, int secondNumber){
if(secondNumber == 0)
{ArithmeticException ae = new ArithmeticException(" Error in denominator");
throw ae;
}
/*The above two statements can be simplified by using a single statement
throw new ArithmeticException("Error in denominator");*/
return firstNumber/secondNumber;
}
}
class throwtest
{
public static void main(String args[]){
ThrowDemo d = new ThrowDemo();
try{
d.division(12,0);
}
catch(ArithmeticException ae){
System.out.println(ae);
throw ae; // rethrow the exception
}
}
}
H:>javac throwtest.java
H:>java throwtest
java.lang.ArithmeticException: Error in
denominator
Exception in thread "main"
java.lang.ArithmeticException: Error in
denominator
at ThrowDemo.division(throwtest.java:5)
at throwtest.main(throwtest.java:19)
Throws clause or Declaring Exceptions
 A method, instead of handling an exception by itself using try .. catch, it can simply instruct the
caller method to handle the exception by making use of throws keyword along with the method
signature.
 (ie) Throws gives an information to the programmer that there may occur an exception so it is
better for the programmer to provide the exception handling code so that normal flow can be
maintained.
 The 'throws' keyword is used to delegate (hand over) the exception handling mechanism to the
caller of the function
 It requires in the case of checked exception.
 In our program if there is any chance of raising checked exception then compulsory we should
handle either by try catch or by throws keyword otherwise the code won't compile.
 This is necessary for all exceptions, except those of type Error or RuntimeException, or any of their
subclasses.
 All other exceptions that a method can throw must be declared in the throws clause.
Throws clause or Declaring Exceptions
The syntax is
 This tells methods to other methods
"If you call me, you must handle any exceptions that I throw.”
 If you don’t want the exception to be handled in the same function you can use the
throws class to handle the exception in the calling function.
In our program if there is any chance of raising checked exception then it is compulsory to
handle the exception either by
1. By using try-catch block
2. By using throws keyword
otherwise the code won't compile.
Note: "throws" keyword required only to convince complier. Usage of throws keyword
doesn't prevent abnormal termination of the program.
type method-name(parameter-list) throws exception-list{
// body of method
}
Here, exception-list is a comma-separated list of the exceptions that a method can throw.
1. example using throws clause
// here we are not catching the thrown exception, we are
// declaring it in the throws clause of the calling method
import java.io.*;
public class input {
public static void main(String args[]) throws IOException
{ //program code
System.out.print("Please enter a string: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
System.out.println("You entered: " + s);
}
}
Input operations can cause run-time exceptions. The previous program chose
not to catch them but to propogate them out of main - hence the throws
IOException clause. In the next example, we catch such exceptions within the
program.
74
2.Example of catching an exception using a try/catch block
import java.io.*;
public class exceptionExample {
public static void main(String args[])
{ //program code
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s ;
System.out.print("Please enter a string: ");
try {
s = br.readLine();
}
catch (IOException e) {
System.out.println( "Error when reading line from console");
}
System.out.println("You entered: " + s);
}
}
75
 If method1 calls method2 that has a throws clause in its method
header, method1 must:
 Use try-catch around the call to method2 (OR)
 Have a throws clause in its own method header
76
class thro
{
static String read() throws
IOException //method 2
{
BufferedReader br=new
BufferedReader(new
InputStreamReader(System.in));
String s=br.readLine ();
return s;
}
} output
J:>javac demo.java
J:>java demo
Enter a string
welcome
Received string is welcome
import java.io.*;
class demo
{ public static void main (String args[])//method1
{ try
{ System.out.println ("Enter a string");
String s =thro.read();
System.out.println ("Received string is "+ s);
}
catch (IOException e)
{ System.out.println ("IO error has occurred");
}
}
}
Difference between throw and throws in Java
No. throw throws
1)
Java throw keyword is used to
explicitly throw an exception.
Java throws keyword is used to
declare an exception.
2) Throw is followed by an instance. Throws is followed by class.
3) Throw is used within the method.
Throws is used with the
method signature.
4)
You cannot throw multiple
exceptions.
You can declare multiple
exceptions e.g.
public void method()throws
IOException,SQLException.
finally
 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 no exception is generated, the statements in the finally clause are executed after the statements
in the try block complete
 if an exception is generated, the statements in the finally clause are executed after the statements
in the appropriate catch clause complete
 Generally, finally block is used for freeing up resources, cleaning up code, db closing connection, io
stream, etc.
 A finally block is optional but at least one of the catch or finally blocks must exist with a try.
 Unlike catch, multiple finally blocks cannot be declared with a single try block. That is there can be
only one finally block with a single try block.
 Any time a method is about to return to the caller from inside a try/catch block, via an uncaught
exception or an explicit return statement, the finally clause is also executed just before the
method returns.
Example
public class finallyBlockExample
{
public static void main(String[] args)
{
int a = 20, b = 0;
try
{
System.out.println("Value of a: " +a);
System.out.println("Value of b: " +b);
int div = a/b;
System.out.println("Division: " +div);
}
catch(ArithmeticException ae)
{
System.out.println(ae); // prints corresponding exception.
}
finally
{
System.out.println("Denominator cannot be zero");
}
System.out.println("Hello Java");
}
}
F:>javac finallyBlockExample.java
F:>java finallyBlockExample
Value of a: 20
Value of b: 0
java.lang.ArithmeticException: / by zero
Denominator cannot be zero
Hello Java
Java's built-in Exceptions
Built-in exceptions are exceptions that are already available in
Java. These exceptions are thrown by the Java runtime system
to explain the exception condition
The default java.lang package provides several exception classes,
all sub-classing the RuntimeException class.
Two categories of Java's built in exception are :
1. Unchecked exception
2. Checked exception
1.Unchecked Exceptions (RunTimeException) :
The exceptions which are not checked by the compiler whether programmer
handling or not ,are called 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.
All Unchecked exceptions are direct sub classes of RuntimeException class.
 Unchecked Exceptions are unchecked by compiler.
 If Unchecked exception is caught then exception handling code will be executed and
program’s execution continues.
 If Unchecked exception is not caught then java interpreter will provide the default
handler. But in this case execution of the program will be stopped by displaying the
name of the exceptions object.
 RuntimeException, Error and their subclasses are known as unchecked
exceptions.
 The most Common examples are ArrayIndexOutOfBoundException, NUllPointerException
,ClassCastException
Unchecked Exceptions
LinkageError
Error
Throwable
ClassNotFoundException
VirtualMachineError
IOException
Exception
RuntimeException
Object
ArithmeticException
NullPointerException
IndexOutOfBoundsException
Many more classes
Many more classes
Many more classes
IllegalArgumentException
Unchecked
exception.
Unchecked RuntimeExceptions defined in java.lang
Exception Description
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsExce
ption
Array index is out-of-bounds.
ArrayStoreException Assignment to an array element of an
incompatible type.
IllegalArgumentException Illegal argument used to invoke a method.
IllegalStateException Environment or application is in incorrect state.
IndexOutOfBoundsException Some type of index is out-of-bounds.
NegativeArraySizeException Array created with a negative size.
NullPointerException Invalid use of a null reference.
NumberFormatException Invalid conversion of a string to a numeric
format.
SecurityException Attempt to violate security.
StringIndexOutOfBounds Attempt to index outside the bounds of a string.
2. Checked Exceptions (Compile Time Exception):
The exceptions which are checked by the compiler for smooth execution of the program at Runtime are
called checked exceptions.
A checked exception is one which always deals with compile time errors.
Checked exceptions are checked at compile-time.
If a method is throwing a checked exception then it should handle the exception using
1. try-catch block or
2. it should declare the exception using throws keyword,
otherwise compilation error will occur in the program.
 Checked Exceptions are checked by the Java compiler.
 If Checked exception is caught then exception handling code will be executed and program’s execution
continues.
 If Checked exception is not caught then java interpreter will provide the default handler. But in this
case execution of the program will be stopped by displaying the name of the exceptions object.
 Exceptions other than RuntimeException, Error and their subclasses are known as checked exceptions,
meaning that the compiler forces the programmer to check and deal with the exceptions.
 The most perfect example of Checked Exceptions is IOException which should be handled in your code
Compulsorily or else your Code will throw a Compilation Error.
Checked Exceptions Defined in java.lang.
Exception Description
ClassNotFoundException Class not found.
IllegalAccessException Access to a class is denied.
InstantiationException Attempt to create an object of an abstract
class or interface.
InterruptedException One thread has been interrupted by
another thread.
NoSuchFieldException A requested field does not exist.
NoSuchMethodException A requested method does not exist.
Creating Your Own Exception Subclasses or User
Defined Exception or custom Exception
 Custom exceptions in Java are those exceptions which are created by a programmer to
meet their specific requirements of the application.
 We can create our own exception types to handle situations specific to our
applications.
Examples:
InvalidAgeException
InvalidRollNumberexception
MarksOutOfBoundsException
UnauthorizedRequestException etc
 We can create our own exceptions by creating a subclass of the class “Exception”
which is a subclass of “Throwable”.
 There is no need to implement any methods, since our class already extends
“Exception”, all the methods available in it are accessible in our class also.
 We can also override one or more of these methods in exception classes that you
create.
 An exception class is like any other class, containing useful fields and methods.
 Custom exceptions are used to customize the exceptions and messages according to
user needs.
steps to create user defined or custom exception
Step 1: Create a new class whose name should end with Exception like
ClassNameException. This is a convention to differentiate an exception class
from regular ones.
Examples:
AgeException, MarksOutOfBoundsException
Step 2: Make the class extends one of the exceptions which are subtypes of
the java.lang.Exception class.
User-defined exceptions can be created simply by extending Exception class.
This is done as:
class MyException extends Exception{
// body of the class
}
Step 3: If you do not want to store any exception details, define a default
constructor (without any parameter)in your exception class.
MyException()
{
}
steps to create user defined or custom exception
Step 4: If you want to store exception details, define a parameterized
constructor with string as a parameter, call super class (Exception)
constructor from this, and store variable “str”.
MyException(String str)
{
super(str); // Call super class exception constructor and store
variable "str" in it.
}
Step 5: In the last step, we need to create an object of user-defined
exception class and throw it using throw clause.
MyException obj = new MyException ("Exception details");
throw obj;
or,
throw new MyException("Exception details");
Note:
Custom Exception and constructors:
 It is necessary to initialize the base class as the first step before construction of the derived class
object.
 If no explicit call is made then Java will call the default no parameter constructor of the Exception
class and the message/cause will be missed.
 Therefore, it is good practice to use the super keyword to call the parameterized constructor of
the base class and initialize it with the error message.
To display the message override the toString() method or, call the superclass
parameterized constructor by passing the message in String format.
The Methods Defined by Throwable
Method Description
Throwable fillInStackTrace( ) Returns a Throwable object that contains a
completed stack trace. This object can be
rethrown.
Throwable getCause( ) Returns the exception that underlies the
current exception. If there is no underlying
exception, null is returned.
String getMessage( ) Returns a description of the exception.
Throwable initCause(Throwable
causeExc)
Associates causeExc with the invoking exception
as a cause of the invoking exception. Returns a
reference to the exception.
void printStackTrace( ) Displays the stack trace.
String toString( ) Returns a String object containing a description
of the exception. This method is called by
println( ) when outputting a Throwable object.
• The user-defined Exception class also inherits the methods defined in the
Throwable class.
• The following table lists the various methods defined by the Throwable class:
Custom exception types
1. The custom checked exceptions are exceptions that extend java.lang.Exception.
They are recoverable in nature and are handled explicitly.(can be recovered either by
try- catch or by throws otherwise compilation error)
(ie) Whenever a superclass is Exception then that type of User defined Exception is
Checked Exception. ( (ie)need to use either try-catch or throws)
E.g., class XYZException extends Exception{
// body of the class
}
2. The custom unchecked exceptions extend java.lang.RuntimeException. They are
unrecoverable in nature.(can not be recovered either by try- catch or by throws
otherwise Runtime error)
 (ie) If the superclass is RuntimeException then that user defined Exception is
unchecked Exception.( ie no need to use try- catch or throws clause)
E.g., class XYZException extends RunTimeException{
//body of the class
}
 If user can take some action to recover from the expected error then make the custom
exception a checked exception (i.e. inheriting from Exception class). On the other
hand if user cannot do anything useful in case of error then make the custom
User Defined unchecked Exception – Example
If the superclass is RuntimeException then that user
defined Exception is unchecked Exception.( ie no
need to use try- catch or throws clause)
Example:
import java.util.*;
class InvalidAgeException extends RuntimeException {
// Declare parameterized constructor with String as a
parameter.
InvalidAgeException(String s){
super(s); // Call super exception class constructor.
} }
class Demo{
static void validate(int age) throws InvalidAgeException{
if(age<18){
// Create an object of user defined exception and throw it
using throw clause.
throw new InvalidAgeException(" your age is " + age +"
Not eligible to vote");
}
else{
System.out.println(" your age is " + age +" Welcome to
Vote");
} }
}
class throwtest
{
public static void main(String args[]) {
Demo t1 = new Demo();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the age ");
int n =sc.nextInt();
t1.validate(n);
System.out.println("rest of the code...");
} }
Output
F:>javac throwtest.java
F:>java throwtest
Enter the age
12
Exception in thread "main" InvalidAgeException:
your age is 12 Not eligible to
Vote at Demo. Validate(throwtest.java:10)
at throwtest.main(throwtest.java:26)
F:>java throwtest
Enter the age
20
your age is 20 Welcome to Vote
rest of the code...
User Defined checked Exception – Example
Whenever a superclass is Exception then that type of
User defined Exception is Checked Exception. (
(ie)need to use either try-catch or throws)
Example:
import java.util.*;
class InvalidAgeException extends Exception {
// Declare parameterized constructor with String as a
parameter.
InvalidAgeException(String s){
super(s); // Call super exception class constructor.
} }
class Demo{
static void validate(int age) throws InvalidAgeException{
if(age<18){
// Create an object of user defined exception and throw
it using throw clause.
throw new InvalidAgeException(" your age is " + age +"
Not eligible to vote");
}
else{
System.out.println(" your age is " + age +" Welcome to
Vote");
} }
}
class throwtest2
{ public static void main(String args[]) throws
InvalidAgeException {
Demo t1 = new Demo();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the age ");
int n =sc.nextInt();
t1.validate(n); // if throws clause not used in the
//main(), we have to use try catch or
//t.validate(n)
System.out.println("rest of the code...");
} }
Output
F:>javac throwtest.java
F:>java throwtest
Enter the age
12
Exception in thread "main" InvalidAgeException:
your age is 12 Not eligible to
Vote at Demo. Validate(throwtest.java:10)
at throwtest.main(throwtest.java:26)
F:>java throwtest
Enter the age
20
your age is 20 Welcome to Vote
Multithreaded Programming
 A task or Process is a program in execution
 Multitasking :running more than one program (process) concurrently
 A thread is a single sequential flow of control within a program. (A
segment of code in a program).
 Threads are parts of a program that run on their own while the rest
of the program does something else
 Single-threaded program can handle one task at any time.
 Multithreading – a special type of multi tasking in which single
program is divided into several pieces called thread and each thread
is permitted to proceed simultaneously
Multithreading
 The process of executing multiple threads simultaneously (concurrently) is
called multithreading in Java.
 A program that contains multiple flow of control is known as multithreaded
program.
 Multithreading allows single processor to run several concurrent threads.
 A single program can perform two tasks using two threads
 multithreading is a specialized form of multitasking
 Most modern operating systems support multithreading
Ex: in a Web browser we may do the following tasks at the same time:
 1. scroll a page,
 2. download an applet or image,
 3. play sound,
 4 print a page.
 An application or applet can have many threads doing different things independently.
 In single processor systems, the multiple threads share CPU time and the operating system is responsible for
scheduling and allocating resources to them.
 This is possible because most of the time the CPU is idle
 Example: Receiving the input data from the user downloading images etc.
 We can walk, talk, breath, ear, smell all the same time.
 Computer can download a file, print a file, receive e-mail, run the clock all at the same time.
Advantages of Multithreading
1. Multithreading allows making maximum use of the CPU because idle time can be reduced.
2. It lets you tackle different tasks independently, leaving the problems of time sharing among the tasks to the OS
or virtual machine.
3. Inter-thread communication is inexpensive and content switching from one thread to the next is low cost.
The main application areas of multithreading are:
 To implement Multimedia graphics
 To develop animations
 To develop video games
 To develop web and application etc
Multi Tasking
 The ability to perform more than one task (program)at the same time is called multitasking.
Multitasking is divided into two types
1. Process based multitasking: (Multiprocessing)
 A process is a program that is executing.
 Process-based multitasking is the feature that allows your computer to run two or more programs
concurrently.
 In process-based multitasking, a program is the smallest unit of code that can be dispatched by the
scheduler.
 For example, process-based multitasking enables you to run the Java compiler at the same time that you
are using a text editor or browsing the internet.
2.Thread based Multitasking : (Multithreading )
A thread is a single sequential flow of control within a program. (A segment of code in a program).
 In a thread-based multitasking environment, the thread is the smallest unit of dispatchable code.
 In a thread-based multitasking a single program can perform two or more tasks simultaneously.
 For Example, a text editor can format text at the same time that it is printing, as long as these two actions
are being performed by two separate threads.
 Whenever thread is created it will not occupy any separate memory. But it will share the memory which
is already allocated to a program.
The differences between process-based and thread-
based multitasking:
Process-based multitasking handles the concurrent
execution of programs.
Thread-based multitasking deals with the concurrent
execution of pieces of the same program.
Note: In a single processor system the processor is
doing only one job at a time. However the processor
switches between the processes is so fast that it
appears to human being that all are being done
simultaneously.
Difference between Multithreading and Multitasking
Differences between a process and a Thread
Multithreading Multitasking
Multithreading refers to multiple
threads of control within a single
program
each program can run multiple
threads of control within it, e.g.,
Web Browser
Multitasking refers to a computer's
ability to perform multiple jobs
concurrently
more than one program are
running concurrently, e.g., UNIX
Process Thread
1) A process is a program that is currently in
execution.
1) A thread is a single sequential flow of
control within a program
2) Processes are heavy weight tasks that
require their own separate address space
2) A thread is a light weight and shares the
same address space.
3) Inter process communication is expensive
and limited.
3) The inter thread communication is
inexpensive and context switching from
thread to another is low cost.
The Java Thread Model
Single-Threaded Systems
 Single-threaded systems use an approach called an event loop with polling.
 In this model:
A single thread of control runs in an infinite loop
Polling a single event queue to decide which instruction to execute next
Until this instruction returns, nothing else can happen in the system
This results in wastage of precious CPU cycles
Java’s Multithreading Model
 The benefit of Java’s multithreading is that the event loop/polling
mechanism is eliminated. One thread can pause without stopping other
parts of your program.
 When a thread blocks in a Java program, only the single thread that is
blocked pauses; All other threads continue to run.
All the libraries and classes are designed with multithreading in mind
The Java Thread Model
Java thread model is designed based on the following concepts:
Thread states:
 Threads can be in several states like running, ready, suspended, blocked, resumed.
Thread Priorities:
 Each thread has its own priority in Java. Thread priority is an absolute integer value.
 Thread priority decides only when a thread switches from one running thread to next, called context switching.
 Priority does increase the running time of the thread or gives faster execution.
Synchronization:
 When two or more threads need access to a shared resource it is called as race condition
 To avoid this race condition we need to use a mechanism called as synchronization.
 synchronization is the act of allowing only one thread at a time to execute code within a method or a block.
 Java provides a simple methodology to implement synchronization.
Messaging:
 A program is a collection of more than one thread. Threads can communicate with each other
 Java threads communicate with each other through notify() notifyall() and wait() methods.
Creating a Thread:
Java defines two ways by which a thread can be created.
1. By implementing the Runnable interface.
2. By extending the Thread class.
Single Thread System Vs. Multi Thread System
 Single-thread System use an
approach called an event loop
with pooling.
 A Single thread of control runs
in an infinite loop, pooling a
single event queue to decide
what to do next.
 In a single-threaded
environment, when a thread
blocks because it is waiting for
some resources the entire
program stops running.
 The advantage of multi threading is
that the main loop, pooling
mechanism is eliminated.
 Multithreading enables us to write
very efficient programs that make
maximum use of CPU. Because
ideal time can be kept to a
minimum.
 One thread can pause with out
stopping other parts of the
program. Java supports multi
threading.
Life Cycle of a Thread or Thread State
A thread can be in one of the five states.
1.New State: MyThread t=new MyThread();.
 The thread is in new state if you create an instance of Thread class but before the invocation of start() method. At
this point, the thread is considered not alive.
2. Runnable (Ready) State: t.start()
 A thread start its life from Runnable state.
 When the start() method is called on a new thread, thread enters into a runnable state.
 In runnable state, thread is ready for execution and is waiting for availability of the processor (CPU time).
 A thread can come into runnable state from running, waiting, or new states.
3.Running State:
 Running means Processor (CPU) has allocated time slot to thread for its execution. When thread scheduler
selects a thread from the runnable state for execution, it goes into running state.
 In running state, processor gives its time to the thread for execution and executes its run method. This is the state
where thread performs its actual functions. A thread can come into running state only from runnable state.
4.Blocked (Non-Runnable) State:
 A thread is considered to be in the blocked state when it is suspended, sleeping, or waiting for some time in order
to satisfy some condition.
5.Dead (Terminated) State:
 A thread can be considered dead when its run() method completes.
 If any thread comes on this state that means it cannot ever run again.
JAVA 2-studenttrreadexeceptionpackages.pdf
Life Cycle of a Thread(Contd..)
 Starting from the birth of a thread, till its death, a thread exists in different states which are
collectively called “Thread Life Cycle”.
 A thread will be born when it is created using Thread class as:
Thread obj=new Thread();
 A thread goes into runnable state when start() method is applied on it.
 That is void start() method is used to call the public void run() method.
 From runnable state, a thread may get into not-runnable state, when sleep() or wait() or
suspend() methods act on it.
 notify() and resume() methods are used to restart waiting and suspended threads respectively.
 yield() method causes the currently executing thread object to temporarily pause and allow other
threads to execute.
 ThreadDeath class will be invoked whenever the stop() method is called.
Life Cycle of a Thread(Contd..)
 Starting from the birth of a thread, till its death, a thread exists in different states which are
collectively called “Thread Life Cycle”.
 A thread will be born when it is created using Thread class as:
Thread obj=new Thread();
 A thread goes into runnable state when start() method is applied on it.
 That is void start() method is used to call the public void run() method.
 From runnable state, a thread may get into not-runnable state, when sleep() or wait() or
suspend() methods act on it.
 notify() and resume() methods are used to restart waiting and suspended threads respectively.
 yield() method causes the currently executing thread object to temporarily pause and allow other
threads to execute.
 ThreadDeath class will be invoked whenever the stop() method is called.
Syntax of the method purpose
void start( ) used to start a new thread.
void stop() to stop the running thread even before the completion of the task.
void run( ) This method encapsulates the functionality of a thread. This method is
always overridden
Boolean isAlive( ) returns true if the thread is alive
void setName(Strings) To set the name of the specified thread
String getName( ) To return the name of the specified thread.
void setPriority(int p) To set the priority of the specified thread to p
int getPriority(int p) To return the priority of the specified thread.
Join() wait for a thread to terminate
Void resume( ) resumes execution of a suspended thread
suspend( ) suspends a thread
static Thread currentThread() return the reference to the currently working thread
static void sleep(long m) To cause the current thread to wait for m milliseconds
void yield() to bring the blocked thread to ready to run mode
Methods in the Thread class:
The Main Thread
 In every java program, there is always a thread running internally. This thread is used by
JVM to execute the program statements.
 When a Java program starts up, one thread begins running immediately.
 This is usually called the main thread of your program, because it is the one that is executed
when your program begins.
The main thread is important for three reasons:
 It is the parent thread from which other child threads will be spawned or created.
 The main thread must be the last thread to finish execution, because it performs various
shutdown actions.
 When the main thread stops, the program terminates.
Example:
class CurrentThreadDemo{
public static void main(String st[]){
System.out.println(“Let us find the current thread…..”);
Thread t = Thread.currentThread();
System.out.println(“Current Thread= ”+t);
System.out.println(“It’s name= ”+t.getName());
}
}
Let us find the current thread…..
Current Thread= Thread[main,5,main]
It’s name= main
Note: In Thread[main,5,main]” , the square bracket, the first value, main represents the
name of thread; second value 5 represents the priority (normal priority)of main thread.
Creating a Thread
A new thread can be created in two ways:
1. By extending Thread class (java.lang.Thread)
2. By implementing Runnable interface (java.lang.Runnable)
Both of them have a method named run(). The JVM will call this method when a thread starts executing. You
can think of the run() method as a starting point for the execution of a thread, just like the main() method,
which is the starting point for the execution of a program.
By extending the Thread class
You need to override the run() method when you want to extend the Thread class. If you don’t override the run()
method, the default run() method from the Thread class will be called, which does nothing.
Note: the default implementation run() method in the Thread class does nothing, if you want your thread to do
some meaningful work, you need to still define it.
By implementing the Runnable interface
The Runnable interface declares the run() method, so you must define the run() method in your class if you
implement the Runnable interface.
Note: Inside run( ), you will define the code that constitutes the new thread.
run() method should be declared as public void run().
1.Creating threads by Extending the Thread Class
1. Declare the class as extending the Thread class.
Ex: class Myclass extends Thread{
…..
}
2. Implement the run( ) method that is responsible for executing the sequence of code that
the thread will execute.
Public void run()
{
….
}
3. Create an object to the class.
Myclass obj=new Myclass();
4. Run the thread using obj.start() method. //invokes run() method
class One extends Thread{ //Single thread example using
public void run(){ // “extends Thread”
for(int i=0;i<5;i++){
System.out.println("i value: "+i);
}
}
}
class ThreadDemo{
public static void main(String sree[]){
One o=new One();
o.start();
}
}
i value: 0
i value: 1
i value: 2
i value: 3
i value: 4
2. Creating threads by Implementing the ‘Runnable’ Interface
1.Declare the class as implementing the Runnable interface.
Ex: class Myclass implements Runnable{
…..
}
2.Implement the run( ) method.
Public void run()
{
….
}
3. Create an object to the class.
Myclass obj=new Myclass();
4. Create a thread and attach the thread to the object obj.
Thread t = new Thread(obj);
5. Run the thread using t.start() method.
//Example : single thread using runnable
class Thread3 implements Runnable //step1
{
public void run ( ) //step 2
{
for (int i = 1; i<= 10; i++)
{
Thread.sleep (1000);
System.out.println ("welcome to java");
}
} }
class ThreadDemo3
{
public static void main (String[] args)
{
Thread3 rx = new Thread3();
Thread t3 = new Thread (rx);// step 3
t3.start(); // step 4
}
}
J:>javac ThreadDemo3.java
J:>java ThreadDemo3
welcome to java
welcome to java
welcome to java
welcome to java
welcome to java
welcome to java
welcome to java
welcome to java
welcome to java
welcome to java
Difference between “extends Thread” and “implements Runnable” :
 Both are functionally same.
 But when we write extends Thread, there is no scope to extend another class, as multiple
inheritance is not supported in java.

class MyClass extends Thread, AnotherClass //invalid
 If we write implements Runnable, then still there is scope to extend another class.
class MyClass extends AnotherClass implements Runnable //valid
 This is definitely advantageous when the programmer wants to use threads and also
wants to access the features of another class.
Creating Multiple Threads
 So far, we have been using only two threads: the main thread and one
child thread
 However, our program can spawn as many threads as it needs
 In multithreading, Threads do not run sequentially (like function calls), so
the order of execution of threads is not predictable.(ie) In other words,
threads run asynchronously
 The threads are running concurrently on their own.
 Note that the output from the threads are not specially sequential.
 They do not follow any specific order.
 They are running independently of one another and each executes
whenever it has a chance.
 Remember that once the threads are started, we cannot decide with
certainty the order in which they may execute statements.
The following example is a program spawning multiple threads:
Example://Multi thread example using
//“extends Thread”
class Fivetable extends Thread
{
public void run ( )
{
for (int i= 1;i<=10;i++ )
System.out.println(i+"x 5 = "+(i*5));
System.out.println(“Exit from Fivetable ");
}
}
class Seventable extends Thread
{
public void run ( )
{
for(int i=1;i<=10;i++)
System.out.println(i+"x 7 = "+(i*7));
System.out.println(“Exit from Seventable");
}
}
class Ninetable extends Thread
{
public void run ( )
{
for(int i=1;i<=10;i++)
System.out.println(i+“x 9="+(i*9));
System.out.println(“Exit from Ninetable ");
}
}
class Table
{
public static void main(String[] args)
{
Fivetable f = new Fivetable( );
Seventable s = new Seventable ( );
Ninetable n = new Ninetable ( )
f.start ( );
s.start ( );
n.start ( );
}
}
1x 5 = 5
2x 5 = 10
3x 5 = 15
4x 5 = 20
5x 5 = 25
6x 5 = 30
1x 7 = 7
2x 7 = 14
3x 7 = 21
4x 7 = 28
5x 7 = 35
6x 7 = 42
7x 7 = 49
8x 7 = 56
9x 7 = 63
10x 7 = 70
Exit from
Seventable
1x 9 = 9
2x 9 = 18
3x 9 = 27
4x 9 = 36
5x 9 = 45
6x 9 = 54
7x 9 = 63
8x 9 = 72
9x 9 = 81
10x 9 = 90
Exit from Ninetable
7x 5 = 35
8x 5 = 40
9x 5 = 45
10x 5 = 50
Exit from Fivetable
class One implements Runnable{
public void run(){
for(int i=0;i<5;i++){
System.out.println("i value: "+i);
}
}
}
class Two implements Runnable{
public void run(){
for(int j=10;j>4;j--){
System.out.println(“j value: "+j);
}
}
}
class RunnableDemo{
public static void main(String sree[]){
One o=new One();
Thread t1=new Thread(o);
t1.start();
Two t=new Two();
Thread t2=new Thread(t);
t2.start();
}
}
H:>javac RunnableDemo.java
H:>java RunnableDemo
i value: 0
i value: 1
j value:10
i value: 2
j value:9
i value: 3
j value:8
i value: 4
j value:7
j value:6
j value:5
//Multi thread example using “implements Runnable”
Thread Priorities
 The thread of the same priority are given equal treatment by the Java scheduler
and, therefore, they share the processor on a first-come, first-serve basis.
 But, Priorities can be assigned to threads
 scheduler uses them to decide which thread gets to run
 Each thread is assigned a default priority of Thread.NORM_PRIORITY
(constant of 5).
 Java permits us to set the priority of a thread using the setPriority( ) method as
follows
ThreadName.setPriority(int Number);
 The intNumber is an integer value to which the thread’s priority is set. The Thread
class defines several priority constants:
MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
 Higher priorities threads gets more CPU time than the lower one
•To obtain the current priority setting of a thread:
final int getPriority( )
class Even extends Thread
{
public void run ( )
{
for (int i= 1;i<=200;i++ )
if(i%2==0) System.out.print(" "+i);
System.out.println (" Exit from Even");
} }
class Odd extends Thread
{
public void run ( )
{
for (int i= 1;i<=200;i++ )
if(i%2!=0) System.out.print(" " + i);
System.out.println (" Exit from Odd");
} }
class threadpri
{
public static void main(String[] args)
{
Even e = new Even();
Odd o= new Odd();
e.setPriority(Thread.MAX_PRIORITY );
o.setPriority(Thread.MIN_PRIORITY );
System.out.println("Thread 1 has priority " + e.getPriority());
System.out.println("Thread 2 has priority " + o.getPriority());
e.start();
o.start();
} }
H:>java threadpri
Thread 1 has priority 10
Thread 2 has priority 1
2 4 6 1 8 3 10 12 5 14 7 16 9 18 11 20 13 22
15 24 17 26 19 28 21 30
23 32 25 34 36 27 38 29 40 31 42 33 44 35
46 37 48 39 50 41 52 43 54
45 56 47 58 49 60 51 62 53 64 55 66 57 68
59 70 61 72 63 74 76 65 78
67 80 69 82 71 84 86 73 88 75 90 77 92 79
94 96 81 98 83 100 85 102
87 104 89 106 91 108 93 110 95 112 114 116
118 120 97 122 99 124 101 126
103 128 105 130 107 132 109 134 111 136
113 138 115 140 117 142 119 144
121 146 123 148 125 150 127 152 129 154
131 156 133 158 135 160 137 16
2 139 164 141 166 143 168 145 170 147 172
149 174 151 176 178 153 180 1
55 182 157 184 159 186 161 188 163 190 192
194 196 165 198 167 200 169
Exit from Even
171 173 175 177 179 181 183 185 187 189
191 193 195 197 199
Exit from Odd
Synchronization
 When two or more threads need access to a shared resource it is called as race condition
 To avoid this race condition we need to use a mechanism called as synchronization.
 synchronization is the act of allowing only one thread at a time to execute code within a method
or a block.
 For example, two unsynchronized threads accessing the same bank account may cause conflict.
 A shared resource may be corrupted if it is accessed simultaneously by multiple threads
 To avoid this java uses the concept of monitor(also called a semaphore). A monitor is an object
used as a mutually exclusive lock.
 At a time only one thread can access the Monitor. A second thread cannot enter the monitor
until the first comes out. Till such time the other thread is said to be waiting.
 Only methods (or blocks) can be synchronized, Classes and variable cannot be synchronized.
 Constructors cannot be synchronized. Code inside the constructors can be synchronized.
 Synchronization can be achieved in two ways:
1) Method level synchronization
2) Block level synchronization
 synchronization can not applied for classes and variables
 In method level synchronization the total data of method is sensitive. Where as in block level
synchronization part of the method is sensitive.
Synchronized Methods
 When a method created using a synchronized keyword, it allows only one object to access it at a
time.
 When an object calls a synchronized method, it put a lock on that method so that other objects or
thread that are trying to call the same method must wait, until the lock is released.
 Once the lock is released on the shared resource, one of the threads among the waiting threads
will be allocated to the shared resource.
The general form of synchronized method is:
synchronized type methodName(arg-list)
{ // synchronized methodbody
}
class Table{
synchronized void printTable(int n) {
for(int i = 1; i <= 15; i++)
System.out.println(i + " * " + n + " = " + i*n);
}
}
class MyThread_1 extends Thread{ // To call printTable() method Table object and n must required
Table table; // Declaration of variable table of class type Table.
int number; // declaration of number- n
MyThread_1(Table table, int number){ // Declare one parameterized constructor and pass variable table as a
parameter.
this.table = table;
this.number = number;
}
public void run() { // for ewvery thtread class,we should overide the run method
table.printTable(number);
}
}
class MyThread_2 extends Thread{ // To call printTable() method Table object and n must required
Table table; // Declaration of variable table of class type Table.
int number; // declaration of number- n
MyThread_2(Table table, int number){ // Declare one parameterized constructor and pass variable
table as a parameter.
this.table = table;
this.number = number;
}
public void run() {
table.printTable(number);
}
}
public class ThreadSynchronizationExample {
public static void main(String[] args) {
Table table = new Table();
MyThread_1 thread_1 = new MyThread_1(table, 2);
MyThread_2 thread_2 = new MyThread_2(table, 5);
thread_1.start();
thread_2.start();
}
}
Output without using Synchronized keyword
F:>javac ThreadSynchronizationExample.java
F:>java ThreadSynchronizationExample
1 * 2 = 2
2 * 2 = 4
1 * 5 = 5
3 * 2 = 6
2 * 5 = 10
4 * 2 = 8
3 * 5 = 15
5 * 2 = 10 Irregular output
4 * 5 = 20
6 * 2 = 12
5 * 5 = 25
7 * 2 = 14
6 * 5 = 30
8 * 2 = 16
7 * 5 = 35
9 * 2 = 18
8 * 5 = 40
10 * 2 = 20
9 * 5 = 45
10 * 5 = 50
Output with Synchronized keyword
F:>javac ThreadSynchronizationExample.java
F:>java ThreadSynchronizationExample
1 * 2 = 2
2 * 2 = 4
3 * 2 = 6
4 * 2 = 8
5 * 2 = 10
6 * 2 = 12
7 * 2 = 14
8 * 2 = 16
9 * 2 = 18 Regular output
10 * 2 = 20
1 * 5 = 5
2 * 5 = 10
3 * 5 = 15
4 * 5 = 20
5 * 5 = 25
6 * 5 = 30
7 * 5 = 35
8 * 5 = 40
9 * 5 = 45
10 * 5 = 50
import java.io.*;
class SavingAccounts
{ int account,balance;
SavingAccounts(int acc_num,int initial)
{ account = acc_num;
balance = initial; }
Public synchronized boolean withdrawal(int amount)
{ boolean result = false;
System.out.println("withdrawal from
account"+account);
System.out.println(" amount="+amount);
if (amount<= balance)
{ balance = balance-amount;
System.out.println("New balance="+ balance);
result = true;
} else
System.out.println("Insufficient amount");
System.out.println();
return result;
} }
class ATM extends Thread
{SavingAccounts account;
ATM (SavingAccounts savings)
{ account =savings; }
public void run()
{account.withdrawal(300);
}
}
public class ATM_Account
{ public static void main ( String args[])
{ SavingAccounts savings = new
SavingAccounts(4321,531);
ATM west = new ATM(savings);
ATM east = new ATM(savings);
west.start();
east.start();
}
}
output
----
withdrawal from account4321
amount=300
New balance=231
withdrawal from account4321
amount=300
Insufficient amount
After removing the word synchronized
The output will be
withdrawal from account4321
withdrawal from account4321
amount=300
amount=300
New balance=231
Insufficient amount
Synchronized Blocks
 If very few lines of the code required synchronization then it's never
recommended to declare entire method as synchronized we have to enclose those
few lines of the code with in synchronized block.
 The main advantage of synchronized block over synchronized method is it reduces
waiting time of Thread and improves performance of the system.
 In synchronized blocks, you use the synchronized keyword for a reference variable
and follow it by a block of code.
 A thread has to acquire a lock on the synchronized variable to enter the block; when
the execution of the block completes, the thread releases the lock.
The general form of synchronized Block is:
synchronized(this) {
// code segment guarded by the mutex lock
}
class Counter {
public static long count = 0;
}
class UseCounter implements Runnable
{
public void increment() {
synchronized(this) {
Counter.count++;
System.out.print(Counter.count + " ");
}
}
public void run() {
increment();
increment();
increment();
}
}
// This class creates three threads
public class DataRaceblock {
public static void main(String args[]) {
UseCounter c = new UseCounter();
Thread t1 = new Thread(c);
Thread t2 = new Thread(c);
Thread t3 = new Thread(c);
t1.start();
t2.start();
t3.start();
}
}
F:>javac DataRaceblock.java
F:>java DataRaceblock
1 2 3 4 5 6 7 8 9
Inter Thread Communication
 When multiple threads are running inside an application, most of them will need to communicate
with each other in some form.
 (ie)There may be cases where one of the created threads require data from another thread.
 Inter-thread communication can be defined as the exchange of messages between two or more
threads.
 Java achieves this through the usage of wait(), notify(), notifyAll() methods of the object class.
 These methods can be called only from within a synchronized method or synchronized block of
code otherwise, an exception named IllegalMonitorStateException is thrown.
 wait(), notify() and notifyAll() method present in Object class. Hence, these methods are available
to all classes
wait(), notify() and notifyAll() methods
Wait() method: The wait() method causes the current thread to wait until another thread
invokes the notify() or notifyAll() methods for that object. This method throws
InterruptedException.
Syntax: 1.public final void wait() throws InterruptedException
2. public final void wait(long millisecond) throws InterruptedException
notify() Method: The notify() method wakes up a single thread that called wait() method on
the same object.
Syntax: public final void notify()
notifyAll() Method: The notifyAll() method is used to wake up all threads that called wait()
method on the same object
Syntax: public final void notifyAll()
class Customer
{
int amount = 10000;
synchronized void withdraw(int amount)
{
System.out.println("Available Balance " + this.amount);
System.out.println("Going to withdraw." + amount);
if (this.amount < amount)
{
System.out.println("Insufficient Balance waiting for deposit.");
try
{
wait();
} catch (Exception e)
{
System.out.println("Interruption Occurred");
}
}
this.amount -= amount;
System.out.println("Detected amount: " + amount);
System.out.println("Balance amount : " + this.amount);
System.out.println("withdraw completed");
}
synchronized void deposit(int amount)
{
System.out.println("Going to deposit " + amount);
this.amount += amount;
System.out.println("Available Balance " + this.amount);
System.out.println("deposit completedn");
notify();
}
}
class InterThreadDemo
{
public static void main(String arg[])
{
Customer c = new Customer();
Thread t1= new Thread()
{
public void run()
{
c.withdraw(15000);
}
};
t1.start();
Thread t2= new Thread()
{
public void run()
{
c.deposit(10000);
}
};
t2.start();
}
}
output
F:>javac InterThreadDemo.java
F:>java InterThreadDemo
Available Balance 10000
Going to withdraw.15000
Insufficient Balance waiting for deposit.
Going to deposit 10000
Available Balance 20000
deposit completed
Detected amount: 15000
Balance amount : 5000
withdraw completed

More Related Content

PPTX
Java package
CS_GDRCST
 
PPTX
Packages in java
Elizabeth alexander
 
PDF
Class notes(week 7) on packages
Kuntal Bhowmick
 
DOCX
Class notes(week 7) on packages
Kuntal Bhowmick
 
PPTX
java package in java.. in java packages.
ArunPatrickK1
 
PPTX
java package java package in java packages
ArunPatrick2
 
PPT
9 cm604.26
myrajendra
 
DOCX
Unit4 java
mrecedu
 
Java package
CS_GDRCST
 
Packages in java
Elizabeth alexander
 
Class notes(week 7) on packages
Kuntal Bhowmick
 
Class notes(week 7) on packages
Kuntal Bhowmick
 
java package in java.. in java packages.
ArunPatrickK1
 
java package java package in java packages
ArunPatrick2
 
9 cm604.26
myrajendra
 
Unit4 java
mrecedu
 

Similar to JAVA 2-studenttrreadexeceptionpackages.pdf (20)

PDF
Java packages
Jeffrey Quevedo
 
PPT
PACKAGE.PPT12345678912345949745654646455
meetjaju38
 
PPTX
javapackage,try,cthrow,finallytch,-160518085421 (1).pptx
ArunPatrick2
 
PPT
Packages(9 cm604.26)
myrajendra
 
PPTX
Package in Java
lalithambiga kamaraj
 
PPTX
Packages
Monika Mishra
 
PDF
javapackage
Arjun Shanka
 
PPTX
Packages in java
SahithiReddyEtikala
 
PPTX
Packages
Nuha Noor
 
PPTX
Java packages
Shreyans Pathak
 
PPTX
Lecture 11.pptx galgotias College of engineering and technology
officialpriyanshu228
 
PPTX
THE PACKAGES CONCEPT IN JAVA PROGRAMMING.pptx
Kavitha713564
 
PPT
7.Packages and Interfaces(MB).ppt .
happycocoman
 
PPTX
Packages in java
Kavitha713564
 
PPTX
Java packages
GaneshKumarKanthiah
 
PPT
packages.ppt
radhika477746
 
PPT
packages in java programming language ppt
ssuser5d6130
 
PPT
packages.ppt
surajthakur474818
 
PPT
Unit 4 Java
arnold 7490
 
PPT
packages unit 5 .ppt
thenmozhip8
 
Java packages
Jeffrey Quevedo
 
PACKAGE.PPT12345678912345949745654646455
meetjaju38
 
javapackage,try,cthrow,finallytch,-160518085421 (1).pptx
ArunPatrick2
 
Packages(9 cm604.26)
myrajendra
 
Package in Java
lalithambiga kamaraj
 
Packages
Monika Mishra
 
javapackage
Arjun Shanka
 
Packages in java
SahithiReddyEtikala
 
Packages
Nuha Noor
 
Java packages
Shreyans Pathak
 
Lecture 11.pptx galgotias College of engineering and technology
officialpriyanshu228
 
THE PACKAGES CONCEPT IN JAVA PROGRAMMING.pptx
Kavitha713564
 
7.Packages and Interfaces(MB).ppt .
happycocoman
 
Packages in java
Kavitha713564
 
Java packages
GaneshKumarKanthiah
 
packages.ppt
radhika477746
 
packages in java programming language ppt
ssuser5d6130
 
packages.ppt
surajthakur474818
 
Unit 4 Java
arnold 7490
 
packages unit 5 .ppt
thenmozhip8
 
Ad

Recently uploaded (20)

PDF
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
PDF
Virat Kohli- the Pride of Indian cricket
kushpar147
 
PPTX
Artificial Intelligence in Gastroentrology: Advancements and Future Presprec...
AyanHossain
 
PPTX
CONCEPT OF CHILD CARE. pptx
AneetaSharma15
 
PDF
Biological Classification Class 11th NCERT CBSE NEET.pdf
NehaRohtagi1
 
PPTX
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
PPTX
How to Close Subscription in Odoo 18 - Odoo Slides
Celine George
 
PPTX
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
PPTX
Tips Management in Odoo 18 POS - Odoo Slides
Celine George
 
PPTX
Care of patients with elImination deviation.pptx
AneetaSharma15
 
PPTX
Virus sequence retrieval from NCBI database
yamunaK13
 
PPTX
BASICS IN COMPUTER APPLICATIONS - UNIT I
suganthim28
 
PPTX
20250924 Navigating the Future: How to tell the difference between an emergen...
McGuinness Institute
 
PPTX
CARE OF UNCONSCIOUS PATIENTS .pptx
AneetaSharma15
 
PPTX
Continental Accounting in Odoo 18 - Odoo Slides
Celine George
 
PPTX
Applications of matrices In Real Life_20250724_091307_0000.pptx
gehlotkrish03
 
PPTX
family health care settings home visit - unit 6 - chn 1 - gnm 1st year.pptx
Priyanshu Anand
 
PPTX
A Smarter Way to Think About Choosing a College
Cyndy McDonald
 
PDF
The-Invisible-Living-World-Beyond-Our-Naked-Eye chapter 2.pdf/8th science cur...
Sandeep Swamy
 
PPTX
How to Track Skills & Contracts Using Odoo 18 Employee
Celine George
 
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
Virat Kohli- the Pride of Indian cricket
kushpar147
 
Artificial Intelligence in Gastroentrology: Advancements and Future Presprec...
AyanHossain
 
CONCEPT OF CHILD CARE. pptx
AneetaSharma15
 
Biological Classification Class 11th NCERT CBSE NEET.pdf
NehaRohtagi1
 
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
How to Close Subscription in Odoo 18 - Odoo Slides
Celine George
 
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
Tips Management in Odoo 18 POS - Odoo Slides
Celine George
 
Care of patients with elImination deviation.pptx
AneetaSharma15
 
Virus sequence retrieval from NCBI database
yamunaK13
 
BASICS IN COMPUTER APPLICATIONS - UNIT I
suganthim28
 
20250924 Navigating the Future: How to tell the difference between an emergen...
McGuinness Institute
 
CARE OF UNCONSCIOUS PATIENTS .pptx
AneetaSharma15
 
Continental Accounting in Odoo 18 - Odoo Slides
Celine George
 
Applications of matrices In Real Life_20250724_091307_0000.pptx
gehlotkrish03
 
family health care settings home visit - unit 6 - chn 1 - gnm 1st year.pptx
Priyanshu Anand
 
A Smarter Way to Think About Choosing a College
Cyndy McDonald
 
The-Invisible-Living-World-Beyond-Our-Naked-Eye chapter 2.pdf/8th science cur...
Sandeep Swamy
 
How to Track Skills & Contracts Using Odoo 18 Employee
Celine George
 
Ad

JAVA 2-studenttrreadexeceptionpackages.pdf

  • 1. UNIT II 12 hours Defining a Package – Packages and Member Access – Importing Packages – Defining, Implementing, Applying Interfaces – Interfaces Can Be Extended – #Default Interface Methods# – Use static Methods in an Interface – Exception Handling Fundamentals – Exception Types – Using try and catch – Multiple catch Clauses – Nested try Statements – throw – throws – finally – Java’s Built- in Exceptions – Creating Own Exception Subclasses – The Java Thread Model – Creating a Thread – Creating Multiple Threads-Thread Priorities – Synchronization – Interthread Communication.
  • 2. Packages and Interfaces PACKAGES  A package can be defined as collection used for grouping a variety of classes and interfaces based on their functionality.  Classes and interfaces are grouped together in containers called packages.  A package represents a directory that contains related group of classes and interfaces. Advantages of using a package 1. Preventing naming conflicts. For example there can be two classes with name Employee in two packages, college.staff.aided.Employee and college.staff.sf.Employee. These two classes can be used in the same program and distinguished using the fully-qualified class name - package name plus class name. This mechanism is called Namespace Management. 2. Making searching/locating and usage of classes, interfaces easier 3. Providing controlled access: protected and default have package level access control. A protected member is accessible by classes in the same package and its subclasses. A default member (without any access specifier) is accessible by classes in the same package only. 4. Packages can be considered as data encapsulation (or data-hiding). 5. Reusability: A class once developed can be reused by any number of programs wishing to incorporate the class in that particular program.
  • 3. Packages are divided into two categories: 1. Built-in Packages (packages from the Java API) 2. User-defined Packages (create your own packages) - It is a collection of predefined classes and interfaces
  • 4. Java API Packages Java APl (Application Program Interface) provides a large numbers of classes grouped into different packages according to functionality. 1. java.lang – Core Classes and interfaces of Java Language(automatically imported in all programs. ) 2. java.util – Utility classes like Date, Calendar and Collections etc. 3. java.io – Classes and Interfaces for accessing Files and Streams 4. java.net – Classes and Interfaces for Network Programming 5. java.applet – Classes and Interfaces for Applet Programming 6. java.awt – Abstract Windowing Toolkit (AWT) for basic GUI 7. javax.swing – Swing Based Classes for Advanced and Platform Independent GUI 8. java.sql – Classes and Interfaces for database access (JDBC API) 9. javax.sql - the package that provides server-side database capabilities such as connection 10.java.rmi— the package that lets Java applications make remote method invocations on Java objects
  • 5. How to check Pre defined methods in pre defined class Syntax: javap <fully qualified name> Example: •If we want to see all the methods present in String class. The command javap java.lang.String Displays all the methods in the string class.
  • 6. Example: Built-in packages Example: java.util.Arrays class: This class contains various methods for manipulating arrays (such as sorting and searching). import java.util.Arrays; class JavaUtilExample { public static void main(String args []) { int[] intArray = {10,30,20,50,40}; Arrays.sort(intArray); System.out.printf("Sorted array : %s", Arrays.toString(intArray)); } } F:>java JavaUtilExample Sorted array : [10, 20, 30, 40, 50]
  • 7. User-defined packages or Defining a Package • The users of the Java language can also create their own packages. • They are called user-defined packages. • User defined packages can also be imported into other classes & used exactly in the same way as the Built in packages. Defining a Package: SYNTAX: package package name; Example : package packexample; public class ClassinPackage { // body of the class } We must first declare the name of the package using the package keyword followed by the package name. while declaring the package every character must be in lower case. The source file allow to declare only one package and it must be the first statement in a Java source file. Then define a classes as normally as define a class. If you omit the package statement, the class names are put into the default package, which has no name. More than one file can include the same package statement. The package statement simply specifies to which package the classes defined in a file belong.
  • 8. Package Hierarchy  Remember that packages are normal folders in the file system  Java also supports the concept of package hierarchy.  A set of packages shall be arranged in a hierarchal manner.  This is done by specifying multiple names in a package statement, separated by dots. The general form of a multileveled package statement is shown here: package pkg1[.pkg2[.pkg3]];  All predefined packages are arranged in this manner. java.awt.event.MouseEvent;  Here awt package contains the event package and the event package contains the MouseEvent class.  Similarly the user defined packages all so be arranged in a hierarchal manner. ex: college. compdept. mca. secondyear;  Each package should be stored in a separate sub directory. The name of the sub directory should be same as the name of the package.  The source files for the package secondyear should be placed in a directory named college compdept mca secondyear;  By convention name of each package should start with a lower case letter.
  • 9. Java Packages and CLASSPATH  Classpath is used for storing the path of the user-defined classes.  Whenever we compile/execute any class file, jdk tools(javac and java) search the package/class file in the current directory by default.  If the classes are not in the current directory, then we need to set the classpath.  CLASSPATH is an environment variable that tells the Java runtime system where the classes are present  (ie) classpath environment variable is used to specify the location of the .class file  When a packages is not created, all classes are stored in the default package  The default package is stored in the current directory.  The current directory is the default directory for CLASSPATH.
  • 10. Java Packages and CLASSPATH  w.k.t, It is not mandatory that the main program and the package(s) to be at the same location.  How does the java run-time system know where to look for packages that you create? There are three options: For example, consider the following package specification. package mypackage; 1. Placing the package in the current working directory. By default Java compiler and JVM searches the current working directory for specified package(s) like mypackage.
  • 11. Java Packages and CLASSPATH 2. Specifying the package(s) path using CLASSPATH environment variable. Let’s assume that our package mypackage is stored at following location: D:packagesmypackage Then we can set the CLASSPATH environment variable (in command prompt) to the location of the package as shown below: set CLASSPATH = .;D:packages The dot (.) before the path specifies the current working directory and multiple paths can be separated using semi-colon (;) 3. Using the -classpath or -cp options with javac and java commands. We can also use -classpath or -cp options (option 3) with javac and java commands as shown below: javac -classpath .;D:packages Driver.java Or javac -cp .;D:packages Driver.java In the above example, Driver.java is a main program which utilizes the classes in the package mypackage.
  • 12. compiling and executing packages The java source file can be saved in any directory. How to compile java package?  To compile the Java programs with package statements, you have to use -d option as shown below. Syntax: javac -d Destination_folder file_name.java Then a folder with the given package name is created in the specified destination, and the compiled class files will be placed in that folder. The -d option with javac command is used to specify the directory where the .class files needs to be stored. How to run a Java program with package? We need to use fully qualified name java packagename.classname Example: To Compile: javac -d . Simple.java To Run: java mypack.Simple The -d is a switch that tells the compiler where to put the class file i.e. it represents destination. The . represents the current folder.
  • 13. Example: package mypack; class MyPackageClass { public static void main(String[] args) { System.out.println("This is my first package!"); } } To compile and store the .class file in the working directory F:>javac -d . MyPackageClass.java To run the MyPackageClass.java file, F:>java mypack.MyPackageClass output This is my first package! If we want to store the .class file E:pack1mypack Then we have to compile like F:>javac -d e:pack1 MyPackageClass.java To run the package from the root directory, we have to set a path like this F:>set classpath= .;E:pack1 F:>java mypack.MyPackageClass This is my first package!
  • 14. Example; package empPack; class EmpClass { String empName; double salary; EmpClass(String name, double sal) { empName = name; salary = sal; } void display() { System.out.println(empName + " : $"+salary); } } class EmpSal { public static void main(String args[]) { EmpClass emp[] = new EmpClass[4]; emp[0] = new EmpClass("A.D Tedd",450.20); emp[1] = new EmpClass("D.M Scott",725.93); emp[2] = new EmpClass("B.W TayLor",630.80); emp[3] = new EmpClass("T.N Blair",545.60); for (int i=0; i<4; i++) emp[i].display(); } } F:>javac -d . EmpSal.java F:>java empPack.EmpSal A.D Tedd : $450.2 D.M Scott : $725.93 B.W TayLor : $630.8 T.N Blair : $545.6
  • 15. Packages and Member Access Packages act as containers for classes and other subordinate packages. Classes act as containers for data and code.  The class is Java’s smallest unit of abstraction. Because of the interplay between classes and packages, Java addresses four categories of visibility for class members: 1.Subclasses in the same package. 2.Non-subclasses in the same package. 3.Subclasses in different packages. 4.Classes that are neither in the same package nor subclasses.  A class has only two possible access levels: default and public.
  • 16. Packages and Member Access  Public - Anything declared public can be accessed from anywhere.  Private - Anything declared private cannot be seen outside of its class.  Package - When a member does not have an explicit access specification, it is visible to subclasses as well as to other classes in the same package. - This is the default access.  Protected - If you want to allow an element to be seen outside your current package, but only to classes that subclass your class directly
  • 17. Class Member Access type Public Private default protected Same class yes Yes yes yes Same package sub class yes no yes yes Same package non sub class yes no yes Yes Diff.package sub class yes no no yes Diff package non sub class yes no no no
  • 18. Importing or Using Packages  An import statement is used to access the classes that are stored in other packages.  An import statement must appear after the package statement but before any class declaration.  There are three ways of accessing the classes stored in a package. 1.Selected classes in packages can be imported: Syntax: import packagename.classname; Examples: 1.java.awt.Colour; 2. import mypackage1.Square; 2. All classes in packages can be imported: Syntax: import packagename.*; Examples: 1. import java.awt.*; 2. import mypackage1.*;
  • 19. Importing or Using Packages 3. using fully qualified name (Accessing package without import keyword) We can access the class of a package without importing it. In that case we will have to use the name of class with it's package name For example,consider the example, import java.util.*; class MyDate extends Date { } The same example without the import statement looks like this: class MyDate extends java.util.Date { } Here, Date is fully-qualified Example2: mypackage1.Square s = new mypackage1.Square(); Note: If you use fully qualified name then only declared class of this package will be accessible. Now there is no need to import. But you need to use fully qualified name every time when you are accessing the class or interface.  All of the standard Java classes included with Java are stored in a package called java.  The basic language functions are stored in a package inside of the java package called java.lang. Since Java is useless without much of the functionality in java.lang, it is implicitly imported by the compiler for all programs.  If a class with the same name exists in two different packages that you import using the star form, the compiler will remain silent, unless you try to use one of the classes.
  • 20. Subpackages Package inside the package is called the subpackage. Subpackage can also be designed in hierarchy, i.e. one package can be a part of another package. This can be achieved by specifying multiple names of the packages at various levels of hierarchy, separated by dots(.). For e.g. package rootPackage.subPackage; Example: 1.java.awt.event.MouseEvent; 2.college. compdept. mca. secondyear; Note When a package is imported any of its sub packages will not be imported. Example: import java.awt.*; When this statement in used in the program all the classes and interfaces that are defined in the package awt such as Graphics class will be imported but the classes and interfaces that are defined in any sub packages of the awt such as the event sub package will not be imported. Example: if you want import classes and interfaces in the event sub package we have to write the import statement as import java.awt.event.*
  • 21. Example: package pack1; // sub directory name pack1 public class add1 // source file add1.java { public int add(int m,int n) { return(m+n); } } Compile this file using F:>javac -d . add1.java package pack2; // sub directory name pack2 public class sub1// source file sub1.java { public int sub(int m,int n) { return(m-n); } } Compile this using F:>javac -d . sub1.java // in the root directory import pack1.*; import pack2.*; class math// source file name math.java { public static void main(String args[]) { int b,c; add1 a=new add1(); sub1 s=new sub1(); b=a.add(10,5); c=s.sub(10,5); System.out.println("add 10+5="+b); System.out.println("sub 10-5="+c); } } Output: ------------ F:>javac math.java F:>java math add 10+5=15 sub 10-5=5
  • 22.  It is not necessary to import a class, if it resides in the same physical directory. package p; class B //B.java { void display() { System.out.println("I am in B"); } } class C //C.java { void display() { System.out.println("I am in C"); } } class packDemo1 //packDemo1.java { public static void main(String args[]) { B b=new B(); b.display(); C c=new C(); c.display(); } F:>javac -d . packDemo1.java F:>java p.packDemo1 I am in B I am in C
  • 23. Example of package by import fully qualified name Without using import statement, you can still access classes and interfaces stored in a separate package by using their fully qualified name. But this is not considered a good practice, and you should avoid using it. //Save as Square.java package mypackage1; public class Square { public void area(int side) { System.out.println("Area of square = "+side*side); } } //Save as Test.java package mypackage2; class Test { public static void main(String args[]) { mypackage1.Square s = new mypackage1.Square(); //access classes using their fully qualified name. s.area(5); } } Output F:>javac -d . Square.java F:>javac -d . Test.java F:>java mypackage2.Test Area of square = 25
  • 24. Interfaces  The interfaces are extension of abstract classes  The abstract class contains abstract methods & normal methods  Interfaces are used to declare the functionality declarations but not definition.  Interfaces are used to achieve full abstraction.  Java Does not support Multiple Inheritance directly.  Multiple inheritance can be achieved in java by the use of interfaces. Defining an Interface  An interfaces is a collection of abstract methods and final fields.  Therefore, it is the responsibility of the class that implements an interface to supply the code for methods.  A class can implement any number of interfaces, but cannot extend more than one class at a time.  We cannot create an object for an interface but we can create references.  Once it is defined, any number of classes can implement an interface.  Also, one class can implement any number of interfaces.  The methods in interface are abstract by default.  The variables in interface are final by default.
  • 25. Reasons for using interfaces There are mainly two reasons to use interface. 1. It is used to achieve abstraction. 2. By interface, we can support the functionality of multiple inheritance.
  • 26. Defining an Interface General form of an Interface An interface is defined much like a class. interface InterfaceName { final type var_name1 = vlaue; final type var_name2 = vlaue; ............... return_type method_name1(parameter-list); return_type method_name2(parameter-list); ............... } Here Interface is the key word and InterfaceName is any valid java variable(Just like class names). Examples: 1.interface Area { final static double pi= 3.142; float compute (float x,float y); void show (); } 2.public interface IArea { double PI = 3.142; void area(); }
  • 27. CLASS INTERFACE 1. The members of a class can be constant or variables 1. The members of an interface are always declared as constant. 2. The class definition can contain the code for each of its methods 2. The methods in interface are abstract in nature i.e. there is no code associated with them. 3. It can be instantiated by declaring objects 3. It cannot be used to declare objects 4. It can use various specifiers like public, private, protected 4. It can only use the public access specifier Differences between Class and Interface Differences between an abstract class and an interface Abstract class Interface An abstract class contains some abstract methods and also some concrete methods. An interface contains only abstract methods. An abstract class contain instance variables also. An interface cannot contain instance variables. It contains only constants. All the abstract methods of the abstract class should be implemented in its sub classes. All the (abstract) methods of the interface should be implemented in its implementation classes. Abstract class is declared by using the keyword abstract. Interface is declared using the keyword interface.
  • 28. Implementing Interfaces Classes implement interfaces using the implements keyword Once an interface has been defined, one or more classes can implement that interface. To implement an interface, include the implements clause in a class definition, and then create the methods defined by the interface. The general form of a class that includes the implements clause looks like this: access class classname [extends superclass] [implements interface [,interface...]] { // class-body } Here, access is either public or not used. If a class implements more than one Interface, the interfaces are separated with a comma. The methods that implement an interface must be declared public. Also, the type signature of the implementing method must match exactly the type signature specified in the interface definition.
  • 29. Example: implementing interfaces interface Shape2D { double computeArea( ); } class Circle implements Shape2D { int radius; Circle(int radius) { this.radius = radius; } public double computeArea( ) { return 3.14 * radius * radius; } } class CircleDemo { public static void main(String[ ] args) { Circle obj = new Circle(10); System.out.println(obj. computeArea( )); } } Output 314.0
  • 30. Example2: interface Calculator { int add(int a,int b); int subtract(int a,int b); int multiply(int a,int b); int divide(int a,int b); } class Normal_Calculator implements Calculator { public int add(int a,int b){ return a+b;} public int subtract(int a,int b){ return a-b;} public int multiply(int a,int b){return a*b;} public int divide(int a,int b){return a/b;} } class intefacetest { public static void main(String args[]) { Normal_Calculator c=new Normal_Calculator(); System.out.println("Value after addition = "+c.add(5,2)); System.out.println("Value after Subtraction = "+c.subtract(5,2)); System.out.println("Value after Multiplication = "+c.multiply(5,2)); System.out.println("Value after division = "+c.divide(5,2)); } F:>javac intefacetest.java F:>java intefacetest Value after addition = 7 Value after Subtraction = 3 Value after Multiplication = 10 Value after division = 2
  • 31. Accessing Implementations Through Interface References The following example calls the callback( ) method via an interface reference variable: interface MyInterface { void callback(int param); } class Client implements MyInterface{ // Implement Callback's interface public void callback(int p) { System.out.println("callback called with " + p); } } public class Main { public static void main(String args[]) { MyInterface c = new Client(); c.callback(42); } } We can create a reference for an interface then again we can assign that reference to the implemented class object and then this reference can be used to access the method version disfigured in the implemented class.  This is one of the key features of the interface. This process is similar of using the super class references for accessing the sub class overridden methods. Output: callback called with 42
  • 32. Nested Interfaces An interface defined inside another interface or class is known as nested interface. Nested interface is also known as inner interfaces or member interfaces. Syntax: interface OuterInterfaceName { interface InnerInterfaceName { // constant declarations // Method declarations } }  A nested interface can be declared as public, private, or protected. This differs from a top-level interface, which must either be declared as public or use the default access level.  When a nested interface is used outside of its enclosing scope, it must be qualified by the name of the class or interface of which it is a member.  Thus, outside of the class or interface in which a nested interface is declared, its name must be fully qualified.
  • 33. Nested Interfaces - Example interface MyInterface { void calculateArea(); interface MyInnerInterface { int id = 20; void print(); } } class NestedInterface implements MyInterface.MyInnerInterface { public void print() { System.out.println("Print method of nested interface"); } } class nestedinterDemo { public static void main(String args []) { NestedInterface obj = new NestedInterface(); obj.print(); System.out.println(obj.id); } } F:>javac nestedinterDemo.java F:>java nestedinterDemo Print method of nested interface 20
  • 34.  Just as classes can be inherited, interfaces can also be inherited  One interface can extend one or more interfaces using the keyword extends  The syntax is the same as for inheriting classes.  When a class implements an interface that inherits another interface, it must provide implementations for all methods defined within the interface inheritance chain. Note: 1.An interface can extend only one interface.(like a class can extend only one class) 2.It cannot extend a class. 3.A class can implement more than one interface and extend only one class 4. An interface cannot implement an interface. Interfaces Can Be Extended
  • 35. // One interface can extend another. interface A { void meth1(); void meth2(); } // B now includes meth1() and meth2() -- it adds meth3(). interface B extends A { void meth3(); } // This class must implement all of A and B class MyClass implements B { public void meth1() { System.out.println("Implement meth1()."); } public void meth2() { System.out.println("Implement meth2()."); } public void meth3() { System.out.println("Implement meth3()."); } } class IFExtend { public static void main(String arg[]) { MyClass ob = new MyClass(); ob.meth1(); ob.meth2(); ob.meth3(); } } Output: Implement meth1(). Implement meth2(). Implement meth3().
  • 36. Multiple Inheritance  A class derived from more than one superclass is called multiple inheritance.  Java doesn’t support multiple inheritance directly. For instance a definition like class A extends B extends C { ………….. ………….. } is not permitted in java.  Java provide an alternate approach to implement multiple inheritance by interface. class A extends B implements C // C is an interface { ………….. ………….. } is permitted in java.  Although a java class cannot be a subclass of more than one super class ,it can be implement more than one interface  Multiple inheritance by interface occurs if a class implements multiple interfaces or also if an interface itself extends multiple interfaces.
  • 37. Example :Extending one class and implementing one interface. interface shape2 { double getArea(); } class shape { Void display() { System.out.println(“Name of the shape is circle”); } } class circle extends shape implements shape2 //multiple inheritance { int radius; circle (int radius) { this.radius=radius; } public getArea() { retrun Math.PI*radius*radius; } } class Demo { public static void main(String args[]) { circle c=new circle(10); c.display(); System.out.println(“The area of the circle” +c.getArea()); } }
  • 38. Multiple Inheritance Using Interface Example Program interface vehicleone{ int speed=90; public void distance(); } interface vehicletwo{ int distance=100; public void speed(); } class Vehicle implements vehicleone,vehicletwo{ public void distance(){ int distance=speed*100; System.out.println("distance travelled is "+distance); } public void speed(){ System.out.println("speed is "+speed); } } class MultipleInheritinterface { public static void main(String args[]) { System.out.println("Vehicle"); Vehicle obj = new Vehicle(); obj.distance(); obj.speed(); } } F:>javac MultipleInheritinterface.java F:>java MultipleInheritinterface Vehicle distance travelled is 9000 speed is 90
  • 39. Exception Handling There are basically 3 types of errors in a java program: 1.Compile-time errors 2.Run-time errors 3.Logical errors.
  • 40. 1.Compile-time errors:  All syntax errors will be detected and displayed by the Java compiler and these errors are known as compiler-time errors.  Whenever the compiler displays an error, it will not create the .class file. The most common compile time errors are:  Missing semicolons  Missing brackets in classes and methods  Misspelling of identifiers and keywords Example: class CError{ public static void main(String args[]){ System.out.println(“Compilation Error…..”) } } D:>javac Cerror.java CError.java:4: ';' expected } ^ 1 error
  • 41. 2.Run-time errors:  A program may compile successfully creating a .class file but may not run properly.  Such programs may produce wrong results due to wrong logic or may terminate such as stack overflow. Most common run time errors are:  Dividing an integer by zero.  Accessing an element that is out of bound of in an array.  Trying to store a value into an array of an incompatible class or type.  Passing a parameter that is not in a valid range or value for a method Example: class RError{ public static void main(String args[]){ int a=10,b=0; System.out.println(“a/b: ”+(a/b)); } } D:>javac RError.java D:>java RError Exception in thread "main" java.lang.ArithmeticException: / by zero at RError.main(RError.java:4)
  • 42. 3.Logical errors:  A logic error (or logical error) is a mistake in a program's source code that results in incorrect or unexpected behavior.  Logical errors means the logic of the program is wrong and these are identified after observing the output.  These errors depict flaws in the logic of the program.  The programmer might be using a wrong formula or the design of the program itself is wrong.  Logical errors are not detected either by the java compiler or JVM.  The programmer is solely responsible for them. class LError{ int sum(int a,int b){ return a-b; } public static void main(String args[]){ LError le=new LError(); System.out.println("Sum is: "+le.sum(20,10)); } } D:>javac LError.java D:>java LError Sum is: 10
  • 43. What is an Exception?  An Exception is an abnormal situation (or) unexpected situation in the normal flow of the program execution. (ie) unexpected event that disturbs normal flow of the program is called exception.  An exception is an abnormal condition that arises in a code sequence at run time. In other words, an exception is a run-time error. Because of Exceptions the flow of program execution is getting disturbed so that program execution may continue (or) may not be continued.  Examples Division by zero Attempts to use an array index out of bounds. Number input in wrong format Unable to write output to file Missing input file
  • 44. Exception Handling  Exception Handling is a mechanism to handle runtime errors Meaning of exception handling Exception handling doesn't mean repairing an exception. We have to define alternative way to continue rest of the program normally. This way of defining alternative is nothing but exception handling. Objective of Exception handling It is highly recommended to handle exceptions. The main objective of exception handling is to maintain the normal flow of the Java program. In a language without exception handling When an exception occurs, control goes to the operating system, where a message is displayed and the program is terminated. In a language with exception handling Programs are allowed to trap some exceptions, thereby providing the possibility of fixing the problem and continuing
  • 45. Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional condition that has occurred in a piece of code.  When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error.  Exceptions needs to be handled so that appropriate actions can be taken.  Programmer can also provide exception handling code. However if there is no exception handling code present during runtime and exception occurs, then java interpreter provides default exception handler.  Default Exception Handler displays the name of the exception object in string form and stops the execution of the program.  However , programmer can provide exception handling code and program’s execution can continue even after the occurrence of exception.
  • 46. Java exception handling is managed by via five keywords: try, catch, throw, throws, and finally. 1) try – Java try block is used to enclose the code that might throw an exception. 2) catch – Java catch block is used to handle the Exception. It must be used after the try block only 3) finally – Java finally block is always executed whether exception is handled or not. Java finally block follows try or catch block. 4) throw –throw keyword is used to manually create and throw an exception object. 5) throws – If a method which raises exceptions doesn’t want to handle them, they can be thrown to parent method or the Java run-time using the throws keyword. Difference between Exception and Error  An exception is an error which can be handled. It means an exception happens, the programmer can do something to avoid any harm.  But an error is an error which cannot be handled, it happens and the programmer cannot do anything.
  • 47. • General form of an exception-handling block try{ // block of code to monitor for errors } catch (ExceptionType1 exOb){ // exception handler for ExceptionType1 } catch (ExceptionType2 exOb){ // exception handler for ExceptionType2 } //… finally{ // block of code to be executed before try block ends } Note: Once an exception is thrown , program control transfers out of the try block into the catch block. Once the catch statement is executed program control continues with the next line following the entire try/catch mechanism.
  • 48. … Java Exception Class Hierarchy or Exception Types Object Error Throwable Exception VirtualMachineError Ex: Stack overflow IOException … RuntimeException … ArithmeticException NullPointerException IndexOutOfBoundsException Unchecked Checked NoSuchElementException FileNotFoundException EOFException … Exceptions are recoverable. Most of the cases exceptions are raised due to program code only. Errors are non-recoverable. Most of the cases errors are due to lack of system resources but not due to our programs.
  • 49.  All exception types are subclasses of the built-in class Throwable  Throwable class has two direct subclasses named Exception and Error 1.Exception . The Exception class has subclasses that describe problems encountered during execution. These subclasses include ClassNotFoundException, NoSuchFieldException, NoSuchMethodException, and RuntimeException. The RuntimeException class has additional subclasses like ArithmeticException, ArrayIndexOutOfBoundsException, NullPointerException, and NumberFormatException 2. Error The Error class represents problems within the virtual machine. This includes memory exhaustion error, stack overflow error, illegal access error and other serious problems. Error classes are generally not caught and result in program termination.  The Throwable class defines two useful methods like getMessage() and printStackTrace(), that can be used to handle exceptions.
  • 50. Uncaught Exceptions or Default Exception Handling class Exc0 { public static void main(String args[]) { int d = 0; int a = 42 / d; } } class Exc1 { static void subroutine() { int d = 0; int a = 10 / d; } public static void main(String args[]) { Exc1.subroutine(); } } java.lang.ArithmeticException: / by zero at Exc0.main(Exc0.java:4) java.lang.ArithmeticException: / by zero at Exc1.subroutine(Exc1.java:4) at Exc1.main(Exc1.java:7)
  • 51.  When the Java run-time system detects the attempt to divide by zero, it constructs a new exception object and then throws this exception.  This causes the execution of Exc0 to stop, because once an exception has been thrown, it must be caught by an exception handler and dealt with immediately.  In this example, we haven’t supplied any exception handlers of our own, so the exception is caught by the default handler provided by the Java run-time system.  Any exception that is not caught by your program will ultimately be processed by the default handler.  The default handler displays a string describing the exception, prints a stack trace from the point at which the exception occurred, and terminates the program. There are two drawbacks in the default exception handling Mechanism. 1) Always reports the exception in a predefined formats. 2) After reporting an exception, it immediately terminates the execution of the program.  The overcome these drawbacks programmer can provide exception handling code and program’s execution can continue even after the occurrence of exception.
  • 52. Using try and catch Handling an exception has two benefits, 1) It allows you to fix the error 2) It prevents the program from automatically terminating.  To guard against and handle a run-time error, simply enclose the code that you want to monitor inside a try block.  Immediately following the try block, include a catch clause that specifies the exception type that you wish to catch.  Once an exception is thrown, program control transfer out of the try block into the catch block  Once the catch statement has executed, program control continues with the next line in the program following the entire try/catch mechanism  To illustrate how easily this can be done, the following program includes a try block and a catch clause which processes the ArithmeticException generated by the division-by-zero error:
  • 53. Using try and catch - Example Without try catch class Testexcep { public static void main(String[] args){ System.out.println("statement1:This will be printed"); System.out.println(42/0); System.out.println("statement3:This will not be printed"); } } output F:>javac Testexcep.java F:>java Testexcep statement1:This will be printed Exception in thread "main" java.lang.ArithmeticException: / by zero at Testexcep.main(Testexcep.java:5) With try catch class Testexep1 { public static void main(String[] args){ System.out.println("statement1:This will be printed"); try{ System.out.println(42/0); } catch(ArithmeticException e){ System.out.println(42/2); } System.out.println("statement3:This will also be printed"); }} output F:>javac Testexep1.java F:>java Testexep1 statement1:This will be printed 21 statement3:This will also be printed
  • 54. Example2: class Exc2 { public static void main(String args[]) { int d, a; try { // monitor a block of code. d = 0; a = 42 / d; System.out.println("This will not be printed."); } catch (ArithmeticException e) { // catch divide-by-zero error System.out.println("Division by zero."); } System.out.println("After catch statement."); } } Output: Division by zero. After catch statement.
  • 55. Method to Print Exception Information Throwable class defines the following methods to print exception information to the console. 1.getMessage(): Returns a string that describes the exception that occurred. If we use getMessage() method then print only i)description 2.toString(): Returns a string made up of the specific exception class name and the error message. If we use toString() method then it will i) print name of exception and ii) description . 3.printStackTrace(): Displays the sequence of method calls that led to the exception to the standard error stream If we use printStackTrace() method then it will i)print name of exception, ii) description and iii)where exception occur.
  • 56. Example 2:Printing exception message – getMessage() and printStackTrace() An exception message can be printed in three ways. The first way is printing the exception object thrown by the JVM. The other two are using the methods of Throwable class – getMessage() and printStackTrace(). 1. Printing exception object. class printmessage { public static void main(String[] args) { try { System.out.println(10/0); } catch(ArithmeticException e) { System.out.println(e); } } } H:>javac printmessage.java H:>java printmessage java.lang.ArithmeticException: / by zero 2. Using getMessage() class printmessage1 { public static void main(String[] args) { try { System.out.println(10/0); } catch(ArithmeticException e) { System.out.println(e.getMess age()); } } } H:>javac printmessage1.java H:>java printmessage1 / by zero 3. Using printStackTrace() class printmessage2 { public static void main(String[] args) { try { System.out.println(10/0); } catch(ArithmeticException e) { e.printStackTrace(); } } } H:>javac printmessage2.java H:>java printmessage2 java.lang.ArithmeticExceptio n: / by zero at printmessage2.main(printme ssage2.java:3)
  • 57.  The above three screenshots can infer you the following information.  System.out.println(e) prints the exception class name (java.lang.ArithmeticException) and also the exception message ( / by zero).  System.out.println(e.getMessage()) prints exception message ( / by zero) only indicating the cause of exception.  e.printStackTrace() prints the exception class name with the message particulars and also the line number where the problem arises (traces the actual problem).
  • 58. When more than one exception can be raised by a single piece of code, several catch clauses can be used with one try block: each catch catches a different kind of exception when an exception is thrown, the first one whose type matches that of the exception is executed after one catch executes, the other are bypassed and the execution continues after the try/catch block Multiple Catch Clauses
  • 59. Example class MultiCatch { public static void main( String args[] ) { int num1, num2; try { num1 = Integer.parseInt(args[0]); num2 = Integer.parseInt(args[1]); System.out.println("The quotient is " + (num1/num2)); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Invalid Number of arguments!"); System.out.println("the error is "+ e ); } catch (NumberFormatException e) { System.out.println("Please enter integers!"); System.out.println("the error is "+ e ); } catch (ArithmeticException e) { System.out.println("Error in denominator!"); System.out.println("division by zero!"); System.out.println("the error is "+ e ); } finally { System.out.println("Thank you for using this program."); } } } output J:>javac MultiCatch.java J:>java MultiCatch 5 2 The quotient is 2 Thank you for using this program. J:>java MultiCatch 23.2 5 Please enter integers! the error is java.lang.NumberFormatException: For input string: "23.2" Thank you for using this program. J:>java MultiCatch 25 0 Error in denominator! division by zero! the error is java.lang.ArithmeticException: / by zero Thank you for using this program. J:>java MultiCatch 25 Invalid Number of arguments! the error is java.lang.ArrayIndexOutOfBoundsException: 1 Thank you for using this program.
  • 60. Single catch  Single catch can handle multiple exceptions  The catch statement in the next example catches exception objects of Exception and all its subclasses.
  • 61. Example – single catch public class CatchException2 { public static void main( String args[] ) { int num1, num2; try { num1 = Integer.parseInt(args[0]); num2 = Integer.parseInt(args[1]); System.out.println("The sum is " + (num1+num2)); } catch (Exception e) { System.out.println("The error : " + e.toString()); System.out.println( "Usage : java AddTwoIntegers <num1> <num2>"); } } } >java CatchException2 The error : java.lang.ArrayIndexOutOfBoundsException: 0 Usage : java AddTwoIntegers <num1> <num2> >java CatchException2 A B The error : java.lang.NumberFormatException: For input string: "A" Usage : java AddTwoIntegers <num1> <num2> Message stored in the Exception object e
  • 62. Nested try Statements  Some times, a part of one block may cause an exception and the entire block may cause another exception.  In such a case, exception handlers have to be nested.  That is, a try statement can be inside the block of another try.  When nested try blocks are used, inner try block is executed first.  If no matching catch block is encountered, catch blocks of outer try blocks are inspected until all nested try statements are executed.  If no catch statement matches, then the Java run-time system will handle the exception.
  • 63. Example class Nested_Try { public static void main (String args [ ] ) { try { int a = Integer.parseInt (args [0]); int b = Integer.parseInt (args [1]); int quot; try { quot = a / b; System.out.println(quot); } catch (ArithmeticException e) { System.out.println("divide by zero"); } } catch (NumberFormatException e) { System.out.println ("Incorrect argument type"); } } output F:>java Nested_Try 24 6 4 F:>java Nested_Try 24 a Incorrect argument type F:>java Nested_Try 24 0 divide by zero
  • 64. throw statement or throwing exceptions  We have seen earlier in all the programs of exception handling that Java runtime system was responsible for identifying exception class, creating its object, and throwing that object.  JVM automatically throws system generated exceptions. All those exceptions are called implicit exceptions.  If we want to throw an exception manually or explicitly, for this, Java provides a keyword throw.  (ie) The keyword “throw” is used to hand over user created exception objects to the JVM (Java Virtual Machine) manually. If “throw” is not used to throw an exception instance and the exception occurs, then the runtime system internally throws the exception instance to JVM and the program terminates abnormally.  Throw in Java is a keyword that is used to throw a built-in exception or a user defined exception explicitly or manually.  Using throw keyword, we can throw either checked or unchecked exceptions in java programming.
  • 65. throw statement or throwing exceptions  When an exception occurs in the try block, throw keyword transfers the control of execution to the caller by throwing an object of exception.  Only one object of exception type can be thrown by using throw keyword at a time.  Throw keyword can be used inside a method or static block provided that exception handling is present.  The throw keyword is mainly used to throw custom exception. We will see custom exceptions later. The general form of throw is shown here: throw ThrowableInstance;  Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable.
  • 66. Note: • The flow of execution stops immediately after the throw statement; any subsequent statements are not executed. • The nearest enclosing try block is inspected to see if it has a catch statement that matches the type of exception. If it does find a match, control is transferred to that statement. • If not, then the next enclosing try statement is inspected, and so on. If no matching catch is found, then the default exception handler halts the program and prints the stack trace.
  • 67. The result of following 2 programs are exactly same class Ex { public static void main(String[] args) { System.out.println(50/0); } } F:>javac Ex.java F:>java Ex Exception in thread "main" java.lang.ArithmeticException: / by zero at Ex.main(Ex.java:4) Note: In this case ArithmeticException object created implicitly and handover to the JVM automatically by the main method. class ExwithThrow { public static void main(String[] args) { throw new ArithmeticException("/ by zero"); } } F:>javac ExwithThrow.java F:>java ExwithThrow Exception in thread "main" java.lang.ArithmeticException: / by zero at ExwithThrow.main(ExwithThrow.java:5) Note: In this case we created exception object explicitly using throw keyword and handover that object to the JVM manually.
  • 68.  There are two ways you can obtain a Throwable object: 1. creating one with the new operator. The general form is throw new Exception( message); here the message is optional Example: if(secondNumber == 0) throw new ArithmeticException("Error in denominator"); 2. using a parameter into a catch clause The general form is throw exceptionReference; Example: catch ( ArithmeticException e) { System.out.println(“Arithmetic error has occurred”); throw e; // rethrow the exception }
  • 69. Example -throw Statement class Testthrow{ void validate(int age) { if(age<18) throw new ArithmeticException(" age not valid"); else System.out.println("welcome to vote"); } } class testexception { public static void main(String args[]){ Testthrow t = new Testthrow(); t. validate(Integer.parseInt (args[0])); System.out.println("rest of the code..."); } } F:>javac testexception.java Note: when we enter age<18 an ArithmeticException is raised and thrown to the user. Because, We are not properly handle the exception, therefore JVM handles the exception in its own way. (ie) In this case we are creating exception object explicitly and handover to the JVM manually. F:>java testexception 13 Exception in thread "main" java.lang.ArithmeticException: age not valid at Testthrow.validate(testexception.java:5) at testexception.main(testexception.java:14) when we enter age>18 an ArithmeticException is not raised, the program executed fully. F:>java testexception 34 welcome to vote rest of the code...
  • 70. Example -throw Statement with try catch class Testthrow{ void validate(int age) { if(age<18) throw new ArithmeticException(" age not valid"); else System.out.println("welcome to vote"); } } class testexception1 { public static void main(String args[]){ Testthrow t = new Testthrow(); try{ t. validate(Integer.parseInt (args[0])); } catch(ArithmeticException ae){ System.out.println(ae); //throw ae; // rethrow the exception } System.out.println("rest of the code..."); } } Note: Here we handle the exception with try catch block, Therefore the program executed completely. F:>javac testexception1.java F:>java testexception1 34 welcome to vote rest of the code... F:>java testexception1 13 java.lang.ArithmeticException: age not valid rest of the code... Note1: we can use try catch in the validate method also like void validate(int age) { if(age<18) try{throw new ArithmeticException(" age not valid");} catch(ArithmeticException ae){ System.out.println(ae); } else System.out.println("welcome to vote"); } }
  • 71. Example -throw Statements public int division(int firstNumber, int secondNumber){ if(secondNumber == 0) {ArithmeticException ae = new ArithmeticException(" Error in denominator"); throw ae; } /*The above two statements can be simplified by using a single statement throw new ArithmeticException("Error in denominator");*/ return firstNumber/secondNumber; } } class throwtest { public static void main(String args[]){ ThrowDemo d = new ThrowDemo(); try{ d.division(12,0); } catch(ArithmeticException ae){ System.out.println(ae); throw ae; // rethrow the exception } } } H:>javac throwtest.java H:>java throwtest java.lang.ArithmeticException: Error in denominator Exception in thread "main" java.lang.ArithmeticException: Error in denominator at ThrowDemo.division(throwtest.java:5) at throwtest.main(throwtest.java:19)
  • 72. Throws clause or Declaring Exceptions  A method, instead of handling an exception by itself using try .. catch, it can simply instruct the caller method to handle the exception by making use of throws keyword along with the method signature.  (ie) Throws gives an information to the programmer that there may occur an exception so it is better for the programmer to provide the exception handling code so that normal flow can be maintained.  The 'throws' keyword is used to delegate (hand over) the exception handling mechanism to the caller of the function  It requires in the case of checked exception.  In our program if there is any chance of raising checked exception then compulsory we should handle either by try catch or by throws keyword otherwise the code won't compile.  This is necessary for all exceptions, except those of type Error or RuntimeException, or any of their subclasses.  All other exceptions that a method can throw must be declared in the throws clause.
  • 73. Throws clause or Declaring Exceptions The syntax is  This tells methods to other methods "If you call me, you must handle any exceptions that I throw.”  If you don’t want the exception to be handled in the same function you can use the throws class to handle the exception in the calling function. In our program if there is any chance of raising checked exception then it is compulsory to handle the exception either by 1. By using try-catch block 2. By using throws keyword otherwise the code won't compile. Note: "throws" keyword required only to convince complier. Usage of throws keyword doesn't prevent abnormal termination of the program. type method-name(parameter-list) throws exception-list{ // body of method } Here, exception-list is a comma-separated list of the exceptions that a method can throw.
  • 74. 1. example using throws clause // here we are not catching the thrown exception, we are // declaring it in the throws clause of the calling method import java.io.*; public class input { public static void main(String args[]) throws IOException { //program code System.out.print("Please enter a string: "); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s = br.readLine(); System.out.println("You entered: " + s); } } Input operations can cause run-time exceptions. The previous program chose not to catch them but to propogate them out of main - hence the throws IOException clause. In the next example, we catch such exceptions within the program. 74
  • 75. 2.Example of catching an exception using a try/catch block import java.io.*; public class exceptionExample { public static void main(String args[]) { //program code BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s ; System.out.print("Please enter a string: "); try { s = br.readLine(); } catch (IOException e) { System.out.println( "Error when reading line from console"); } System.out.println("You entered: " + s); } } 75
  • 76.  If method1 calls method2 that has a throws clause in its method header, method1 must:  Use try-catch around the call to method2 (OR)  Have a throws clause in its own method header 76 class thro { static String read() throws IOException //method 2 { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String s=br.readLine (); return s; } } output J:>javac demo.java J:>java demo Enter a string welcome Received string is welcome import java.io.*; class demo { public static void main (String args[])//method1 { try { System.out.println ("Enter a string"); String s =thro.read(); System.out.println ("Received string is "+ s); } catch (IOException e) { System.out.println ("IO error has occurred"); } } }
  • 77. Difference between throw and throws in Java No. throw throws 1) Java throw keyword is used to explicitly throw an exception. Java throws keyword is used to declare an exception. 2) Throw is followed by an instance. Throws is followed by class. 3) Throw is used within the method. Throws is used with the method signature. 4) You cannot throw multiple exceptions. You can declare multiple exceptions e.g. public void method()throws IOException,SQLException.
  • 78. finally  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 no exception is generated, the statements in the finally clause are executed after the statements in the try block complete  if an exception is generated, the statements in the finally clause are executed after the statements in the appropriate catch clause complete  Generally, finally block is used for freeing up resources, cleaning up code, db closing connection, io stream, etc.  A finally block is optional but at least one of the catch or finally blocks must exist with a try.  Unlike catch, multiple finally blocks cannot be declared with a single try block. That is there can be only one finally block with a single try block.  Any time a method is about to return to the caller from inside a try/catch block, via an uncaught exception or an explicit return statement, the finally clause is also executed just before the method returns.
  • 79. Example public class finallyBlockExample { public static void main(String[] args) { int a = 20, b = 0; try { System.out.println("Value of a: " +a); System.out.println("Value of b: " +b); int div = a/b; System.out.println("Division: " +div); } catch(ArithmeticException ae) { System.out.println(ae); // prints corresponding exception. } finally { System.out.println("Denominator cannot be zero"); } System.out.println("Hello Java"); } } F:>javac finallyBlockExample.java F:>java finallyBlockExample Value of a: 20 Value of b: 0 java.lang.ArithmeticException: / by zero Denominator cannot be zero Hello Java
  • 80. Java's built-in Exceptions Built-in exceptions are exceptions that are already available in Java. These exceptions are thrown by the Java runtime system to explain the exception condition The default java.lang package provides several exception classes, all sub-classing the RuntimeException class. Two categories of Java's built in exception are : 1. Unchecked exception 2. Checked exception
  • 81. 1.Unchecked Exceptions (RunTimeException) : The exceptions which are not checked by the compiler whether programmer handling or not ,are called 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. All Unchecked exceptions are direct sub classes of RuntimeException class.  Unchecked Exceptions are unchecked by compiler.  If Unchecked exception is caught then exception handling code will be executed and program’s execution continues.  If Unchecked exception is not caught then java interpreter will provide the default handler. But in this case execution of the program will be stopped by displaying the name of the exceptions object.  RuntimeException, Error and their subclasses are known as unchecked exceptions.  The most Common examples are ArrayIndexOutOfBoundException, NUllPointerException ,ClassCastException
  • 83. Unchecked RuntimeExceptions defined in java.lang Exception Description ArithmeticException Arithmetic error, such as divide-by-zero. ArrayIndexOutOfBoundsExce ption Array index is out-of-bounds. ArrayStoreException Assignment to an array element of an incompatible type. IllegalArgumentException Illegal argument used to invoke a method. IllegalStateException Environment or application is in incorrect state. IndexOutOfBoundsException Some type of index is out-of-bounds. NegativeArraySizeException Array created with a negative size. NullPointerException Invalid use of a null reference. NumberFormatException Invalid conversion of a string to a numeric format. SecurityException Attempt to violate security. StringIndexOutOfBounds Attempt to index outside the bounds of a string.
  • 84. 2. Checked Exceptions (Compile Time Exception): The exceptions which are checked by the compiler for smooth execution of the program at Runtime are called checked exceptions. A checked exception is one which always deals with compile time errors. Checked exceptions are checked at compile-time. If a method is throwing a checked exception then it should handle the exception using 1. try-catch block or 2. it should declare the exception using throws keyword, otherwise compilation error will occur in the program.  Checked Exceptions are checked by the Java compiler.  If Checked exception is caught then exception handling code will be executed and program’s execution continues.  If Checked exception is not caught then java interpreter will provide the default handler. But in this case execution of the program will be stopped by displaying the name of the exceptions object.  Exceptions other than RuntimeException, Error and their subclasses are known as checked exceptions, meaning that the compiler forces the programmer to check and deal with the exceptions.  The most perfect example of Checked Exceptions is IOException which should be handled in your code Compulsorily or else your Code will throw a Compilation Error.
  • 85. Checked Exceptions Defined in java.lang. Exception Description ClassNotFoundException Class not found. IllegalAccessException Access to a class is denied. InstantiationException Attempt to create an object of an abstract class or interface. InterruptedException One thread has been interrupted by another thread. NoSuchFieldException A requested field does not exist. NoSuchMethodException A requested method does not exist.
  • 86. Creating Your Own Exception Subclasses or User Defined Exception or custom Exception  Custom exceptions in Java are those exceptions which are created by a programmer to meet their specific requirements of the application.  We can create our own exception types to handle situations specific to our applications. Examples: InvalidAgeException InvalidRollNumberexception MarksOutOfBoundsException UnauthorizedRequestException etc  We can create our own exceptions by creating a subclass of the class “Exception” which is a subclass of “Throwable”.  There is no need to implement any methods, since our class already extends “Exception”, all the methods available in it are accessible in our class also.  We can also override one or more of these methods in exception classes that you create.  An exception class is like any other class, containing useful fields and methods.  Custom exceptions are used to customize the exceptions and messages according to user needs.
  • 87. steps to create user defined or custom exception Step 1: Create a new class whose name should end with Exception like ClassNameException. This is a convention to differentiate an exception class from regular ones. Examples: AgeException, MarksOutOfBoundsException Step 2: Make the class extends one of the exceptions which are subtypes of the java.lang.Exception class. User-defined exceptions can be created simply by extending Exception class. This is done as: class MyException extends Exception{ // body of the class } Step 3: If you do not want to store any exception details, define a default constructor (without any parameter)in your exception class. MyException() { }
  • 88. steps to create user defined or custom exception Step 4: If you want to store exception details, define a parameterized constructor with string as a parameter, call super class (Exception) constructor from this, and store variable “str”. MyException(String str) { super(str); // Call super class exception constructor and store variable "str" in it. } Step 5: In the last step, we need to create an object of user-defined exception class and throw it using throw clause. MyException obj = new MyException ("Exception details"); throw obj; or, throw new MyException("Exception details");
  • 89. Note: Custom Exception and constructors:  It is necessary to initialize the base class as the first step before construction of the derived class object.  If no explicit call is made then Java will call the default no parameter constructor of the Exception class and the message/cause will be missed.  Therefore, it is good practice to use the super keyword to call the parameterized constructor of the base class and initialize it with the error message. To display the message override the toString() method or, call the superclass parameterized constructor by passing the message in String format.
  • 90. The Methods Defined by Throwable Method Description Throwable fillInStackTrace( ) Returns a Throwable object that contains a completed stack trace. This object can be rethrown. Throwable getCause( ) Returns the exception that underlies the current exception. If there is no underlying exception, null is returned. String getMessage( ) Returns a description of the exception. Throwable initCause(Throwable causeExc) Associates causeExc with the invoking exception as a cause of the invoking exception. Returns a reference to the exception. void printStackTrace( ) Displays the stack trace. String toString( ) Returns a String object containing a description of the exception. This method is called by println( ) when outputting a Throwable object. • The user-defined Exception class also inherits the methods defined in the Throwable class. • The following table lists the various methods defined by the Throwable class:
  • 91. Custom exception types 1. The custom checked exceptions are exceptions that extend java.lang.Exception. They are recoverable in nature and are handled explicitly.(can be recovered either by try- catch or by throws otherwise compilation error) (ie) Whenever a superclass is Exception then that type of User defined Exception is Checked Exception. ( (ie)need to use either try-catch or throws) E.g., class XYZException extends Exception{ // body of the class } 2. The custom unchecked exceptions extend java.lang.RuntimeException. They are unrecoverable in nature.(can not be recovered either by try- catch or by throws otherwise Runtime error)  (ie) If the superclass is RuntimeException then that user defined Exception is unchecked Exception.( ie no need to use try- catch or throws clause) E.g., class XYZException extends RunTimeException{ //body of the class }  If user can take some action to recover from the expected error then make the custom exception a checked exception (i.e. inheriting from Exception class). On the other hand if user cannot do anything useful in case of error then make the custom
  • 92. User Defined unchecked Exception – Example If the superclass is RuntimeException then that user defined Exception is unchecked Exception.( ie no need to use try- catch or throws clause) Example: import java.util.*; class InvalidAgeException extends RuntimeException { // Declare parameterized constructor with String as a parameter. InvalidAgeException(String s){ super(s); // Call super exception class constructor. } } class Demo{ static void validate(int age) throws InvalidAgeException{ if(age<18){ // Create an object of user defined exception and throw it using throw clause. throw new InvalidAgeException(" your age is " + age +" Not eligible to vote"); } else{ System.out.println(" your age is " + age +" Welcome to Vote"); } } } class throwtest { public static void main(String args[]) { Demo t1 = new Demo(); Scanner sc = new Scanner(System.in); System.out.println("Enter the age "); int n =sc.nextInt(); t1.validate(n); System.out.println("rest of the code..."); } } Output F:>javac throwtest.java F:>java throwtest Enter the age 12 Exception in thread "main" InvalidAgeException: your age is 12 Not eligible to Vote at Demo. Validate(throwtest.java:10) at throwtest.main(throwtest.java:26) F:>java throwtest Enter the age 20 your age is 20 Welcome to Vote rest of the code...
  • 93. User Defined checked Exception – Example Whenever a superclass is Exception then that type of User defined Exception is Checked Exception. ( (ie)need to use either try-catch or throws) Example: import java.util.*; class InvalidAgeException extends Exception { // Declare parameterized constructor with String as a parameter. InvalidAgeException(String s){ super(s); // Call super exception class constructor. } } class Demo{ static void validate(int age) throws InvalidAgeException{ if(age<18){ // Create an object of user defined exception and throw it using throw clause. throw new InvalidAgeException(" your age is " + age +" Not eligible to vote"); } else{ System.out.println(" your age is " + age +" Welcome to Vote"); } } } class throwtest2 { public static void main(String args[]) throws InvalidAgeException { Demo t1 = new Demo(); Scanner sc = new Scanner(System.in); System.out.println("Enter the age "); int n =sc.nextInt(); t1.validate(n); // if throws clause not used in the //main(), we have to use try catch or //t.validate(n) System.out.println("rest of the code..."); } } Output F:>javac throwtest.java F:>java throwtest Enter the age 12 Exception in thread "main" InvalidAgeException: your age is 12 Not eligible to Vote at Demo. Validate(throwtest.java:10) at throwtest.main(throwtest.java:26) F:>java throwtest Enter the age 20 your age is 20 Welcome to Vote
  • 94. Multithreaded Programming  A task or Process is a program in execution  Multitasking :running more than one program (process) concurrently  A thread is a single sequential flow of control within a program. (A segment of code in a program).  Threads are parts of a program that run on their own while the rest of the program does something else  Single-threaded program can handle one task at any time.  Multithreading – a special type of multi tasking in which single program is divided into several pieces called thread and each thread is permitted to proceed simultaneously
  • 95. Multithreading  The process of executing multiple threads simultaneously (concurrently) is called multithreading in Java.  A program that contains multiple flow of control is known as multithreaded program.  Multithreading allows single processor to run several concurrent threads.  A single program can perform two tasks using two threads  multithreading is a specialized form of multitasking  Most modern operating systems support multithreading Ex: in a Web browser we may do the following tasks at the same time:  1. scroll a page,  2. download an applet or image,  3. play sound,  4 print a page.
  • 96.  An application or applet can have many threads doing different things independently.  In single processor systems, the multiple threads share CPU time and the operating system is responsible for scheduling and allocating resources to them.  This is possible because most of the time the CPU is idle  Example: Receiving the input data from the user downloading images etc.  We can walk, talk, breath, ear, smell all the same time.  Computer can download a file, print a file, receive e-mail, run the clock all at the same time. Advantages of Multithreading 1. Multithreading allows making maximum use of the CPU because idle time can be reduced. 2. It lets you tackle different tasks independently, leaving the problems of time sharing among the tasks to the OS or virtual machine. 3. Inter-thread communication is inexpensive and content switching from one thread to the next is low cost. The main application areas of multithreading are:  To implement Multimedia graphics  To develop animations  To develop video games  To develop web and application etc
  • 97. Multi Tasking  The ability to perform more than one task (program)at the same time is called multitasking. Multitasking is divided into two types 1. Process based multitasking: (Multiprocessing)  A process is a program that is executing.  Process-based multitasking is the feature that allows your computer to run two or more programs concurrently.  In process-based multitasking, a program is the smallest unit of code that can be dispatched by the scheduler.  For example, process-based multitasking enables you to run the Java compiler at the same time that you are using a text editor or browsing the internet. 2.Thread based Multitasking : (Multithreading ) A thread is a single sequential flow of control within a program. (A segment of code in a program).  In a thread-based multitasking environment, the thread is the smallest unit of dispatchable code.  In a thread-based multitasking a single program can perform two or more tasks simultaneously.  For Example, a text editor can format text at the same time that it is printing, as long as these two actions are being performed by two separate threads.  Whenever thread is created it will not occupy any separate memory. But it will share the memory which is already allocated to a program.
  • 98. The differences between process-based and thread- based multitasking: Process-based multitasking handles the concurrent execution of programs. Thread-based multitasking deals with the concurrent execution of pieces of the same program. Note: In a single processor system the processor is doing only one job at a time. However the processor switches between the processes is so fast that it appears to human being that all are being done simultaneously.
  • 99. Difference between Multithreading and Multitasking Differences between a process and a Thread Multithreading Multitasking Multithreading refers to multiple threads of control within a single program each program can run multiple threads of control within it, e.g., Web Browser Multitasking refers to a computer's ability to perform multiple jobs concurrently more than one program are running concurrently, e.g., UNIX Process Thread 1) A process is a program that is currently in execution. 1) A thread is a single sequential flow of control within a program 2) Processes are heavy weight tasks that require their own separate address space 2) A thread is a light weight and shares the same address space. 3) Inter process communication is expensive and limited. 3) The inter thread communication is inexpensive and context switching from thread to another is low cost.
  • 100. The Java Thread Model Single-Threaded Systems  Single-threaded systems use an approach called an event loop with polling.  In this model: A single thread of control runs in an infinite loop Polling a single event queue to decide which instruction to execute next Until this instruction returns, nothing else can happen in the system This results in wastage of precious CPU cycles Java’s Multithreading Model  The benefit of Java’s multithreading is that the event loop/polling mechanism is eliminated. One thread can pause without stopping other parts of your program.  When a thread blocks in a Java program, only the single thread that is blocked pauses; All other threads continue to run. All the libraries and classes are designed with multithreading in mind
  • 101. The Java Thread Model Java thread model is designed based on the following concepts: Thread states:  Threads can be in several states like running, ready, suspended, blocked, resumed. Thread Priorities:  Each thread has its own priority in Java. Thread priority is an absolute integer value.  Thread priority decides only when a thread switches from one running thread to next, called context switching.  Priority does increase the running time of the thread or gives faster execution. Synchronization:  When two or more threads need access to a shared resource it is called as race condition  To avoid this race condition we need to use a mechanism called as synchronization.  synchronization is the act of allowing only one thread at a time to execute code within a method or a block.  Java provides a simple methodology to implement synchronization. Messaging:  A program is a collection of more than one thread. Threads can communicate with each other  Java threads communicate with each other through notify() notifyall() and wait() methods. Creating a Thread: Java defines two ways by which a thread can be created. 1. By implementing the Runnable interface. 2. By extending the Thread class.
  • 102. Single Thread System Vs. Multi Thread System  Single-thread System use an approach called an event loop with pooling.  A Single thread of control runs in an infinite loop, pooling a single event queue to decide what to do next.  In a single-threaded environment, when a thread blocks because it is waiting for some resources the entire program stops running.  The advantage of multi threading is that the main loop, pooling mechanism is eliminated.  Multithreading enables us to write very efficient programs that make maximum use of CPU. Because ideal time can be kept to a minimum.  One thread can pause with out stopping other parts of the program. Java supports multi threading.
  • 103. Life Cycle of a Thread or Thread State A thread can be in one of the five states. 1.New State: MyThread t=new MyThread();.  The thread is in new state if you create an instance of Thread class but before the invocation of start() method. At this point, the thread is considered not alive. 2. Runnable (Ready) State: t.start()  A thread start its life from Runnable state.  When the start() method is called on a new thread, thread enters into a runnable state.  In runnable state, thread is ready for execution and is waiting for availability of the processor (CPU time).  A thread can come into runnable state from running, waiting, or new states. 3.Running State:  Running means Processor (CPU) has allocated time slot to thread for its execution. When thread scheduler selects a thread from the runnable state for execution, it goes into running state.  In running state, processor gives its time to the thread for execution and executes its run method. This is the state where thread performs its actual functions. A thread can come into running state only from runnable state. 4.Blocked (Non-Runnable) State:  A thread is considered to be in the blocked state when it is suspended, sleeping, or waiting for some time in order to satisfy some condition. 5.Dead (Terminated) State:  A thread can be considered dead when its run() method completes.  If any thread comes on this state that means it cannot ever run again.
  • 105. Life Cycle of a Thread(Contd..)  Starting from the birth of a thread, till its death, a thread exists in different states which are collectively called “Thread Life Cycle”.  A thread will be born when it is created using Thread class as: Thread obj=new Thread();  A thread goes into runnable state when start() method is applied on it.  That is void start() method is used to call the public void run() method.  From runnable state, a thread may get into not-runnable state, when sleep() or wait() or suspend() methods act on it.  notify() and resume() methods are used to restart waiting and suspended threads respectively.  yield() method causes the currently executing thread object to temporarily pause and allow other threads to execute.  ThreadDeath class will be invoked whenever the stop() method is called.
  • 106. Life Cycle of a Thread(Contd..)  Starting from the birth of a thread, till its death, a thread exists in different states which are collectively called “Thread Life Cycle”.  A thread will be born when it is created using Thread class as: Thread obj=new Thread();  A thread goes into runnable state when start() method is applied on it.  That is void start() method is used to call the public void run() method.  From runnable state, a thread may get into not-runnable state, when sleep() or wait() or suspend() methods act on it.  notify() and resume() methods are used to restart waiting and suspended threads respectively.  yield() method causes the currently executing thread object to temporarily pause and allow other threads to execute.  ThreadDeath class will be invoked whenever the stop() method is called.
  • 107. Syntax of the method purpose void start( ) used to start a new thread. void stop() to stop the running thread even before the completion of the task. void run( ) This method encapsulates the functionality of a thread. This method is always overridden Boolean isAlive( ) returns true if the thread is alive void setName(Strings) To set the name of the specified thread String getName( ) To return the name of the specified thread. void setPriority(int p) To set the priority of the specified thread to p int getPriority(int p) To return the priority of the specified thread. Join() wait for a thread to terminate Void resume( ) resumes execution of a suspended thread suspend( ) suspends a thread static Thread currentThread() return the reference to the currently working thread static void sleep(long m) To cause the current thread to wait for m milliseconds void yield() to bring the blocked thread to ready to run mode Methods in the Thread class:
  • 108. The Main Thread  In every java program, there is always a thread running internally. This thread is used by JVM to execute the program statements.  When a Java program starts up, one thread begins running immediately.  This is usually called the main thread of your program, because it is the one that is executed when your program begins. The main thread is important for three reasons:  It is the parent thread from which other child threads will be spawned or created.  The main thread must be the last thread to finish execution, because it performs various shutdown actions.  When the main thread stops, the program terminates.
  • 109. Example: class CurrentThreadDemo{ public static void main(String st[]){ System.out.println(“Let us find the current thread…..”); Thread t = Thread.currentThread(); System.out.println(“Current Thread= ”+t); System.out.println(“It’s name= ”+t.getName()); } } Let us find the current thread….. Current Thread= Thread[main,5,main] It’s name= main Note: In Thread[main,5,main]” , the square bracket, the first value, main represents the name of thread; second value 5 represents the priority (normal priority)of main thread.
  • 110. Creating a Thread A new thread can be created in two ways: 1. By extending Thread class (java.lang.Thread) 2. By implementing Runnable interface (java.lang.Runnable) Both of them have a method named run(). The JVM will call this method when a thread starts executing. You can think of the run() method as a starting point for the execution of a thread, just like the main() method, which is the starting point for the execution of a program. By extending the Thread class You need to override the run() method when you want to extend the Thread class. If you don’t override the run() method, the default run() method from the Thread class will be called, which does nothing. Note: the default implementation run() method in the Thread class does nothing, if you want your thread to do some meaningful work, you need to still define it. By implementing the Runnable interface The Runnable interface declares the run() method, so you must define the run() method in your class if you implement the Runnable interface. Note: Inside run( ), you will define the code that constitutes the new thread. run() method should be declared as public void run().
  • 111. 1.Creating threads by Extending the Thread Class 1. Declare the class as extending the Thread class. Ex: class Myclass extends Thread{ ….. } 2. Implement the run( ) method that is responsible for executing the sequence of code that the thread will execute. Public void run() { …. } 3. Create an object to the class. Myclass obj=new Myclass(); 4. Run the thread using obj.start() method. //invokes run() method
  • 112. class One extends Thread{ //Single thread example using public void run(){ // “extends Thread” for(int i=0;i<5;i++){ System.out.println("i value: "+i); } } } class ThreadDemo{ public static void main(String sree[]){ One o=new One(); o.start(); } } i value: 0 i value: 1 i value: 2 i value: 3 i value: 4
  • 113. 2. Creating threads by Implementing the ‘Runnable’ Interface 1.Declare the class as implementing the Runnable interface. Ex: class Myclass implements Runnable{ ….. } 2.Implement the run( ) method. Public void run() { …. } 3. Create an object to the class. Myclass obj=new Myclass(); 4. Create a thread and attach the thread to the object obj. Thread t = new Thread(obj); 5. Run the thread using t.start() method.
  • 114. //Example : single thread using runnable class Thread3 implements Runnable //step1 { public void run ( ) //step 2 { for (int i = 1; i<= 10; i++) { Thread.sleep (1000); System.out.println ("welcome to java"); } } } class ThreadDemo3 { public static void main (String[] args) { Thread3 rx = new Thread3(); Thread t3 = new Thread (rx);// step 3 t3.start(); // step 4 } } J:>javac ThreadDemo3.java J:>java ThreadDemo3 welcome to java welcome to java welcome to java welcome to java welcome to java welcome to java welcome to java welcome to java welcome to java welcome to java
  • 115. Difference between “extends Thread” and “implements Runnable” :  Both are functionally same.  But when we write extends Thread, there is no scope to extend another class, as multiple inheritance is not supported in java.  class MyClass extends Thread, AnotherClass //invalid  If we write implements Runnable, then still there is scope to extend another class. class MyClass extends AnotherClass implements Runnable //valid  This is definitely advantageous when the programmer wants to use threads and also wants to access the features of another class.
  • 116. Creating Multiple Threads  So far, we have been using only two threads: the main thread and one child thread  However, our program can spawn as many threads as it needs  In multithreading, Threads do not run sequentially (like function calls), so the order of execution of threads is not predictable.(ie) In other words, threads run asynchronously  The threads are running concurrently on their own.  Note that the output from the threads are not specially sequential.  They do not follow any specific order.  They are running independently of one another and each executes whenever it has a chance.  Remember that once the threads are started, we cannot decide with certainty the order in which they may execute statements. The following example is a program spawning multiple threads:
  • 117. Example://Multi thread example using //“extends Thread” class Fivetable extends Thread { public void run ( ) { for (int i= 1;i<=10;i++ ) System.out.println(i+"x 5 = "+(i*5)); System.out.println(“Exit from Fivetable "); } } class Seventable extends Thread { public void run ( ) { for(int i=1;i<=10;i++) System.out.println(i+"x 7 = "+(i*7)); System.out.println(“Exit from Seventable"); } } class Ninetable extends Thread { public void run ( ) { for(int i=1;i<=10;i++) System.out.println(i+“x 9="+(i*9)); System.out.println(“Exit from Ninetable "); } } class Table { public static void main(String[] args) { Fivetable f = new Fivetable( ); Seventable s = new Seventable ( ); Ninetable n = new Ninetable ( ) f.start ( ); s.start ( ); n.start ( ); } } 1x 5 = 5 2x 5 = 10 3x 5 = 15 4x 5 = 20 5x 5 = 25 6x 5 = 30 1x 7 = 7 2x 7 = 14 3x 7 = 21 4x 7 = 28 5x 7 = 35 6x 7 = 42 7x 7 = 49 8x 7 = 56 9x 7 = 63 10x 7 = 70 Exit from Seventable 1x 9 = 9 2x 9 = 18 3x 9 = 27 4x 9 = 36 5x 9 = 45 6x 9 = 54 7x 9 = 63 8x 9 = 72 9x 9 = 81 10x 9 = 90 Exit from Ninetable 7x 5 = 35 8x 5 = 40 9x 5 = 45 10x 5 = 50 Exit from Fivetable
  • 118. class One implements Runnable{ public void run(){ for(int i=0;i<5;i++){ System.out.println("i value: "+i); } } } class Two implements Runnable{ public void run(){ for(int j=10;j>4;j--){ System.out.println(“j value: "+j); } } } class RunnableDemo{ public static void main(String sree[]){ One o=new One(); Thread t1=new Thread(o); t1.start(); Two t=new Two(); Thread t2=new Thread(t); t2.start(); } } H:>javac RunnableDemo.java H:>java RunnableDemo i value: 0 i value: 1 j value:10 i value: 2 j value:9 i value: 3 j value:8 i value: 4 j value:7 j value:6 j value:5 //Multi thread example using “implements Runnable”
  • 119. Thread Priorities  The thread of the same priority are given equal treatment by the Java scheduler and, therefore, they share the processor on a first-come, first-serve basis.  But, Priorities can be assigned to threads  scheduler uses them to decide which thread gets to run  Each thread is assigned a default priority of Thread.NORM_PRIORITY (constant of 5).  Java permits us to set the priority of a thread using the setPriority( ) method as follows ThreadName.setPriority(int Number);  The intNumber is an integer value to which the thread’s priority is set. The Thread class defines several priority constants: MIN_PRIORITY = 1 NORM_PRIORITY = 5 MAX_PRIORITY = 10  Higher priorities threads gets more CPU time than the lower one •To obtain the current priority setting of a thread: final int getPriority( )
  • 120. class Even extends Thread { public void run ( ) { for (int i= 1;i<=200;i++ ) if(i%2==0) System.out.print(" "+i); System.out.println (" Exit from Even"); } } class Odd extends Thread { public void run ( ) { for (int i= 1;i<=200;i++ ) if(i%2!=0) System.out.print(" " + i); System.out.println (" Exit from Odd"); } } class threadpri { public static void main(String[] args) { Even e = new Even(); Odd o= new Odd(); e.setPriority(Thread.MAX_PRIORITY ); o.setPriority(Thread.MIN_PRIORITY ); System.out.println("Thread 1 has priority " + e.getPriority()); System.out.println("Thread 2 has priority " + o.getPriority()); e.start(); o.start(); } } H:>java threadpri Thread 1 has priority 10 Thread 2 has priority 1 2 4 6 1 8 3 10 12 5 14 7 16 9 18 11 20 13 22 15 24 17 26 19 28 21 30 23 32 25 34 36 27 38 29 40 31 42 33 44 35 46 37 48 39 50 41 52 43 54 45 56 47 58 49 60 51 62 53 64 55 66 57 68 59 70 61 72 63 74 76 65 78 67 80 69 82 71 84 86 73 88 75 90 77 92 79 94 96 81 98 83 100 85 102 87 104 89 106 91 108 93 110 95 112 114 116 118 120 97 122 99 124 101 126 103 128 105 130 107 132 109 134 111 136 113 138 115 140 117 142 119 144 121 146 123 148 125 150 127 152 129 154 131 156 133 158 135 160 137 16 2 139 164 141 166 143 168 145 170 147 172 149 174 151 176 178 153 180 1 55 182 157 184 159 186 161 188 163 190 192 194 196 165 198 167 200 169 Exit from Even 171 173 175 177 179 181 183 185 187 189 191 193 195 197 199 Exit from Odd
  • 121. Synchronization  When two or more threads need access to a shared resource it is called as race condition  To avoid this race condition we need to use a mechanism called as synchronization.  synchronization is the act of allowing only one thread at a time to execute code within a method or a block.  For example, two unsynchronized threads accessing the same bank account may cause conflict.  A shared resource may be corrupted if it is accessed simultaneously by multiple threads  To avoid this java uses the concept of monitor(also called a semaphore). A monitor is an object used as a mutually exclusive lock.  At a time only one thread can access the Monitor. A second thread cannot enter the monitor until the first comes out. Till such time the other thread is said to be waiting.  Only methods (or blocks) can be synchronized, Classes and variable cannot be synchronized.  Constructors cannot be synchronized. Code inside the constructors can be synchronized.
  • 122.  Synchronization can be achieved in two ways: 1) Method level synchronization 2) Block level synchronization  synchronization can not applied for classes and variables  In method level synchronization the total data of method is sensitive. Where as in block level synchronization part of the method is sensitive. Synchronized Methods  When a method created using a synchronized keyword, it allows only one object to access it at a time.  When an object calls a synchronized method, it put a lock on that method so that other objects or thread that are trying to call the same method must wait, until the lock is released.  Once the lock is released on the shared resource, one of the threads among the waiting threads will be allocated to the shared resource. The general form of synchronized method is: synchronized type methodName(arg-list) { // synchronized methodbody }
  • 123. class Table{ synchronized void printTable(int n) { for(int i = 1; i <= 15; i++) System.out.println(i + " * " + n + " = " + i*n); } } class MyThread_1 extends Thread{ // To call printTable() method Table object and n must required Table table; // Declaration of variable table of class type Table. int number; // declaration of number- n MyThread_1(Table table, int number){ // Declare one parameterized constructor and pass variable table as a parameter. this.table = table; this.number = number; } public void run() { // for ewvery thtread class,we should overide the run method table.printTable(number); } }
  • 124. class MyThread_2 extends Thread{ // To call printTable() method Table object and n must required Table table; // Declaration of variable table of class type Table. int number; // declaration of number- n MyThread_2(Table table, int number){ // Declare one parameterized constructor and pass variable table as a parameter. this.table = table; this.number = number; } public void run() { table.printTable(number); } } public class ThreadSynchronizationExample { public static void main(String[] args) { Table table = new Table(); MyThread_1 thread_1 = new MyThread_1(table, 2); MyThread_2 thread_2 = new MyThread_2(table, 5); thread_1.start(); thread_2.start(); } }
  • 125. Output without using Synchronized keyword F:>javac ThreadSynchronizationExample.java F:>java ThreadSynchronizationExample 1 * 2 = 2 2 * 2 = 4 1 * 5 = 5 3 * 2 = 6 2 * 5 = 10 4 * 2 = 8 3 * 5 = 15 5 * 2 = 10 Irregular output 4 * 5 = 20 6 * 2 = 12 5 * 5 = 25 7 * 2 = 14 6 * 5 = 30 8 * 2 = 16 7 * 5 = 35 9 * 2 = 18 8 * 5 = 40 10 * 2 = 20 9 * 5 = 45 10 * 5 = 50 Output with Synchronized keyword F:>javac ThreadSynchronizationExample.java F:>java ThreadSynchronizationExample 1 * 2 = 2 2 * 2 = 4 3 * 2 = 6 4 * 2 = 8 5 * 2 = 10 6 * 2 = 12 7 * 2 = 14 8 * 2 = 16 9 * 2 = 18 Regular output 10 * 2 = 20 1 * 5 = 5 2 * 5 = 10 3 * 5 = 15 4 * 5 = 20 5 * 5 = 25 6 * 5 = 30 7 * 5 = 35 8 * 5 = 40 9 * 5 = 45 10 * 5 = 50
  • 126. import java.io.*; class SavingAccounts { int account,balance; SavingAccounts(int acc_num,int initial) { account = acc_num; balance = initial; } Public synchronized boolean withdrawal(int amount) { boolean result = false; System.out.println("withdrawal from account"+account); System.out.println(" amount="+amount); if (amount<= balance) { balance = balance-amount; System.out.println("New balance="+ balance); result = true; } else System.out.println("Insufficient amount"); System.out.println(); return result; } } class ATM extends Thread {SavingAccounts account; ATM (SavingAccounts savings) { account =savings; } public void run() {account.withdrawal(300); } } public class ATM_Account { public static void main ( String args[]) { SavingAccounts savings = new SavingAccounts(4321,531); ATM west = new ATM(savings); ATM east = new ATM(savings); west.start(); east.start(); } } output ---- withdrawal from account4321 amount=300 New balance=231 withdrawal from account4321 amount=300 Insufficient amount After removing the word synchronized The output will be withdrawal from account4321 withdrawal from account4321 amount=300 amount=300 New balance=231 Insufficient amount
  • 127. Synchronized Blocks  If very few lines of the code required synchronization then it's never recommended to declare entire method as synchronized we have to enclose those few lines of the code with in synchronized block.  The main advantage of synchronized block over synchronized method is it reduces waiting time of Thread and improves performance of the system.  In synchronized blocks, you use the synchronized keyword for a reference variable and follow it by a block of code.  A thread has to acquire a lock on the synchronized variable to enter the block; when the execution of the block completes, the thread releases the lock. The general form of synchronized Block is: synchronized(this) { // code segment guarded by the mutex lock }
  • 128. class Counter { public static long count = 0; } class UseCounter implements Runnable { public void increment() { synchronized(this) { Counter.count++; System.out.print(Counter.count + " "); } } public void run() { increment(); increment(); increment(); } } // This class creates three threads public class DataRaceblock { public static void main(String args[]) { UseCounter c = new UseCounter(); Thread t1 = new Thread(c); Thread t2 = new Thread(c); Thread t3 = new Thread(c); t1.start(); t2.start(); t3.start(); } } F:>javac DataRaceblock.java F:>java DataRaceblock 1 2 3 4 5 6 7 8 9
  • 129. Inter Thread Communication  When multiple threads are running inside an application, most of them will need to communicate with each other in some form.  (ie)There may be cases where one of the created threads require data from another thread.  Inter-thread communication can be defined as the exchange of messages between two or more threads.  Java achieves this through the usage of wait(), notify(), notifyAll() methods of the object class.  These methods can be called only from within a synchronized method or synchronized block of code otherwise, an exception named IllegalMonitorStateException is thrown.  wait(), notify() and notifyAll() method present in Object class. Hence, these methods are available to all classes
  • 130. wait(), notify() and notifyAll() methods Wait() method: The wait() method causes the current thread to wait until another thread invokes the notify() or notifyAll() methods for that object. This method throws InterruptedException. Syntax: 1.public final void wait() throws InterruptedException 2. public final void wait(long millisecond) throws InterruptedException notify() Method: The notify() method wakes up a single thread that called wait() method on the same object. Syntax: public final void notify() notifyAll() Method: The notifyAll() method is used to wake up all threads that called wait() method on the same object Syntax: public final void notifyAll()
  • 131. class Customer { int amount = 10000; synchronized void withdraw(int amount) { System.out.println("Available Balance " + this.amount); System.out.println("Going to withdraw." + amount); if (this.amount < amount) { System.out.println("Insufficient Balance waiting for deposit."); try { wait(); } catch (Exception e) { System.out.println("Interruption Occurred"); } } this.amount -= amount; System.out.println("Detected amount: " + amount); System.out.println("Balance amount : " + this.amount); System.out.println("withdraw completed"); } synchronized void deposit(int amount) { System.out.println("Going to deposit " + amount); this.amount += amount; System.out.println("Available Balance " + this.amount); System.out.println("deposit completedn"); notify(); } } class InterThreadDemo { public static void main(String arg[]) { Customer c = new Customer(); Thread t1= new Thread() { public void run() { c.withdraw(15000); } }; t1.start(); Thread t2= new Thread() { public void run() { c.deposit(10000); } }; t2.start(); } } output F:>javac InterThreadDemo.java F:>java InterThreadDemo Available Balance 10000 Going to withdraw.15000 Insufficient Balance waiting for deposit. Going to deposit 10000 Available Balance 20000 deposit completed Detected amount: 15000 Balance amount : 5000 withdraw completed