OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
UNIT-II
Interfaces: Defining an interface, implementing interfaces, extending interface.
Packages: Defining, Creating and Accessing a Package, importing packages
Exception handling: Benefits of exception handling, classification, checked exceptions and
unchecked exceptions, usage of try, catch, throw, throws and finally, rethrowing exceptions, built in
exceptions, creating own exception sub classes
Multithreading: Java Thread Model, The Main Thread, creating a Thread, creating multiple
threads, using is Alive() and join(), thread priorities, synchronization, inter thread
communication,deadlock
Course Objective: To create Java application programs using sound OOP practices such as interfaces,
exception handling, multi threading.
Course Outcome Create Java application programs using sound OOP practices e.g. Inheritance,
interfaces and proper program structuring by using packages, access controlspecifiers
DEFINING AN INTERFACE
An interface in Java is a blueprint of a class. It has static constants and abstract methods. The
interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the
Java interface, not method body. It is used to achieve abstraction and multiple inheritances in Java.
In other words, you can say that interfaces can have abstract methods and variables. It cannot have a
method body. It cannot be instantiated just like the abstract class.
IMPLEMENTING INTERFACES
To declare a class that implements an interface, you include an implements clause in the class
declaration. Your class can implement more than one interface, so the implements keyword is
followed by a comma-separated list of the interfaces implemented by the class. By convention, the
implements clause follows the extends clause
Program:
interface printable{
void print();
}
class A6 implements printable{
public void print(){[Link]("Hello");}
public static void main(String args[]){
A6 obj = new A6();
[Link]();
}
}
1
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
EXTENDING INTERFACE
An interface extends another interface like a class implements an interface in interface
inheritance.
interface A {
void funcA();
}
interface B extends A {
void funcB();
}
class C implements B {
public void funcA() {
[Link]("This is funcA");
}
public void funcB() {
[Link]("This is funcB");
}}
public class Demo {
public static void main(String args[]) {
C obj = new C();
[Link]();
[Link]();
}}
DEFINING A PACKAGE
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
CREATING AND ACCESSING A PACKAGE
//save as [Link]
package mypack;
public class Simple{
public static void main(String args[]){
[Link]("Welcome to package");
}
}
To Compile: javac -d . [Link]
To Run: java [Link]
2
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
IMPORTING PACKAGES
//save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
[Link]();
} }
BENEFITS OF EXCEPTION HANDLING
Provision to Complete Program Execution
Easy Identification of Program Code and Error-Handling Code
Propagation of Errors
Meaningful Error Reporting
Identifying Error Types
CHECKED EXCEPTIONS
The classes that directly inherit the Throwable class except RuntimeException and Error are
known as checked exceptions. For example, IOException, SQLException, etc. Checked
exceptions are checked at compile-time.
UNCHECKED EXCEPTIONS
The classes that inherit the RuntimeException are known as unchecked exceptions. For
example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException,
etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime.
Java provides five keywords that are used to handle the exception
Try -The "try" keyword is used to specify a block where we should place an exception
code. It means we can't use try block alone. The try block must be followed by either
catch or finally.
Catch-The "catch" block is used to handle the exception. It must be preceded by try
block which means we can't use catch block alone. It can be followed by finally block
later.
Finally - The "finally" block is used to execute the necessary code of the program.
It is executed whether an exception is handled or not.
Throw- The "throw" keyword is used to throw an exception.
Throws- The "throws" keyword is used to declare exceptions. It specifies that there
may occur an exception in the method. It doesn't throw an exception. It is always used
with method signature.
3
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
Program:
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){[Link](e);}
//rest code of the program
[Link]("rest of the code...");
}
}
RETHROWING EXCEPTIONS
If a catch block cannot handle the particular exception it has caught, we can rethrow the
exception. The rethrow expression causes the originally thrown object to be rethrown.
catch(Exception e) {
[Link]("An exception was thrown");
throw e;
}
BUILT IN EXCEPTIONS
Built-in exceptions are the exceptions which are available in Java libraries. These exceptions
are suitable to explain certain error situations. Below is the list of some important built-in
exceptions in Java.
Arithmetic exception
ArrayIndexOutOfBounds Exception
ClassNotFoundException
FileNotFoundException
IOException
InterruptedException
NoSuchMethodException
NullPointerException
NumberFormatException
StringIndexOutOfBoundsException
Program:
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){[Link](e);}
//rest code of the program
[Link]("rest of the code...");
} }
4
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
CREATING OWN EXCEPTION SUB CLASSES
Program:
class CustomException extends Exception {
String message;
CustomException(String str) {
message = str;
}
public String toString() {
return ("Custom Exception Occurred : " + message);
}}
public class MainException {
public static void main(String args[]) {
try {
throw new CustomException("This is a custom
message");
} catch(CustomException e) {
[Link](e);
} }}
MULTITHREADING: JAVA THREAD MODEL
Multithreading is a Java feature that allows concurrent execution of two or more parts of a
program for maximum utilization of CPU. Each part of such program is called a thread. So,
threads are light-weight processes within a process.
Threads can be created by using two mechanisms:
Extending the Thread class
Implementing the Runnable Interface
THE MAIN THREAD, CREATING A THREAD, CREATING MULTIPLE THREADS
We create a class that extends the [Link] class. This class overrides the run() method
available in the Thread class. A thread begins its life inside run() method. We create an object of
our new class and call start() method to start the execution of a thread. Start() invokes the run()
method on the Thread object.
We create a new class which implements [Link] interface and override run() method.
Then we instantiate a Thread object and call start() method on this object.
Program:
// Java code for thread creation by extending
// the Thread class
class MultithreadingDemo extends Thread {
public void run()
{
try {
// Displaying the thread that is running
[Link](
"Thread " + [Link]().getId()+ " is running");
}
catch (Exception e) {
// Throwing an exception
[Link]("Exception is caught");
}}}
5
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
// Main Class
public class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
MultithreadingDemo object= new MultithreadingDemo();
[Link]();
}}}
THREAD USING IS Alive() AND join()
Program for alive():
public class MyThread extends Thread
{
public void run()
{
[Link]("r1 ");
try {
[Link](500);
}
catch(InterruptedException ie)
{
// do something
}
[Link]("r2 ");
}
public static void main(String[] args)
{
MyThread t1=new MyThread();
MyThread t2=new MyThread();
[Link]();
[Link]();
[Link]([Link]()); //is alive
[Link]([Link]());
}
}
Program for join():
public class MyThread extends Thread
{
public void run()
{
[Link]("r1 ");
try {
[Link](500);
}catch(InterruptedException ie){ }
[Link]("r2 ");
}
public static void main(String[] args)
{
MyThread t1=new MyThread();
MyThread t2=new MyThread();
[Link]();
6
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
try{
[Link](); //Waiting for t1 to finish // join() method
}catch(InterruptedException ie){}
[Link]();
}}
THREAD PRIORITIES
Each thread has a priority. Priorities are represented by a number between 1 and 10. In most
cases, the thread scheduler schedules the threads according to their priority (known as
preemptive scheduling). But it is not guaranteed because it depends on JVM specification
that which scheduling it chooses. Note that not only JVM a Java programmer can also assign
the priorities of a thread explicitly in a Java program
public final int getPriority(): The [Link]() method returns the priority
of the given thread.
public final void setPriority(int newPriority): The [Link]() method
updates or assign the priority of the thread to newPriority. The method throws
IllegalArgumentException if the value newPriority goes out of the range, which is 1
(minimum) to 10 (maximum).
public static int MIN_PRIORITY
public static int NORM_PRIORITY
public static int MAX_PRIORITY
Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1
and the value of MAX_PRIORITY is 10.
SYNCHRONIZATION
Synchronization in Java is the capability to control the access of multiple threads to any
shared [Link] Synchronization is better option where we want to allow only one
thread to access the shared resource.
The synchronization is mainly used to
To prevent thread interference.
To prevent consistency problem.
There are two types of synchronization
Process Synchronization
Thread Synchronization
Program:
class Table{
void printTable(int n){//method not synchronized
for(int i=1;i<=5;i++){
[Link](n*i);
try{
[Link](400);
}catch(Exception e){[Link](e);}
} }}
class MyThread1 extends Thread{
7
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
[Link](5);
} }
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
[Link](100);
} }
class TestSynchronization1{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
[Link]();
[Link]();
} }
INTER THREAD COMMUNICATION
Inter-thread communication or Co-operation is all about allowing synchronized threads to
communicate with each other.
Cooperation (Inter-thread communication) is a mechanism in which a thread is paused
running in its critical section and another thread is allowed to enter (or lock) in the same
critical section to be [Link] is implemented by following methods of Object class:
wait()
notify()
notifyAll()
8
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
Program:
class Customer{
int amount=10000;
synchronized void withdraw(int amount){
[Link]("going to withdraw...");
if([Link]<amount){
[Link]("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
[Link]-=amount;
[Link]("withdraw completed...");
}
synchronized void deposit(int amount){
[Link]("going to deposit...");
[Link]+=amount;
[Link]("deposit completed... ");
notify();
}}
class Test{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run(){[Link](15000);}
}.start();
new Thread(){
public void run(){[Link](10000);}
}.start();
}}
DEADLOCK
Deadlock in Java is a part of multithreading. Deadlock can occur in a situation when a thread is
waiting for an object lock, that is acquired by another thread and second thread is waiting for an
object lock that is acquired by first thread. Since, both threads are waiting for each other to release
the lock, the condition is called deadlock.
Program:
public class TestDeadlockExample1 {
public static void main(String[] args) {
final String resource1 = "ratan jaiswal";
final String resource2 = "vimal jaiswal";
// t1 tries to lock resource1 then resource2
Thread t1 = new Thread() {
public void run() {
synchronized (resource1) {
[Link]("Thread 1: locked resource 1");
try { [Link](100);} catch (Exception e) {}
synchronized (resource2) {
[Link]("Thread 1: locked resource 2");
} }}};
// t2 tries to lock resource2 then resource1
9
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
Thread t2 = new Thread() {
public void run() {
synchronized (resource2) {
[Link]("Thread 2: locked resource 2");
try { [Link](100);} catch (Exception e) {}
synchronized (resource1) {
[Link]("Thread 2: locked resource 1");
} } } };
[Link]();
[Link]();
}}
END OF UNIT-II
10