Interface:-: Why Use Java Interface?

Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

interface :-

1.It has static constants and abstract methods. The interface in Java is a mechanism to
achieve abstraction. ... It is used to achieve abstraction and multiple inheritance in Java. In
other words, you can say that interfaces can have abstract methods and variables.

2. In other words, you can say that interfaces can have abstract methods and variables. It
cannot have a method body.

4.It cannot be instantiated just like the abstract class. (anonymous inner class)

Why use Java interface?


There are mainly three reasons to use interface. They are given below.

o It is used to achieve abstraction.


o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.

How to declare an interface?


An interface is declared by using the interface keyword. It provides total abstraction.

Syntax:
1. interface <interface_name>{
2.
3. // declare constant fields
4. // declare methods that abstract
5. // by default.
6. }

The relationship between classes and interfaces


As shown in the figure given below, a class extends another class, an interface extends
another interface, but a class implements an interface.
Java Interface Example
In this example, the Printable interface has only one method, and its implementation is
provided in the A6 class.

1. interface printable{
2. void print();
3. }
4. class A6 implements printable{
5. public void print(){System.out.println("Hello");}
6.
7. public static void main(String args[]){
8. A6 obj = new A6();
9. obj.print();
10. }
11. }

variable in interface:-
In Java , interface doesn't allow you to declare any instance variables. Using
avariable declared in an interface as an instance variable will return a compile time
error. You can declare a constant variable, using static final which is different from an
instance variable.

Can an interface can variable ?


Answer:- No.
Unit-7 exception handling

What is Exception in Java??

Dictionary Meaning: Exception is an abnormal condition.

In Java, an exception is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application that is why
we use exception handling. Let's take a scenario:

1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10

Suppose there are 10 statements in your program and there occurs an exception at
statement 5, the rest of the code will not be executed i.e. statement 6 to 10 will not be
executed. If we perform exception handling, the rest of the statement will be executed. That
is why we use exception handling in Java.

Types of Java Exceptions

There are mainly two types of exceptions: checked and unchecked. Here, an error is
considered as the unchecked exception. According to Oracle, there are three types of
exceptions:

1. Checked Exception.
2. Unchecked Exception.
3. Error.
Difference between Checked and Unchecked Exceptions:-

1) Checked Exception

The classes which directly inherit Throwable class except RuntimeException and Error are
known as checked exceptions e.g. IOException, SQLException etc. Checked exceptions are
checked at compile-time.

2) Unchecked Exception

The classes which inherit RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time, but they are checked at runtime.

3) Error

Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Java Exception Handling Example


Let's see an example of Java Exception Handling where we using a try-catch statement to
handle the exception.

1. public class JavaExceptionExample


2. {
3. public static void main(String args[])
4. {
5. Try
6. {
7. //code that may raise exception
8. int data=100/0;
9. }
10. catch(ArithmeticException e){System.out.println(e);}
System.out.println("rest of the code...");
11. }
12. }

Hierarchy of Java Exception classes:-


Diff. between throws and throw

1) The throw keyword is used to throw an The throws keyword is used to declare an exception.
exception explicitly.

2) The checked exceptions cannot be The checked exception can be propagated with throws
propagated with throw only.

3) The throw keyword is followed by an The throws keyword is followed by class.


instance.

4) The throw keyword is used within the The throws keyword is used with the method signature.
method.

5) You cannot throw multiple exceptions. You can declare multiple exceptions, e.g., public void
method()throws IOException, SQLException.

Try catch and finally block:-

Java try block:-

Syntax of java try-catch


1. try{
2. //code that may throw exception
3. }catch(Exception_class_Name ref){}

Syntax of try-finally block:-


1. try{
2. //code that may throw exception
3. }finally{}

Syntax:
1. ....
2. try
3. {
4. statement 1;
5. statement 2;
6. try
7. {
8. statement 1;
9. statement 2;
10. }
11. catch(Exception e)
12. {
13. }
14. }
15. catch(Exception e)
16. {
17. }
18. ....
4.

Java Multi catch block:-

If you have to perform different tasks at the occurrence of different Exceptions, use java
multi catch block.

Let's see a simple example of java multi-catch block.

1. public class TestMultipleCatchBlock{


2. public static void main(String args[]){
3. try{
4. int a[]=new int[5];
5. a[5]=30/0;
6. }
7. catch(ArithmeticException e){System.out.println("task1 is completed");}
8. catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
9. catch(Exception e){System.out.println("common task completed");}
10.
11. System.out.println("rest of the code...");
12. }
13. }

Java finally block:-


Java finally block is a block that is used to execute important code such as closing connection, stream
etc.

Java finally block is always executed whether exception is handled or not.

Java finally block follows try or catch block.


1. public class TestFinallyBlock2{
2. public static void main(String args[]){
3. try{
4. int data=25/0;
5. System.out.println(data);
6. }
7. catch(ArithmeticException e){System.out.println(e);}
8. finally{System.out.println("finally block is always executed");}
9. System.out.println("rest of the code...");
10. }
11. }
Unit -8 multithreading :

Multithreading in Java;-

Multithreading in java is a process of executing multiple threads simultaneously.

A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and


multithreading, both are used to achieve multitasking

Java Multithreading is mostly used in games, animation, etc.

Advantages of Java Multithreading


1) It doesn't block the user because threads are independent and you can perform
multiple operations at the same time.

2) You can perform many operations together, so it saves time.

