1 of 19

MATRUSRI ENGINEERING COLLEGEDEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

SUBJECT NAME: OOP USING JAVA

BE III SEM 2022-23

FACULTY NAME: A V MURALI KRISHNA

MATRUSRI

ENGINEERING COLLEGE

2 of 19

UNIT-2

MATRUSRI

ENGINEERING COLLEGE

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

Syllabus

3 of 19

INTRODUCTION:��

PRELIMINARY CONCEPTS

MATRUSRI

ENGINEERING COLLEGE

OUTCOMES:

Java enables programmers to write native methods to handle situations when an application cannot be written entirely in the Java programming language, e.g. when the standard Java class library does not support the platform-specific features or program library

Course Objective: To create Java application programs using sound OOP practices such as interfaces, exception handling, multi threading.

 

Create Java application programs using sound OOP practices e.g. Inheritance, interfaces and proper program structuring by using packages, access controlspecifiers

4 of 19

CONTENTS:1) Interfaces�2) Packages�3) Exception handling�4) Multithreading

OUTCOMES:

Create Java application programs using sound OOP practices e.g. Inheritance, interfaces and proper program structuring by using packages, access controlspecifiers

MODULE-I

MATRUSRI

ENGINEERING COLLEGE

5 of 19

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

MATRUSRI

ENGINEERING COLLEGE

6 of 19

MATRUSRI

ENGINEERING COLLEGE

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() {

System.out.println("This is funcA");

}

7 of 19

MATRUSRI

ENGINEERING COLLEGE

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 Simple.java

package mypack;

public class Simple{

public static void main(String args[]){

System.out.println("Welcome to package");

}

}

To Compile: javac -d . Simple.java

To Run: java mypack.Simple

8 of 19

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

MATRUSRI

ENGINEERING COLLEGE

9 of 19

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.

MATRUSRI

ENGINEERING COLLEGE

10 of 19

MATRUSRI

ENGINEERING COLLEGE

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) {

System.out.println("An exception was thrown");

throw e;

}

11 of 19

MATRUSRI

ENGINEERING COLLEGE

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.

12 of 19

MATRUSRI

ENGINEERING COLLEGE

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

13 of 19

MATRUSRI

ENGINEERING COLLEGE

THE MAIN THREAD, CREATING A THREAD, CREATING MULTIPLE THREADS

We create a class that extends the java.lang.Thread 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 java.lang.Runnable interface and override run() method. Then we instantiate a Thread object and call start() method on this object.

14 of 19

MATRUSRI

ENGINEERING COLLEGE

THREAD USING IS Alive() AND join()

MyThread t1=new MyThread();

MyThread t2=new MyThread();

t1.start();

 

try{

t1.join(); //Waiting for t1 to finish // join() method

}catch(InterruptedException ie){}

 

t2.start();

}

15 of 19

MATRUSRI

ENGINEERING COLLEGE

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 java.lang.Thread.getPriority() method returns the priority of the given thread.

public final void setPriority(int newPriority): The java.lang.Thread.setPriority() method updates or assign the priority of the thread to newPriority.

16 of 19

MATRUSRI

ENGINEERING COLLEGE

SYNCHRONIZATION

Synchronization in Java is the capability to control the access of multiple threads to any shared resource.Java 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

17 of 19

  • 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 executed.It is implemented by following methods of Object class:
  • wait()
  • notify()
  • notifyAll()

MATRUSRI

ENGINEERING COLLEGE

18 of 19

MATRUSRI

ENGINEERING COLLEGE

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) {

System.out.println("Thread 1: locked resource 1");

try { Thread.sleep(100);} catch (Exception e) {}

synchronized (resource2) {

System.out.println("Thread 1: locked resource 2");

} }}};

19 of 19

END OF UNIT - II

19