0% found this document useful (0 votes)
3 views100 pages

Javanotes Unit-3

The document provides an overview of inheritance in Java, detailing its definition, types, and how to define subclasses. It explains concepts such as method overriding, final variables, methods, and classes, as well as abstract methods and classes. Additionally, it covers the creation and usage of packages in Java, including access protection and examples of different access specifiers.

Uploaded by

classicsiddu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views100 pages

Javanotes Unit-3

The document provides an overview of inheritance in Java, detailing its definition, types, and how to define subclasses. It explains concepts such as method overriding, final variables, methods, and classes, as well as abstract methods and classes. Additionally, it covers the creation and usage of packages in Java, including access protection and examples of different access specifiers.

Uploaded by

classicsiddu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 100

II SEM JAVA PROGRAMMING 2022

Inheritance
Definition:
 The mechanism of deriving a new class from an old one is called inheritance
 The old class is known as the base class or super class or parent class
 The new class is known as the sub class or derived class or child class

Types of Inheritance
 Single inheritance ( only one super class)
 Multiple inheritance ( several super classes)
 Hierarchical inheritance ( one super class, many subclasses)
 Multilevel inheritance ( derived from a derived class)
Java does not directly implement multiple inheritance
This concept is implemented using a secondary inheritance path in the form of interfaces

Defining a subclass
 A subclass is defined as follows:
class subclassname extends superclassname
{
variable declarations;
methods declarations;
}
 The keyword extends specifies that the properties of the superclassname are extended to the subclassname
 The subclass will now contains its own variables and methods as well those of the superclass
Ex:
class Room
{
int length, breadth;
Room(int x, int y)
{
length=x;
breadth=y;
}
int area()
{
return(length*breadth);
}
}

class BedRoom extends Room


1
II SEM JAVA PROGRAMMING 2022

{
int height;

BedRoom(int x, int y, int z)


{
super(x, y);
height=z;
}
int volume()
{
return(length*breadth*height);
}
}

class InherTest
{

public static void main(String args[])


{
BedRoom room1 = new BedRoom(14, 12, 10);
int area1 = room1.area();
int volume1 = room1.volume();
System.out.println(“Area1 = “ + area1);
System.out.println(“Volume = “ + volume);
}
}

Subclass constructor
 A subclass constructor is used to construct the instance variables of both the subclass and superclass
 The subclass constructor uses the keyword super to invoke the constructor method of the superclass
 The keyword super is used under the following conditions
 Super may only be used within a subclass constructor method
 The call to superclass constructor must appear as the first statement within the subclass
constructor
 The parameters in the super call must match the order and type of the instance variable declared
in the superclass

Multilevel inheritance
 class A serves as a base class for the derived class B which in turn serves as a base class for the derived class C
 the chain ABC is known as inheritance path

2
II SEM JAVA PROGRAMMING 2022

 A derived class with multilevel base classes is declared as follows:


