Interface:-: Why Use Java Interface?
Interface:-: Why Use Java Interface?
Interface:-: Why Use Java 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)
Syntax:
1. interface <interface_name>{
2.
3. // declare constant fields
4. // declare methods that abstract
5. // by default.
6. }
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.
In Java, an exception is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime.
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.
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
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.
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.
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.
If you have to perform different tasks at the occurrence of different Exceptions, use java
multi catch block.
Multithreading in Java;-
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.
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.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.
1. Process Synchronization
2. 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
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(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:
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor. Syntax:
wait() method releases the lock sleep() method doesn't release the lock.
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.
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.
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.
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.