3) Threads are independent, so it doesn't affect other threads if an exception occurs in a


single thread.
Life cycle of thread:-
A thread can be in one of the five states. According to sun, there is only 4 states in thread
life cycle in java new, runnable, non-runnable and terminated. There is no running state.

But for better understanding the threads, we are explaining it in the 5 states.

The life cycle of the thread in java is controlled by JVM. The java thread states are as
follows:

1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
1) New

The thread is in new state if you create an instance of Thread class but before the
invocation of start() method.

2) Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler
has not selected it to be the running thread.

3) Running:
The thread is in running state if the thread scheduler has selected it.
4).Timed Waiting : A thread lies in timed waiting state when it calls a method with a time out
parameter. A thread lies in this state until the timeout is completed or until a notification is received. For
example, when a thread calls sleep or a conditional wait, it is moved to timed waiting state.

5) Terminated
A thread is in terminated or dead state when its run() method exits.

Priority of a Thread (Thread Priority):

Each thread have a priority. Priorities are represented by a number between 1 and 10. In
most cases, thread schedular 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.

3 constants defined in Thread class:


1.public static int MIN_PRIORITY: This is minimum priority that a thread can
have. Value for this is 1.

2.public static int NORM_PRIORITY: This is default priority of a thread if do not


explicitly define it. Value for this is 5.

3.public static int MAX_PRIORITY: This is maximum priority of a thread. Value for
this is 10.
Get and Set Thread Priority:-
1. public final int getPriority(): java.lang.Thread.getPriority() method returns
priority of given thread.
2. public final void setPriority(int newPriority): java.lang.Thread.setPriority()
method changes the priority of thread to the value newPriority. This method
throws IllegalArgumentException if value of parameter newPriority goes
beyond minimum(1) and maximum(10) limit.
Synchronization in Java
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.

Why use Synchronization


The synchronization is mainly used to

1. To prevent thread interference.


2. To prevent consistency problem.
Types of Synchronization
There are two types of synchronization

1. Process Synchronization
2. Thread Synchronization

Here, we will discuss only thread synchronization.

Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread
communication.

1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. static synchronization.
2. Cooperation (Inter-thread communication in java)

Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing data.
This can be done by three ways in java:

1. by synchronized method
2. by synchronized block
3. by static synchronization

inter-thread communication in Java


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:

o wait()
o notify()
o notifyAll()

1) wait() method

Causes current thread to release the lock and wait until either another thread invokes the
notify() method or the notifyAll() method for this object, or a specified amount of time has
elapsed.

The current thread must own this object's monitor, so it must be called from the
synchronized method only otherwise it will throw exception.

Method Description

public final void wait()throws InterruptedException waits until object is notified.

public final void wait(long timeout)throws waits for the specified amount of time.
InterruptedException

2) notify() method

Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting
on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at
the discretion of the implementation. Syntax:

public final void notify()

3) notifyAll() method

Wakes up all threads that are waiting on this object's monitor. Syntax:

public final void notifyAll()


Understanding the process of inter-thread communication

The point to point explanation of the above diagram is as follows:

1. Threads enter to acquire lock.


2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait() method on the object. Otherwise it
releases the lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the notified state (runnable
state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and exits the monitor state of
the object.

Why wait(), notify() and notifyAll() methods are defined in Object


class not Thread class?
It is because they are related to lock and object has a lock.

Difference between wait and sleep?


Let's see the important differences between wait and sleep methods.
wait() sleep()

wait() method releases the lock sleep() method doesn't release the lock.

is the method of Object class is the method of Thread class

is the non-static method is the static method

is the non-static method is the static method

should be notified by notify() or after the specified amount of time, sleep is completed.
notifyAll() methods

ThreadGroup in Java
Java provides a convenient way to group multiple threads in a single object. In such way, we can
suspend, resume or interrupt group of threads by a single method call.

Java thread group is implemented by java.lang.ThreadGroup class.

A ThreadGroup represents a set of threads. A thread group can also include the other thread
group. The thread group creates a tree in which every thread group except the initial thread group
has a parent.

A thread is allowed to access information about its own thread group, but it cannot access the
information about its thread group's parent thread group or any other thread groups.

Daemon Thread in Java


Daemon thread in java is a service provider thread that provides services to the user
thread. Its life depend on the mercy of user threads i.e. when all the user threads dies, JVM
terminates this thread automatically.

There are many java daemon threads running automatically e.g. gc, finalizer etc.

You can see all the detail by typing the jconsole in the command prompt. The jconsole tool
provides information about the loaded classes, memory usage, running threads etc.
Points to remember for Daemon Thread in Java
o It provides services to user threads for background supporting tasks. It has no role
in life than to serve user threads.
o Its life depends on user threads.
o It is a low priority thread.

Why JVM terminates the daemon thread if there is no user


thread?
The sole purpose of the daemon thread is that it provides services to user thread for
background supporting task. If there is no user thread, why should JVM keep running this
thread. That is why JVM terminates the daemon thread if there is no user thread.

Methods for Java Daemon thread by Thread class


The java.lang.Thread class provides two methods for java daemon thread.

No. Method Description

1) public void is used to mark the current thread as daemon thread


setDaemon(boolean status)
or user thread.

2) public boolean isDaemon() is used to check that current is daemon.

Enumeration
Enumerations was added to Java language in JDK5.Enumeration means a list of named
constant. InJava, enumeration defines a class type. AnEnumeration can have constructors,
methods and instance variables.

You might also like