class A
{
--- `
}
class B extends A // First level
{
---
}
class C extends B // Second level
{
--
}
 This process may be extended to any number of levels
 The class C inherit the members of both A and B

Hierarchical Inheritance
 Many programming problems can be cast into a hierarchy where certain features of one level are shared by many
others below the level
 Following diagram shows a hierarchical classification of accounts in a commercial bank

Method Overriding
 Defining a method in the subclass that has the same name, same arguments and same return type as a method in
the superclass.
 When that method is called, the method defined in the subclass is invoked and executed instead of the one in the
superclass .This process is known as method overriding
Ex
class Super
{
int x;
Super(int x)
{
this.x = x;
}
void display() // Method Defined
{
System.out.println(“Super x = “ + x);
}
}
class Sub extends Super
3
II SEM JAVA PROGRAMMING 2022

{
int y;
Sub(int x, int y)
{
super(x);
this.y=y;
}
void display() //Method defined again
{
System.out.println(“Super x = “ + x);
System.out.println(“Sub y = “ + y);
}
}
class OverrideTest
{
public static void main(String args[])
{
Sub s1 = new Sub(100, 200);
s1.display();
}
}

Final Variables and Methods


 If we wish to prevent the subclasses from overriding the members of the superclass, we can declare them as final
using the keyword final as a modifier
Ex:
final int s = 10;
final void display() { …………. }
 Making a method final ensures that the functionality defined in this method will never be altered in any way
 Final variables can never be changed
Example for Final variables

class A

{
final float PI = 3.14F;
int rad;
A(int r)
{
rad=r;
}
float area_circle()
{
float area=PI*rad*rad;
//PI=PI+1; Error can’t change value of final variable
return(area);
}
}
public class FinalVar
{
public static void main(String args[])
4
II SEM JAVA PROGRAMMING 2022

{
A a =new A();
float area= a.area_circle(2);
System.out.println(“area of circle is “ + area);
}
}

Example for Final Methods


class A
{
final void meth()
{
System.out.println("This is a final method");
}
}
class B extends A
{
void meth()
{
System.out.println("Illegal"); //Error can’t override
}
}
public class FinalMeth
{
public static void main(String[] args)
{
B b =new B();
b.meth();
}
}

Final classes
 A class that can not be subclassed is called final class
 This is achieved by using the keyword final as follows:
final class A { ……… }
final class B extends C { ………. }
 Any attempt to inherit these classes will cause an error and the compiler will not allow it
 Declaring a class final prevents any unwanted extensions to the class

Example for Final Class


final class A
{
void meth()
{
System.out.println("This is a final class");
}
}
class B extends A //Error can’t extend final class
{
void method1()
5
II SEM JAVA PROGRAMMING 2022

{
System.out.println("Illegal");
}
}
public class FinalClass
{
public static void main(String[] args)
{
B b =new B();
b.method1();
}
}

Abstract methods and classes


 The use of final method ensures that the method is not redefined in a subclass which means that the method can
never be subclassed
 The opposite of this is, we can indicate that a method must always be redefined in a subclass, thus making
overriding compulsory
 This can be done by using the modifier keyword abstract in the method definition

Ex:
abstract class A
{
-----
abstract void display();
-----
}

 While using the abstract classes, the following conditions must be satisfied
 We can not use abstract classes to instantiate objects directly
Ex:
A a = new A();
is illegal because A is an abstract class
 The abstract methods of an abstract class must be defined in its subclass
 We cannot declare abstract constructors or abstract static methods
Example for Abstract Class and Abstract Method

abstract class A
{
abstract void callme();
void callmetoo()
{
System.out.println("THIS IS A CONCRETE METHOD");
}
}
class B extends A
{
void callme()
{
6
II SEM JAVA PROGRAMMING 2022

System.out.println("'B's IMPLEMENTATION OF CALLME.");


}
}
class abstractdemo
{
public static void main(String args[])
{
B b = new B();
b.callme();
b.callmetoo();
}
}

7
Packages:
A Package can be defined as a grouping of related types(classes, interfaces)
A package represents a directory that contains related group of classes and interfaces.
Packages are used in Java in order to prevent naming conflicts.
There are two types of packages in Java.
Pre-defined Packages(built-in)
User defined packages
Pre-defined Packages:

Package Description
Name
Contains language support classes (for e.g classes which definesprimitive
java.lang data types, math operations, etc.). This package is automatically imported.

java.io Contains classes for supporting input / output operations.

Contains utility classes which implement data structures like Linked List,
java.util Hash Table, Dictionary, etc and support for Date / Time operations. This
package is also called as Collections.
java.applet Contains classes for creating Applets.

Contains classes for implementing the components of graphical user interface


java.awt ( like buttons, menus, etc. ).

java.net Contains classes for supporting networking operations.

This package helps to develop GUI like java.awt. The ‘x’ in javax represents
javax.swing that it is an extended package which means it is a package developed from
another package by adding new features to it. In fact,
javax.swing is an extended package of java.awt.
This package helps to connect to databases like Oracle/Sybase/Microsoft
java.sql Access to perform different operations.

Defining a Package(User defined):


To create a package is quite easy: simply include a package command as the firststatement in a Java source
file. Any classes declared within that file will belong to the specified package. The package statement
defines a name space in which classes are stored. If you omitthe package statement, the class names are put
into the default package, which has no name.
This is the general form of the package statement:package pkg;
Here, pkg is the name of the package.
For example, the following statement creates a package called MyPackage:package MyPackage;
Java uses file system directories to store packages. For example, the .class files for any classes you declare to
be part of MyPackage must be stored in a directory called MyPackage. Remember that case is significant,
and the directory name must match the package nameexactly. 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. It does not
exclude other classes in other files from being part of that same package. Most real-world packages are
spread across many files. You can create a hierarchy of packages. To do so, simply separate each package
name from the one above it by use of a period. The general form of a multileveled package statement is shown
here:
package pkg1[.pkg2[.pkg3]];
A package hierarchy must be reflected in the file system of your Java development system. For example, a
package declared as
package java.awt.image;

Example: Package demonstrationpackage pack;


public class Addition
{
int x,y;
public Addition(int a, int b)
{
x=a; y=b;
}
public void sum()
{
System.out.println("Sum :"+(x+y));
}
}
Step 1: Save the above file with Addition.java

package pack;
public class Subtraction
{
int x,y;
public Subtraction(int a, int b)
{
x=a; y=b;
}
public void diff()
{
System.out.println("Difference :"+(x-y));
}
}

Step 2: Save the above file with Subtraction.java


Step 3: Compilation
To compile the java files use the following commands
javac -d directory_pathname_of_the_java file
Javac –d name_of_the_java file
Note: -d is a switching options creates a new directory with package name. Directory path
represents in which location you want to create package and . (dot) represents current
working directory.

Step 4: Access package from another package


There are three ways to use package in another package:
With fully qualified name.
class UseofPack
{
public static void main(String arg[])
{
pack.Addition a=new pack.Addition(10,15);a.sum();
pack.Subtraction s=new pack.Subtraction(20,15);s.difference();
}
}
import package.classname;

import pack.Addition; import pack.Subtraction;class UseofPack


{
public static void main(String arg[])
{
Addition a=new Addition(10,15);a.sum();
Subtraction s=new Subtraction(20,15);s.difference();
}
}
import package.*;
import pack.*; class UseofPack
{
public static void main(String arg[])
{
Addition a=new Addition(10,15);a.sum();
Subtraction s=new Subtraction(20,15);s.difference();
}
}
Note: Don’t place Addition.java, Subtraction.java files parallel to the pack directory. If you
place JVM searches for the class files in the current working directory not in thepack
directory.

Access Protection
Access protection defines actually how much an element (class, method, variable) isexposed to other
classes and packages.
There are four types of access specifiers available in java:
Visible to the class only (private).
Visible to the package (default). No modifiers are needed.
Visible to the package and all subclasses (protected)
Visible to the world (public)

Example:
The following example shows all combinations of the access control modifiers. This example has two
packages and five classes. The source for the first package defines threeclasses: Protection, Derived, and
SamePackage.
Name of the package: pkg1
This file is Protection.javapackage pkg1;
public class Protection
{
int n = 1;
private int n_priv = 2; protected int n_prot = 3;public int n_publ = 4;

public Protection()
{
System.out.println("base constructor"); System.out.println("n = " + n);
System.out.println("n_priv = " + n_priv); System.out.println("n_prot = " + n_prot);
System.out.println("n_publ = " + n_publ);
}
}

This is file Derived.java:


package pkg1;

class Derived extends Protection


{
Derived()
{
System.out.println("Same package - derived (from base) constructor");
System.out.println("n = " + n);

/* class only
* System.out.println("n_priv = "4 + n_priv); */

System.out.println("n_prot = " + n_prot);System.out.println("n_publ = " +n_publ);


}
}

This is file SamePackage.javapackage pkg1;


class SamePackage
{
SamePackage()
{
Protection pro = new Protection(); System.out.println("same package - other constructor");
System.out.println("n = " + pro.n);

/* class only
* System.out.println("n_priv = " + pro.n_priv); */

System.out.println("n_prot = " + pro.n_prot)


System.out.println("n_publ = " + pro.n_publ);
}
}

Name of the package: pkg2

This is file Protection2.java:package pkg2;


class Protection2 extends pkg1.Protection
{
Protection2()
{
System.out.println("Otherpackage-Derived(fromPackage1-Base)Constructor");
/* class or package only
System.out.println("n = " + n); */

/* class only
System.out.println("n_priv = " + n_priv); */

System.out.println("n_prot = " + n_prot); System.out.println("n_publ = " + n_publ);


}
}

This is file OtherPackage.java


package pkg2;

class OtherPackage
{
OtherPackage()
{
pkg1.Protection pro = new pkg1.Protection();
System.out.println("other package - Non sub class constructor");
/* class or package only System.out.println("n = " + pro.n); */

/* class only System.out.println("n_priv = " + pro.n_priv); */

/* class, subclass or package only System.out.println("n_prot = " + pro.n_prot); */

System.out.println("n_publ = " + pro.n_publ);


}
}

If you want to try these t two packages, here are two test files you can use. The one forpackage pkg1 is
shown here:

/* demo package pkg1 */package pkg1;


/* instantiate the various classes in pkg1 */
public class Demo
{
public static void main(String args[])
{
Derived obj2 = new Derived();
SamePackage obj3 = new SamePackage();
}
}

The test file for package pkg2 ispackage pkg2;


/* instantiate the various classes in pkg2 */
public class Demo2
{
public static void main(String args[])
{
Protection2 obj1 = new Protection2(); OtherPackage obj2 = new OtherPackage();
}
}
Interfaces:
A named collection of method declarations.
A Java interface is a collection of constants and abstract methods
Since all methods in an interface are abstract, the abstract modifier is usually left off
Using interface, you can specify what a class must do, but not how it does.
Interface fields are public, static and final by default, and methods are public and abstract.

Advantages of interfaces:
It is used to achieve abstraction.
By interface, we can support the functionality of multiple inheritances.

Syntax:
access_specifier interface interfae_name
{
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
//...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}
Implementing Interfaces:
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 thencreate the methods
defined by the interface.
The general form of a class that includes the implements clause looks like this:
class classname [extends superclass] [implements interface1 [,interface2...]] {
// class-body
}
If a class implements more than one interface, the interfaces are separated with a comma.
The methods that implement an interface must be public. Also, the type signature of implementing method must
match exactly the type signature specified in interface definition.

Example 1: Write a java program to implement interface.


interface Moveable
{
int AVG_SPEED=30;
void Move();
}
class Move implements Moveable
{
void Move(){
System .out. println ("Average speed is: "+AVG_SPEED );
}
}
class Vehicle
{
public static void main (String[] arg)
{
Move m = new Move();m.Move();
}
}
Example 2: Write a java program to implement interface.
interface Teacher
{
void display1();
}
interface Student
{
void display2();
}
class College implements Teacher, Student
{
public void display1()
{
System.out.println("Hi I am Teacher");
}
public void display2()
{
System.out.println("Hi I am Student");
}
}
class CollegeData
{
public static void main(String arh[])
{
College c=new College();c.display1();
c.display2();
}
}

Accessing implementations through interface references:


We can declare variables as object references that use an interface rather than a class type.
Any instance of any class that implements the declared interface can be referred to by sucha
variable. When you call a method through one of these references, the correct version will be
called based on the actual instance of the interface being referred to. This is one of the key
features of interfaces. The method to be executed is looked up dynamically at run time,
allowing classes to be created later than the code which calls methods on them.
Ex:
interface Test {

void call();
}

class InterfaceTest implements Test {

public void call()


{
System.out.println("call method called");
}
}

public class IntefaceReferences {

public static void main(String[] args)


{
Test f ;
InterfaceTest it= new InterfaceTest(); f=it;
f.call();
}
}

Variables in Interfaces:

We can use interfaces to import shared constants into multiple classes by simply declaring an
interface that contains variables that are initialized to the desired values. When we include that
interface in a class (that is, when you “implement” the interface), all of those variable names
will be in scope as constants. (This is similar to using a header file in C/C++ to create a large
number of #defined constants or const declarations). If an interface contains no methods, then
any class that includes such an interface doesn’t actually implement anything. Itis as if that
class were importing the constant fields into the class name space as final variables.
Example: Java program to demonstrate variables in interface.interface left
{
int i=10;
}
interface right

{
int i=100;
}
class Test implements left,right
{
public static void main(String args[])
{
System.out.println(left.i);//10 will be printed System.out.println(right.i);//100 will be printed*/
}
}

Interfaces can be extended:


One interface can inherit another by use of the keyword extends. The syntax is the sameas 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.
Example: Java program to demonstrate interfaces can be extended with extend keyword.
interface Teacher
{
void display1();
}
interface Student
{
void display2();
}
interface T_S extends Teacher, Student
{
void display3();
}
class College implements T_S
{
public void display1()
{
System.out.println("Hi I am Teacher");
}
public void display2()
{
System.out.println("Hi I am Student");
}
public void display3()
{
System.out.println("Hi I am Teacher_Student");

}
}
class Class_Interface
{
public static void main(String arh[])
{
College c=new College();c.display1();
c.display2();
c.display3();
}
}

Example 2: Java program to implement interface and inheriting the properties from a class.
interface Teacher
{
void display1();
}
class Student
{
void display2()
{
System.out.println("Hi I am Student");
}
}
class College extends Student implements Teacher
{
public void display1()
{
System.out.println("Hi I am Teacher");
}
}
class Interface_Class
{
public static void main(String arh[])
{
College c=new College();c.display1();
c.display2();
}
}
Difference between Interface and Abstract class:
Abstract Class Interface

Contains some abstract methods and some Only abstract methods


concrete methods
Contains instance variables Only static and final variables

Doesn’t support multiple inheritance Supports

public class Apple extends Food { … } public class Person implements


Student,Athlete,Chef { … }
Exception Handling
Introduction
An exception is an event that occurs during the execution of a program that disrupts the normal flow of
instruction.

Or
An abnormal condition that disrupts Normal program flow.

There are many cases where abnormal conditions happen during program execution, such as
 Trying to access an out - of –bounds array elements.
 The file you try to open may not exist.
 The file we want to load may be missing or in the wrong format.
 The other end of your network connection may be non –existence.
 If these cases are not prevented or at least handled properly, either the program will be aborted
abruptly, or the incorrect results or status will be produced.
 When an error occurs with in the java method, the method creates an exception object and hands it off
to the runtime system.
 The exception object contains information about the exception including its type and the state of the
program when the error occurred. The runtime system is then responsible for finding some code to
handle the error.
 In java creating an exception object and handling it to the runtime system is called throwing an
exception.
 Exception is an object that is describes an exceptional ( i.e. error) condition that has occurred in a piece
of code at run time.
 When a exceptional condition arises, an object representing that exception is created and thrown in the
method that caused the error. That method may choose to handle the exception itself, or pass it on.
Either way, at some point, the exception is caught and processed.
 Exceptions can be generated by the Java run-time system, or they can be manually generated by your
code.
 System generated exceptions are automatically thrown by the Java runtime system

General form of 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
}

For Example:
class Exc0 {
public static void main(String args[])
{ int d = 0;
int a = 42 / d;
}
}

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 supp 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. Here is the output generated when this example is executed.
java.lang.ArithmeticException: / by zero at Exc0.main(Exc0.java:4)
Notice how the class name, Exc0; the method name, main; the filename, Exc0.java; and the line number, 4

Try and Catch Blocks


If we don’t want to prevent the programapthe to trap the exception using the try block. So we can place the
statements that may causes an
exception in the try block.
Try
{
}
If an exception occurs with in the try block, the appropriate exception handler that is associated with the try
block handles the exception immediately following the try block, include a catch clause specifies the exception
type we wish to catch. A try block must have at least one catch block or finally that allows it immediately.
Catch block
The catch block is used to process the exception raised. A try block can be one or more catch blocks can handle a
try block.
Catch handles are placed immediately after the try block.
Catch(exceptiontype e)
{
//Error handle routine is placed here for handling exception
}
Program 1
Class trycatch
{
Public static void main(String args[])
{
Int[] no={1,2,3};
Try
{
System.out.println(no[3]);
}
Catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(―Out of bonds‖);
}
System.out.println(―Quit‖);
}
}

Output
Out of the Range Quit
Program 2 Class ArithExce
{
Public static void main(String args[])
{
Int a=10; Int b=0; Try
{
a=a/b; System.out.println(―Won’t Print‖);
}
Catch(ArithmeticException e)
{
System.out.println(―Division by Zero error‖); System.out.println(―Change the b value‖);
}
System.out.println(―Quit‖);
}
}

Output
Division By zero error Please change the B value Quit

Note:
A try ad its catch statement form a unit. We cannot use try block alone.
The compiler does not allow any statement between try block and its associated catch block
Displaying description of an Exception
Throwable overrides the toString() method (defined by Object) so that it returns a string containing a description
of the exception.
We can display this description in a println statement by simply passing the exception as an argument.
catch (ArithmeticException e) { System.out.println("Exception: " + e); a = 0; // set a to zero and continue
}
When this version is substituted in the program, and the program is run, each divide-by- zero error displays the
following message:
– Exception: java.lang.ArithmeticException: / by zero
Multiple Catch Blocks
In some cases, more than one exception could be raised by a single piece of code. To handle this type of
situation, you can specify two or more catch clauses, each catching a different type of exception. When an
exception is thrown, each catch statement is inspected in order, and the first one whose type matches that of the
exception is executed. After one catch statement executes, the others are bypassed, and execution continues after
the try/catch block. The following example traps two different exception types:

// Demonstrate multiple catch statements.


class MultiCatch {
public static void main(String args[])
{
try {
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 }; c[42] = 99;
} catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
} catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}
This program will cause a division-by-zero exception if it is started with no commandline parameters, since a
will equal zero. It will survive the division if you provide a command-line argument, setting a to something
larger than zero. But it will cause an ArrayIndexOutOfBoundsException, since the int array c has a length of
1, yet the program attempts to assign a value to c[42].
Here is the output generated by running it both ways: C:\>java MultiCatch
a=0
Divide by 0: java.lang.ArithmeticException: / by zero After try/catch blocks.
C:\>java MultiCatch TestArg a = 1
Array index oob: java.lang.ArrayIndexOutOfBoundsException After try/catch blocks.

Throw Keyword
So far, we have only been catching exceptions that are thrown by the Java Run –Time systems. How ever, it is
possible for our program to throw an exception explicitly, using the throw statement.
Throw throwableInstance
Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable. Simple types, such
as int or char, as well as non-Throwable classes, such as String and Object, cannot be used as exceptions
There are two ways you can obtain a Throwable object:
– using a parameter into a catch clause
– creating one with the new operator.

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 the
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
// Demonstrate throw. class ThrowDemo { static void demoproc()
{ try {
throw new NullPointerException("demo");
} catch(NullPointerException e) { System.out.println("Caught inside demoproc."); throw e; // rethrow the
exception
}
}
public static void main(String args[])
{ try
{
demoproc();
} catch(NullPointerException e)
{
System.out.println("Recaught: " + e);
}
}}

This program gets two chances to deal with the same error. First, main( ) sets up an exception context and then
calls demoproc( ). The demoproc( ) method then sets up another exception-handling context and immediately
throws a new instance of NullPointerException, which is caught on the next line. The exception is then
rethrown. Here is the resulting output:
Caught inside demoproc.
Recaught: java.lang.NullPointerException: demo
The program also illustrates how to create one of J close attention to this line:
throw new NullPointerException("demo");
Here, new is used to construct an instance of NullPointerException. All of- Java’ in run-time exceptions have at
least two constructors: one with no parameter and one that
takes a string parameter. When the second form is used, the argument specifies a string that describes the
exception. This string is displayed when the object
is used as an argument to print( ) or println( ). It can also be obtained by a call to
getMessage( ), which is defined by Throwable.

Throws Keyword
If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers
of the method can guard themselves against that exception. You
do this by including a throws clause in the method’sthrowsclauselistsdeclar the types of exceptions that a
method might throw. 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. If they are not, a compile-time error will result. This is the
general form of a method declaration that includes a throws clause:
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
Program
class ThrowsDemo {
static void throwOne() throws IllegalAccessException
{ System.out.println("Inside throwOne."); throw new IllegalAccessException("demo");
}
public static void main(String args[]) { try {
throwOne();
} catch (IllegalAccessException e)
{ System.out.println("Caught " + e);
}
}
}
Here is the output generated by running this example program:
inside throwOne
caught java.lang.IllegalAccessException

Finally block
Throws is followed by class.
Throws is used with the method signature.
You can declare multiple exceptions e.g. public void method()throws IOException,SQLException.
When exceptions are thrown, execution in a method takes a rather abrupt, nonlinear
path that alters the normal flow through the method. Depending upon how the method is coded, it is even
possible for an exception to cause the method to return prematurely.
This could be a problem in some methods. For example, if a method
opens a file upon entry and closes it upon exit, then you will not want the code that closes the file to be bypassed
by the exception-handling mechanism. The finally keyword is designed to address this contingency.
finally creates a block of code that will be executed after a try/catch block has completed and before the code
following the try/catch block. The finally block will execute whether or not an exception is thrown. If an
exception is thrown, the finally block will execute even if no catch statement matches the exception. 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. This can be useful for closing
file handles and freeing up any other resources that might have been allocated at the beginning of a method with
the intent of disposing of them before returning. The finally clause is optional. However, each try statement
requires at least one catch or a finally clause.
// Demonstrate finally. class FinallyDemo {
// Through an exception out of the method. static void procA() {
try {
System.out.println("inside procA"); throw new RuntimeException("demo");
} finally { System.out.println("procA's finally");
}
}
// Return from within a try block. static void procB() { try {
System.out.println("inside procB"); return;
} finally { System.out.println("procB's finally");
}
}
// Execute a try block normally. static void procC() {
try {
System.out.println("inside procC"); } finally { System.out.println("procC's finally");
}
}
public static void main(String args[]) { try {
procA();
} catch (Exception e) { System.out.println("Exception caught");
}
procB();
procC();
}
}
In this example, procA( ) prematurely breaks out of the try by throwing an exception. The finally clause is
executed on the way out. procB( )’stry statement is exited via a return statement. The finally clause is executed
before procB( ) returns. In procC( ), the try statement executes normally, without error. However, the finally
block is still executed. If a finally block is associated with a try, the finally block will be executed upon
conclusion of the try.
Here is the output generated by the preceding program: inside procA
procA’s finally Exception caught
inside procB
procB’s finally inside procC procC’sly final
Java final example
1. class FinalExample{
2. public static void main(String[] args){
3. final int x=100;
4. x=200;//Compile Time Error 5. }}

Java finally example


1. class FinallyExample{
2. public static void main(String[] args){
3. try{
4. int x=300;
5. }catch(Exception e){System.out.println(e);}
6. finally{System.out.println("finally block is executed");} 7. }}

Java finalize example


1. class FinalizeExample{
2. public void finalize(){System.out.println("finalize called");}
3. public static void main(String[] args){
4. FinalizeExample f1=new FinalizeExample();
5. FinalizeExample f2=new FinalizeExample();
6. f1=null;
7. f2=null;
8. System.gc(); 9. }}

Java Built –In Exceptions


Inside the standard package java.lang, Java defines several exception classes. A few have been used by the
preceding examples. The most general of these exceptions are subclasses of the standard type
RuntimeException. Since java.lang is implicitly imported into all Java programs, most exceptions derived from
RuntimeException are automatically available. Furthermore, they need not be includedthrowslist. inInthe
languageany ofmethod’sJava,thesearecalled unchecked exceptions because the compiler does not check to see if
a method handles or throws these exceptions. The unchecked exceptions defined in java.lang are listed in Table
10-1. Table
lists those exceptions defined by java.lang that must be includedthrowslist in if that method can generate one
of these exceptions and does not handle it itself. These are called
checked exceptions. Java defines several other types of exceptions that relate to its various class libraries

List of Unchecked exceptions


List of Checked exceptions

User defined exceptions


We can create our own exception by extending exception class.
The throw and throws keywords are used while implementing user defined exceptions
Class ownExcepion extends Exception
{
ownException(String msg)
{
Super(msg);
}
}
Class test
{
Public static void main(String args[]) Int mark=101;
Try
{
if(mark>100)
{
Throw new ownException(―Marks>100‖);
}
}
Catch(ownException e)
{
System.out.println (―Exception caughtr‖); System.out.println.(―e.getMessage());
}
Finally
{
System.out.println(―End of prg‖);
}
}
}

Output:
Exception caught Marks is > 100 End of program
Multithreaded Programming
1

MULTITHREADING
Introduction
2

• Unlike many other computer languages, Java


provides built-in support for multithreaded
programming.
• A multithreaded program contains two or more
parts that can run concurrently.
• Each part of such a program is called a
thread, and each thread defines a separate
path of execution.
• Thus, multithreading is a specialized form of
multitasking.
3

• However, there are two distinct types of


multitasking:
– Process based
– Thread based
• It is important to understand the difference
between the two.
• A process is, in essence, a program that is
executing. Thus, process-based multitasking is
the feature that allows your computer to run two
or more programs concurrently.
4

 For example, process-based multitasking


enables you to run the Java compiler at the
same time that you are using a text editor.
 In process based multitasking, a program is
the smallest unit of code that can be
dispatched by the scheduler.
5

• In a thread-based multitasking environment,


the thread is the smallest unit of dispatchable
code.
• This means that a single program can perform
two or more tasks simultaneously.
• For instance, a text editor can format text at
the same time check for spelling, as long as
these two actions are being performed by two
separate threads.
Benefits of Multithreading
6

 Multitasking threads require less overhead


than multitasking processes.
 Processes are heavyweight tasks that require
their own separate address spaces.
 Inter process communication is expensive.
 Context switching from one process to another
is also costly.
Benefits of Multithreading
7

• Threads, on the other hand, are lightweight.


• They share the same address space.
• Interthread communication is inexpensive.
• Context switching from one thread to the next
is low cost.
• Multithreading enables you to write very
efficient programs that make maximum use of
the CPU, because idle time can be kept to a
minimum.
10
Life cycle of a thread
 During the life time of a thread, there are many states it
can enter
 They are
1) newborn state
2) runnable state
3) running state
4) blocked state
5) dead state
 A thread is always in one of these 5 states
 It can move from one state to another via a variety of
ways.
 State transition diagram of a thread
 New Thread  Newborn

11
 stop
 start
 Active Thread
 stop  Dead Killed

 Running  Runnable  Thread


 yield

 suspend  resume
 stop
 sleep  notify
 wait

 Idle thread  Blocked


Newborn state
 When we create a thread object, the thread is born and is
said to be in newborn state

 The thread is not yet scheduled for running

 At this state, we can do only one of the following


› Schedule it for running using start() method
› Kill it using stop() method

 If we attempt to use any other method at this stage, an


exception will be thrown

 If scheduled, it moves to the runnable state as shown below:


Newborn

start stop

Runnable Dead
state state
Runnable state
 This state means that the thread is ready for
execution and is waiting for the availability of
the processor

 That is, the thread has joined the queue of


threads that are waiting for execution

 If all threads have equal priority, then they are


given time slots for execution in round robin
fashion, i.e. first-come, first-serve manner
Runnable state

 The thread that relinquishes control joins the


queue at the end and again waits for its turn

 This process of assigning time to threads is


known as time-slicing
yield()
However, if we want a thread to relinquish control to
another thread to equal priority before its turn comes, we
can do so by using the yield() method

yield

. . . .

Running Thread
Running State
 Running means that the processor has given
its time to the thread for its execution

 The thread runs until it relinquishes control on


its own or it is preempted by a higher priority
thread
A running thread may relinquish its control in one of the following situations:

1. It has been suspended using suspend()


method. A suspended thread can be revived by
using the resume() method. This approach is
useful when we want to suspend a thread for
some time due to certain reason, but do not
want to kill it
suspend

. . .

suspended
Runnable
Running
2. It has been made to sleep. We can put a thread
to sleep for a specified time period using the
method sleep(time) where time is in milliseconds.
This means that the thread is out of the queue
during this time period. The thread re-enters the
runnable state as soon as this time period is
elapsed

sleep(t)

. after(t)
. .

Running Suspended
Runnable
3. It has been told to wait until some event occurs. This
is done using the wait() method. The thread can be
scheduled to run again using the notify() method

wait

. notify
. .

Running Waiting
Runnable
Blocked Thread
 a thread is said to be blocked when it is prevented
from entering into the runnable state and
subsequently the running state

 This happens when the thread is suspended,


sleeping or waiting in order to satisfy certain
requirements

 A blocked thread is considered not runnable but not


dead and therefore fully qualified to run again
Dead state
 A running thread ends its life when it has completed
executing its run() method

 It is a natural death

 However, we can kill it by sending the stop message


to it at any state thus causing a premature death to it

 A thread can be killed as soon it is born, or while it is


running, or even when it is in not runnable condition
Thread Class and Runnable Interface
23

 To create a new thread, your program will either extend


Thread or
 implement the Runnable interface.
 Methods defined in Thread Class
 getName
 getPriority
 isAlive
 join
 run
 sleep
 start
 stop
 Etc…..
24

Method Meaning

getName Obtain a thread’s name.

getPriority Obtain a thread’s priority.

isAlive Determine if a thread is still running.

join Wait for a thread to terminate.

run Entry point for the thread.

sleep Suspend a thread for a period of time.

start Start a thread by calling its run


method.
The Main Thread
25

 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 two reasons:
 It is the thread from which other “child” threads
will be spawned.
 Often, it must be the last thread to finish
execution because it performs various shutdown
actions.
The Main Thread
26

 Although the main thread is created


automatically when your program is started, it
can be controlled through a Thread object.
 To do so, you must obtain a reference to it
by calling the method currentThread( )
 which is a public static member of Thread.
 Its general form is
 static Thread currentThread( )
The Main Thread
27

 This method returns a reference to the thread in


which it is called.
 Once you get the reference to the main thread,
you can control it just like any other thread.
Controlling Main Thread
28

public class CurrentThreadDemo


{
public static void main(String args[])
{
Thread t=Thread.currentThread();
System.out.println("Current Thread:"+t);
t.setName("My Thread");
System.out.print("After name change:"+t);
29

try
{
for(int n=5;n>0;n--)
{
System.out.println(n);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("Main Thread Intertrupted");
}
}
}
30

 final void setName(String threadName)


 final String getName( )
 static void sleep(long milliseconds) throws
InterruptedException
Creating a Thread
31

 In the most general sense, you create a thread


by instantiating an object of type Thread.

 Java defines two ways in which this can be


accomplished:
 You can implement the Runnable interface.
 You can extend the Thread class, itself.
Two Ways to Create Threads

1. By creating a thread class


define a class that extends Thread class and
override its run() method with the code required
by the thread

2. By converting a class to a thread


define a class that implements Runnable interface.
The Runnable interface has only one method,
run(), that is to be defined in the method with the
code to be executed by the thread
Implementing Runnable Interface

 The Runnable interface declares the run() method that is


required for implementing threads in our programs

 To do this, we must perform the steps listed below:

1. declare the class as implementing the Runnable


interface

2. implement the run() mehtod


3. create a thread by defining an object that is instantiated
from this runnable class as the target of the thread

4. call the thread’s start() method to run the thread


Implementing the Runnable
34
Interface
class NewThread implements Runnable
{
Thread t;
NewThread()
{
t=new Thread(this, "Demo Thread");
System.out.println("Child Thread:" + t);
t.start();
}
35

public void run()


{
try
{
for(int i=5;i>0;i--)
{
System.out.println("Child Thread:"+i);
Thread.sleep(500);
}
}
catch(InterruptedException e)
{
System.out.println("Child Inrerrupted");
}
System.out.println("Exiting child thread.");
} }
36

class RunnableDemo1
{
public static void main(String args[])
{
new NewThread();
try
{
for(int i=5;i>0;i--)
{
System.out.println("main Thread:"+i);
Thread.sleep(1000);
}
}
37

catch(InterruptedException e)
{
System.out.println("main thread interrupted");
}
System.out.println("Main thread exiting.");
}
}
Extending Thread
38

 We can make our class runnable as thread by


extending the class java.lang.Thread

 This gives us access to all the thread methods


directly
Steps to Extend a Thread
class
1. Declare the class as extending the Thread
class

2. Implement the run() method that is


responsible for executing the sequence of
code that the thread will execute

3. Create a thread object and call the start()


method to initiate the thread execution
1. Declaring the class

The Thread class can be extended as


class XYZ extends Thread
{
-----------
-----------
}
2. Implementing the run()
Method
 The run() method has been inherited by
previously created class XYZ

 We have to override this method in order to


implement the code to be executed by our thread

 When we start the new thread, Java calls the


thread’s run() method, so it is the run() where all
the action takes place
The basic implementation of run() will look as
public void run()
{
---------
}
3. Starting new thread
 to actually create and run an instance of our
thread class, we must write the following:
XYZ x=new XYZ();
x.start();

 the first line instantiates a new object of class


XYZ. This statement just creates the object
and thread is in a newborn state
 The second line calls the start() method
causing the thread to move into the runnable
state.

 Then, the Java runtime will schedule the


thread to run by invoking the run() method.

 Now, the thread is said to be in the running


state
45

class NewThread extends Thread


{
NewThread()
{
super("Extended Thread");
System.out.println("Child Thread:" + this);
start();
}
public void run()
{
try
46
{
for(int i=5;i>0;i--)
{
System.out.println("Child Thread:"+i);
Thread.sleep(500);
}
}
catch(InterruptedException e)
{
System.out.println("Child Inrerrupted");
}
System.out.println("Exiting child thread.");
}
}
class ThreadDemo1
{
47
public static void main(String args[])
{
new NewThread();
try
{
for(int i=5;i>0;i--)
{
System.out.println(“Main Thread:"+i);
Thread.sleep(1000);
}
}
48

catch(InterruptedException e)
{
System.out.println("main thread interrupted");
}
System.out.println("Main thread exiting.");
}
}
Creating Multiple Threads
49

// Create multiple threads.


class NewThread implements Runnable
{
String name; // name of thread
Thread t;
NewThread(String threadname)
{
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
public void run()
{
50 try
{
for(int i = 5; i > 0; i--)
{
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println(name + "Interrupted");
}
System.out.println(name + " exiting.");
}
}
class MultiThreadDemo
{
public static void main(String args[])
51
{
new NewThread("One"); // start threads
new NewThread("Two");
new NewThread("Three");
try
{
// wait for other threads to end
Thread.sleep(10000);
}
catch (InterruptedException e)
{
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}
Using isAlive( ) and join( )
53

 As mentioned, often you will want the main


thread to finish last. In the preceding examples,
 this is accomplished by calling sleep( ) within
main( ), with a long enough delay to ensure that all
child threads terminate prior to the main thread.
 However, this is hardly a satisfactory solution,
and it also raises a larger question: How can
one thread know when another thread has
ended?
 Thread provides a means by which you can
answer this question.
Using isAlive and join()
54

 final boolean isAlive( )

 While isAlive( ) is occasionally useful, the


method that you will more commonly use to
wait for a thread to finish is called join( ),
shown here:
 final void join( ) throws InterruptedException

 Calling Thread is waiting until the specified


thread joins it.
IsAlive and Join Example
55

 Of course, the exact output produced by this


program depends on the speed of your CPU
and the number of other tasks running in the
system.
Thread Priority
56

 Thread priorities are used by the thread scheduler to


decide when each thread should be allowed to run.

 In theory, higher-priority threads get more CPU time


than lower-priority threads.

 In practice, the amount of CPU time that a thread gets


often depends on several factors besides its priority.
(For example, how an operating system implements
multitasking can affect the relative availability of CPU
time.)
Thread Priority
57

 The Thread class defines several priority


constants:
MIN_PRIORITY 1
NORM_PRIORITY 5
MAX_PRIORITY 10
 The int number may assume one of these
constants or any value between 1 and 10

 The default setting is NORM_PRIORITY

 Whenever multiple threads are ready for


execution, the Java system chooses the highest
priority thread and executes it
Thread Priority
58

 A higher-priority thread can preempt(stop or


prevent) a lower-priority one.

 Methods used to set and get the priorities of a


thread.
 final void setPriority(int level)
 final int getPriority()
For a thread of lower priority to gain control, one
of the following things should happen:
59

1) It stops running at the end of run()


2) It is made to sleep using sleep()
3) It is told to wait using wait()/suspend()
4) I/O operation

 If another thread of a higher priority comes along,


the currently running thread will be preempted by
the incoming thread thus forcing the current
thread to move to the runnable state
Synchronization
 Threads use their own data and methods provided
inside their run() methods

 If they try to use data and methods outside


themselves, leads to serious problems
 Ex:
 one thread may try to read a record from a file while
another is still writing to the same file

 Java enables us to overcome this problem using a


technique known as synchronization
Synchronization
61

 When two or more threads need access to a


shared resource, they need some way to
ensure that the resource will be used by only
one thread at a time. The process by which
this is achieved is called synchronization.
62

 Synchronization is easy in Java, because all


objects have their own implicit monitor
associated with them.
 To enter an object’s monitor, just call a method
that has been modified with the synchronized
keyword.

Ex:
synchronized void update()
{
----------
63

 While a thread is inside a synchronized


method, all other threads that try to call it (or
any other synchronized method) on the same
instance have to wait.
 To exit the monitor and relinquish control of the
object to the next waiting thread, the owner of
the monitor simply returns from the
synchronized method.
64

// This program is not synchronized.


class Callme {
void call(String msg) {
System.out.print("[" + msg);
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
System.out.println("Interrupted");
}
System.out.println("]");
}
}
class Caller implements Runnable {
String msg;
65
Callme target;
Thread t;
public Caller(Callme targ, String s) {
target = targ;
msg = s;
t = new Thread(this);
t.start();
}
public void run() {
target.call(msg);
}
}
class Synch {
public static void main(String args[]) {
66
Callme target = new Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");
// wait for threads to end
try {
ob1.t.join();
ob2.t.join();
ob3.t.join();
} catch(InterruptedException e) {
System.out.println("Interrupted");
}}}
67

 Here is the output produced by this program:


Hello[Synchronized[World]
]
]
68

 As you can see, by calling sleep( ), the call( )


method allows execution to switch to another
thread.
 This results in the mixed-up output of the three
message strings.
 In this program, nothing exists to stop all three
threads from calling the same method, on the
same object, at the same time.
 This is known as a race condition, because
the three threads are racing each other to
complete the method.
 To fix the preceding program, you must serialize access to
call( ).
69  That is, you must restrict its access to only one thread at a
time.
 To do this, you simply need to precede call( )’s definition with
the keyword synchronized, as shown here:
class Callme {
synchronized void call(String msg) {

 This prevents other threads from entering call( ) while
another thread is using it.
 After synchronized has been added to call( ), the output of
the program is as follows:
[Hello]
[Synchronized]
wait( ), notify( ), and notifyAll( )
methods
70

 These methods are implemented as final methods in


Object, so all classes have them.
 All three methods can be called only from within a
synchronized context.
 wait( ) tells the calling thread to give up the monitor

and go to sleep until some other thread enters the


same monitor and calls notify( ).
 notify( ) wakes up a thread that called wait( ) on the

same object.
 notifyAll( ) wakes up all the threads that called wait(

) on the same object. One of the threads will be


granted access.
Producer-Consumer solution using
threads
71

 Producer–consumer problem (also known as the


bounded-buffer problem) is a classic example of a multi-
process synchronization problem.
 The problem describes two processes, the producer and
the consumer, which share a common, fixed-size buffer
used as a queue.

 The producer’s job is to generate data, put it into the


buffer, and start again.
 At the same time, the consumer is consuming the data
(i.e. removing it from the buffer), one piece at a time.
72

 Problem
To make sure that the producer won’t try to
add data into the buffer if it’s full and that the
consumer won’t try to remove data from an
empty buffer.
73

Solution
 The producer is to either go to sleep or discard data if the

buffer is full.
 The next time the consumer removes an item from the

buffer, it notifies the producer, who starts to fill the buffer


again.
 In the same way, the consumer can go to sleep if it finds

the buffer to be empty.


 The next time the producer puts data into the buffer, it

wakes up the sleeping consumer.


 An inadequate solution could result in a deadlock where

both processes are waiting to be awakened.


74

 Producer Consumer Problem

You might also like