Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Friday 25 October 2019

Deadlock | what is deadlock |deadlock in java - Online Help

Let's discuss the important topic of java multithreading is a deadlock

Now, what is deadlock?  A deadlock is a special type of error that you need to avoid( that relates specifically to multitasking), which occurs when two threads have a circular dependency on a pair of synchronized objects.

For Example,

suppose one thread enters object X  and another thread enters the object Y. If the thread in X tries to call any synchronized method on Y, It will be blocked. however, if the thread in Y, in turn, tries to call any synchronized method on X, the thread waits forever, because to access X it would have to release its own lock on Y so that the first thread could complete.

Deadlock | what is deadlock |deadlock in java - Online Help
Read: What is thread and life cycle of a thread


It may involve more than two threads and two synchronized objects.

Deadlock situations can arise that involve more than two threads. Assume that thread1 wait for a lock held by thread2.Thread2 waits for a lock held by thread3. Thread3 waits for a lock held by thread1.

Sample program for deadLock is:

class x
{
y b;
synchronized void x1()
{
System.out.println("starting x1");
b.y2();
}
synchronized void x2()
{
System.out.println("starting x2");
}
}
class y
{
x a;
synchronized void y1()
{
system.out.println("starting y1");
a.x2();
}
synchronized void y2()
{
System.out.println("starting y2");
}
}
class threadX entends Thread
{
x a;
ThreadX(x a)
{
this.a=a;
}
public void run()
{
for(int i=0;i<100000;i++);
a.x1();
}
}
class threadY entends Thread
{
y b;
ThreadY(y b)
{
this.b=b;
}
public void run()
{
for(int i=0;i<10000;i++);
b.y1();
}
}
class deadlockdemo
{
public static void main(String args[])
{
x a=new x();
y b=new y();
a.b=b;
b.a=a;
ThreadX t1=new ThreadX(a);
ThreadY t2=new ThreadY(b);
t1.start();
t2.start();
try
{
t1.join();
t2.join();
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println("successfully");
}
}

Read: interthread communication in java

Explanation:

In the following program class x has two synchronized methods named x1() andx2(). The x1() method calls the y2() method of that object. similarly, class y has two synchronized methods named y1() and y2(). The y1() methods call the x2()method of that object.

Class ThreadX extends and executes a loop that invokes the x1() method of the x object class. Class ThreadY extends and executes a loop that invokes the y1() method of the y object class.

I hope you understand what is a deadlock? if you have any queries or you find something wrong or have more information then please do comment.

Saturday 28 September 2019

interthread communication in java - Online Help

Interthread communication:

let's discuss the important topic of Java multithreading is interthread communication in java.

Inter thread communication is used to allow synchronized threads to communicate with each other. Before we discuss inter-thread communication in java, we should know how and why this concept is included in java?

Multithreading replaces event loop programming by dividing your tasks into discrete and logical units. Thread also provides a secondary benefit: they avoid polling. Polling is usually implemented by a loop that is used to check some condition repeatedly. Once the condition is true, the appropriate action is taken. This waste CPU time.

For example,
Consider the queuing problem when one thread is proceeding some data and another is consuming it. The proceeding thread has to wait until the consuming thread is finished before it generates more data.

Also read: Thread in java



In a polling system, the consuming thread would waste many CPU cycles while it waited for the preceding thread to produce. if the proceeding thread is generated more data until then consuming thread has to wait. clearly this situation is undesirable.

To avoid polling, Java includes an elegant inter-process communication mechanism via wait(), notify(), and notifyAll() method. These methods are implemented as a final method in an object so that all classes have them. All three methods can be called only from within a synchronized method.

wait(): 

Tell the calling thread to give up the monitor and go to sleep until some other enters the same monitor and calls notify (). The general format is:
                           
                               final void wait()throws InterruptedException

notify(): 

Wakes up the first thread that called wait() on the same object. The general format is:
                                           
                                             void notify()

notifyAll(): 

Wakes up all the thread that called wait() on the same object. The highest priority will run first.
                                        
                                                void notifyAll()

Sample program for interthread communication in java:

class q
{
int n;
boolean valueset=false;
synchronized int get()
{
if(!valueset)
{
try{
wait();
}
catch(InterruptedException e)
{
System.out.println(“Interrupted exception caught”);
}
}
System.out.println(“got:”+n);
valueset=false;
notify();
return n;
}
}
synchronized void put()
{
if(valueset)
{
try{
wait();
}
catch(InterruptedException e)
{
System.out.println(“Interrupted exception caught”);
}
this.n=n;
valueset=true;
System.out.println(“put:”+n);
notify();
}
}
class Producer implements Runnable
{
Q q;
Producer(Q p)
{
this.q=q;
new Thread(this,”Producer”).start();
}
public void run()
{
int i=0;
while(true)
{
q.put(i++);
}
}
}
class Consumer implements Runnable
{
Q q ;
Consumer(Q q)
{
this.q=q;
new Thread(this,”consumer”).start();
}
public void run()
{
while(true)
{
q.get();
}
}
}
class PCFixed
{
public static void main(String arg[])
{
Q q=new Q();
new Producer(q);
new Consumer(q);
System.out.prinln(“press control - C to stop”);
}
}




Inside get(),wait() is called. This causes its execution to suspend until the producer notifies you that some data is ready. When this happens, execution inside get() resumes. After the data has been obtained, get() calls notify(). This tells the producer that it is ok to put more data in the queue.




 Inside put(), wait() suspends execution until the consumer has removed the item from the queue. when execution resumes, the next item of data is put in the queue, and notify() is called. This tells the consumer that it should now remove it.

Here is some output from this program:
put:1
got:1
put:2
got:2
put:3
got:3
put:4
got:4
put:5
got:5



Wednesday 25 September 2019

Java synchronization | what is java synchronization - online Help

Java synchronization:

Let's discuss what is java synchronization?

As we know, Java is a multithreaded program. so multiple threads can access the same data at a time. When multiple threads are accessing the single object. Then, there will be a data inconsistency. 

For example, 

Consider two people who have a joint account and the account balance is only 500 rupees. Both of them are accessing the account at the one time. One person wants to withdraw 200 rupees and another person wants to withdraw 400 rupees. 

Now the first person withdraws 200 rupees and the balance amount is only 300 rupees. The balance amount is not updated in the account.

Simultaneously the second person withdraws 400 rupees. Then the balance amount is 100 rupees, which is inconsistent and not correct.

To reduce this data inconsistency, we use thread synchronization. 

For example,

If we allow only one person to access the account at a time, the first person goes and withdraw 200 and the account will update the balance amount as 300 rupees.

Also read: Thread in java



Now if the second person accesses the account (try to withdraw 400 rupees) then it will show insufficient balance. because the balance amount is only 300 rupees.

Whenever multiple threads are trying to execute on a single object, we allow only one thread to be executed at a time is called Thread synchronization.



A thread can be synchronized by using the synchronized keyword as a modifier, applicable only for the method and blocks.

Synchronization cannot apply for the classes and variables.

When a thread begins executing a synchronized instance method, it automatically acquires a lock on those objects. The lock is automatically relinquished when the method completes.

General format for thread synchronization:

The general format is to synchronize access to common data is as follows:

synchronized(object)
{
// statement block
}

here,
the object is the name of the locking object

Sample program for Java Synchronization:

The following program illustrates the usage of synchronization. There are three threads each of which prints the string is shown below through a synchronized method,
good morning
good afternoon
good evening


When the thread is synchronized, the output should be:
good morning
good afternoon
good evening
good morning
good afternoon
good evening
good morning
good afternoon
good evening

When the threads are not synchronized, the output should be:
good morning
good morning
good morning
good afternoon
good afternoon
good afternoon
good evening
good evening
good evening

class ThreadX extends Thread
{
Thread s;
public void call(thread name)throws Exception
{
s=name;
s.start();
}
public void run()
{
try
{
caller(s);
}
catch(Exception obj)
{
}
}
synchronized void caller(Thread r) throws Exception
{
System.out.println("good morning");
System.out.println("good afternoon");
r.sleep(2000);
System.out.println("good evening");
}
}
class syndemo
{
public static void main(String args[])throws Exception
{
ThreadX one=new ThreadX();
Thread x=new Thread(one);
Thread y=new Thread(one);
Thread z=new Thread(one);
one.call(x);
one.call(y);
one.call(z);
}
}





Thursday 29 August 2019

Multithreading in java | Creating multiple threads in java - Online Help

Multithreading in Java:

Let's discuss what is multithreading in java?

Java provides built-in support for the multi-threaded program. A multi-threaded 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 the specialized form of multitasking.

Multithreading enables you to write very efficient programs that make maximum use of the CPU because idle time can be kept to a minimum. This is especially important for the interactive, networked environment in which Java operates because idle time is common.

A program can be divided into a number of small processes. Each small process can be addressed as a single thread(lightweight process). A multithreaded program contains two or more threads that can run concurrently. This means that a single program can perform two or more tasks simultaneously. For example, one thread is writing content on a file at the same time another thread is performing a spelling check.

To create a new thread, your program with either extends Thread or implement the Runnable interface. To know, how to create a thread and what are the ways are available to create a thread and what is the life cycle of the thread, then read this below article:

Creating a thread in java 



Advantages of multithreading: 

  •  multithreading reduces computation time. because it runs more than one thread at a time.
  •  It improves the performance of an application.
  •  Threads distribute the same address space it saves the memory space.
  •  Context switching between threads is usually less costly than between processes.
  •  The cost of communication between Threads is comparatively low.


Creating multiple threads in java:

so far we have seen using only two threads: the main thread and the one-child thread. however, your program can spawn as many threads as its needs. For example, the following program creates three child threads. The main thread starts the work of all of its child thread, context switching will be done between the threads.


//Create multiple threads
Class NewThread implements Runnable
{
String name;
Thread t;
NewThread(String threadname)
{
name=threadname;
t=new Thread(this,name);
System.out.println(“new thread:”+t);
 t.start();          //start the thread
}

//This is the entry point of the thread
public void run()
{
try
{
for(int i=5;i>0;i++)
{
System.out.println(name+”:”+i);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println(name+”existing”);
}
}
Class multithreaddemo
{
Public static void main(String agrs[])
{
newThread(“one”);//start thread
new NewThread(“two”);
new NewThread(“three”);
try
{
// wait for the other thread to end
Thread.sleep(10000);
}
catch(interruptedException e)
{
System.out.println(“main thread interrupted”);
}
System.out.println(“main thread existing”);
}
}

ALSO READ:
Exception handling in java



The Output from this program is shown here:

new thread: thread[ one,5, main]
new thread: thread[ two,5, main]
new thread: thread[ three,5, main]
one:5
two:5
three:5
one:4
two:4
Three:4
one:3
two:3
Three:3
one:2
two:2
Three:2
one:1
two:1
three:1
one existing
two existing
three existing
main thread existing

Major concept of java multithreading:

while working with the java multithreading program, you should know about the following factor:
  • synchronization of thread.
  • how to handle inter-thread communication.
  • what is a deadlock and how to handle it?

Wednesday 21 August 2019

Thread in java | java thread Tutorial | Creating a thread in java - Online Help

Thread in java:

Java's multithreading system is built upon the thread class, its method and its companion interface Runnable. Thread is a sequential flow of control. A thread is a sequence of execution within a program. Since you can't directly refer to the real state of a running thread, you will deal with it through its proxy.

To create a new thread, your program with either extends Thread or implement the Runnable interface.

The thread class defines several methods that help manage threads. The following table lists the various thread methods:

                               Methods
                               Meaning
start()
Starts a thread by calling its run method.
run()
The entry point of a thread i.e. defines while the thread is running
sleep()
Suspends a thread for a period of time.
join()
Waits for a thread to terminate.
isAlive()
Determines if a thread still running.
getName()
Gets the name of the thread.
getPriority()
Returns the priority of a thread.
Yield()
Current thread to yield control of the process to the thread.

Main thread:

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 thread will be swapped
  • It must be the last thread to finish execution. When the main thread stops, your program terminates.

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

    This method returns a reference to the thread in which it is called. Once you have a reference to the main thread, you can control its just like any other thread.

Sample program:
//controlling the main thread.

class currentlythreaddemo
public static void main(String args[])
{
Thread t=Thread.currentThread();
System.out.println("current thread:"+t);

//change the name of the thread

t.setNmae("my thread");
System.out.println("After name change:"+t);
try
{
for(int n=5;n>0;n--)
{
System.out.println(n);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("main thread interrupted");
}
}
}

Output:
current thread:Thread(main,5,main)
After name change: Thread(my thread,5, main)
5
4
3
2
1

Also Read:
Separator in java



Creating a thread in java:

The thread class in the java.lang package allows to create and manages thread. In the most general sense, you create a thread by instantiating an object of the type Thread.Java defines two ways to creating the thread.
  • you can extend a thread class.
  • you can implement the runnable interface.


Implementing Runnable:

The easiest way to create a thread is to create a class that implements the runnable interface. Runnable interface abstract a unit of executable code. You can construct a thread on any object that implements runnable. To implement runnable, a class needs to implement a single method called run(), which declared like this:

public void run();

    inside run() you will define the code for the new thread. It is important to understand that the run() method can call other methods, classes and declared a variable just like the main thread. The only difference is that the run() method establishes the entry point for another concurrent thread of execution within your program. This thread will end when run() returns.

    After you create a class that implements Runnable, you will instantiate an object of type Thread from within the class. Thread defines several constructors. The one that we will use is:

Thread(Runnable threadobj, String threadname)

    In this constructor,threadobj is an instance of a class that implements the runnable interface. This defines where the execution of the thread will begin. The name of the new thread is specified in the threadname.

    After the new thread is created, it will not start running until you call its start() method, which is declared within the thread class.The start() method is used to call run().

Sample program to implement Runnable interface:

class ThreadX implements Runnable
{
public void run()
{
for(int i=1;i<=4;i++)
{
System.out.println("ThreadX:"+i);
}
}
}
class runnabledemo
{
public static void main(String args[])
{
ThreadX imprunnable=new ThreadX();
Thread ThreadY=new Thread(imprunnable);
Thread.start();
}
}

The output is:
ThreadX:1
ThreadX:2
ThreadX:3
ThreadX:4


Extending the class thread:

Extending the class is nothing but a class that defines the extended thread class and overrides it's run() method in the subclass. Each thread is a separate instance of the class.

Sample program to create a thread by extending the class thread:
class ThreadX extends Thread
{
public void run()
{
for(int i=1;i<=3;i++)
{
System.out.println("thread1:"+i)
}
System.out.println("exit from thread1");
}
}
class ThreadY extends Thread
{
public void run()
{
for(int j=1;j<=3;j++)
{
System.out.println("thread2:"+i)
}
System.out.println("exit from thread2");
}
}
class ThreadDemo
{
public static void main(String args[])
{
new ThreadX().start();
new ThreadY().start();
}
}

The output is:

thread1:1
thread1:2
thread2:1
thread2:2
thread2:3
exit from thread2
thread1:3
exit from thread1

The life cycle of a Thread:

A thread moves through several states from its creation to its termination. The life cycles of a thread consist of five states. They are:
-newborn state
-Runnable state
-Running state
-blocked state
-Dead state

The following figure shorts the five states of a thread life cycle:

NewBorn state:

A Thread is said to be the newborn state when we create an object of the Thread class.

Runnable state:

The thread is ready for the execution and waits for the processor to be available. All the thread in an execution queue has equal priority. The thread comes to this state when is start() method is called.

Running state:

The thread comes to this state when it starts its execution. A thread enters this stage whenever it's run() method is called.

Blocked state:

A thread comes to this state when it is made to stop its execution. The thread comes to this state when its stop() or wait() method is called.

Dead state:

A thread comes to this state when it completes its execution.

Also Read:
interface in java



Monday 15 July 2019

Exception handling in java | java Exception - Online Help

Exceptions are generated when we recognized an error condition during the execution of a program. Java includes a system for running exceptions by tracking the potential for each method to throw a specific exception.

Exception handling fundamental(Introduction):

An exception is an event, which occurs during the execution of a program, that an interrupt the normal flow of a program's instruction. In other words, the exception is generated when a recognized condition usually an error condition arises during the execution of a method.Java includes a method for running the exceptions, by tracking the method to throw a specific exception.

For each method that could throw an exception, your code must report the java compiler that it could throw that exact exception. The compiler marks that method as potentially throwing that exception, and then need a code calling the method to handle the possible exception.

Exception Handling Mechanism:

Exception handling in java refers to the java's handling of the run time errors. An exception is an object that is generated at the runtime to describe a problem encountered during the execution of a program.

Java exception handling is managed via five keywords: try, catch, throw, throws, and finally. The general form of exception handling is :

try
{
//  block of code monitor an error
}
catch(exception type1 exceotionobj)
{
//  exception handler for exception type1
}
catch(exception type2 exceotionobj)
{
//  exception handler for exception type2
}
//...................
finally
{
//  block of code to be executed before try block ends.
}

Briefly, here is how they work program statement that you want to monitor for exception contained within the try block. If an exception occurs within the try block, it is thrown and will be catched the exception in the catch block and handle it in some rational manner. System-generated exceptions are automatically thrown by the Java run-time system.

To manually throw an exception, use the keyword throw. Any exception that is thrown out of the method must be specified as such by a throws clause. Any code that must be executed before a method return is put in a finally block. This is called an "Exception handling mechanism".

Classification of exception handling:

Java has a number of built-in classes for handling the exceptions. The class throwable is at the top of the exception class hierarchy. Throwable class is two subclasses that partition exception into two types. One exception and other is an error.

Error:

Error is an exception that is not expected to be catch under normal circumstances by your program. It is used by the run time system to indicate error having to do with the run-time environment, itself. Stack overflow is an example of error. There are basically three types of errors in the java program:

Compile-time error: error which occurs due to syntax or format is called compile-time error. These errors are detected by java compiler at compilation time.

Runtime error: These are an error that computers inefficiency. Insufficient memory to store data or inability of the microprocessor to execute some statement is examples of runtime errors. Runtime errors are detected by JVM at runtime.

Logical error: These are the errors that occur due to the bad logic in the program. These errors are rectified by comparing the output of the program manually.

ALSO READ: packages in java

Built-in Exception:

Java has several built-in Exception. The most commonly used exceptions are as follow:

Exception class
Description
ArithmeticException
Arithmetic error, such as division-by-zero.
ArrayIndexOutOfBoundException
The array index is out of bounds, or wrong index value.
ArrayStoreException
Assignment of an array element of an incompatible type (wrong type of data in an array).
IllegalArgumentException
The illegal argument used to invoke a method.
IllegalStateException
Environment or application is in an incorrect state.
IndexOutOfBoundException
Some types of the index are out of bounds.
NullPointerException
Invalid use of a null reference.
NumberFormatException
A number is in an illegal format.
StringIndexOutOfBoundException
A string index is out of bound.
ClassNotFoundException
A class can not be found.
IllegalAccessException
Access to a class is defined.
NoSuchFieldException
A request field does not exist.
NoSuchMethodException
A request method does not exist.
InterruptException
A thread has been interrupted.


Using try and catch:

In order to handle the exception, simply enclose the code that you want to monitor inside a try block. Immediately following the try block, include a catch clause that specifies the exception type that you wish to catch. The try statement contains a block of the statement. A try block can be written and if a problem occurs during its execution, control proceeds to the appropriate catch block.

Note: The catch block is skipped if no exception is raised in the try block.

Simplest form of the catching an exception is as follows:

try
{
//statement for monitoring the errors
}
catch(exception excepobject)
{
//exception-handling
}

Sample program:

class excepdemo
{
public static void main(String args[])
{
int a=10,b=0,x;
try
{
x=a/b;
}
catch(ArithmeticException e)
{
System.out.println("division-by-zero);
}
}



Multiple catch clauses:

In some clause, 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 clause, catch catching the 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 other is bye passed and execution continues after the try/catch block. The general form is :

try
{
//statement for monitoring the errors
}
catch(Exceptiontype1 excepobj)
{
//
}
catch(Exceptiontype2 excepobj)
{
//
}

Sample program:

class mulcat
{
public static void main(String args[])
{
int a[]={2,8};
int b=4;
try
{
int x=a[2]/b-a[1];
}
catch(ArithmeticException e)
{
System.out.println("division by zero");
}
catch(ArrayIndexOutofBoundException e)
{
System.out.println("invalid index");
}
catch(ArrayStoreException e) 
{
System.out.println("wrong datatype");
}
}
}

Nested try Statement:

The try can be nested. That is, a try statement can be inside the block of another try. Each time a try statement is entered, the context of that exception is pushed on the stack. If an inner try statement does not have a catch handler for a particular exception, the stack is unwound and the next try statement's catch handlers are inspected for a match. This continues until one of the catch statement succeeds or until all of the nested try statement are exhausted. If no catch statement matches, then the java run-time system will handle the exception.



Throw Clause:

The throw statement is used to explicitly throw an exception .i.e; if any error occurred in the try block then it throws the exception to the catch block. The general form of the throw is as follow:

throw throwableinstance;

here,throwableinstance must be an object of the 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 an exception. There are two ways you can obtain a throwable object: using a parameter into a catch clause or creating one with the new operator.

The flow of execution stops immediately after the throw statement; any subsequent statement is not executed. The nearest enclosing try block is inspected to see if it has a catch statement that matches the type of exception. If it does find a  match, control is transferred to that statement. If no matching catch is found, Then the default exception handler halts the program and print the stack trace.

Sample program:

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);
}
}
}

Throws Clause:

The throws clause is used to list the type of exceptions that are thrown by the method. This is necessary for all the exceptions, except those of type error or run time exception and any of their subclasses. We can include throws clause in the method declaration. The general format of throws is as follows:

return-type methodname(parameter_list) throws exception list
{
//body of the method
}

Sample program:

class throwsdemo
{
static void throw1() throws IllegalAccessException
{
System.out.println("Inside throw1")'
throw new IllegalAccessException("demo");}
public static void main(String args[])
{
try
{
throw1();
}
catch(IllegalAccessException e)
{
System.out.println("caught:"+e);
}
}
}


Also Read: Font class in java

Finally clause:

Finally block creates a statement that will be executed after a try or catch block has been computed. The finally block will execute whether or not an exception is thrown. The finally clause is optional. 
The general form is:

finally
{
//statement to be executed before any try block ends
}

Sample program:

class finally
{
public static void main(String arg[])
{
int a[]={2,8};
int b=4;
try
{
int x=a[2]/b-a[1];
}
catch(ArithmeticException e)
{
System.out.println("division-by-zero");
}
catch(ArrayIndexOutOfBoundException e)
{
System.out.println("invalid array index");
}
finally
{
int y=a[1]/a[0];
System.out.println("y="+y);


}
}
}

Tuesday 9 July 2019

interface in java - online help

An interface in Java:

An interface is a group of constants and methods declaration that defines the form of class. An interface is a collection methods declaration which can be implemented by the classes.

 An interface is similar to class.Java uses interfaces to multiple inheritance.java does not support multiple inheritances, but interface serves to implement multiple inheritances.

 All the methods of an interface are automatically public. It is not necessary to supply the keyword "public" when declaring a method in an interface. Once it's defined, any number of classes can implement any number of the interface.

Rules for naming the interface:

-Methods inside the interface must not be static, final, native.

-All variable declared inside the interface is implicitly public static final variables(constants).

-All methods declared inside the Java interface are implicitly public and abstract, even if you don't use public and abstract keyword.

-The interface can extend one or more other interfaces.

-The interface cannot implement a class.

-The interface can be nested inside another interface.

Defining an interface:

Defining an interface is similar to the class. An interface is created in the same way as a class. To create an interface, we use a keyword interface. An interface can extend any number of interfaces. The general form to create interface is,

interface name
{
datatype varname1=value1;
datatype varname2=value2;
datatype varname3=value3;
-------------------
-------------------
-------------------
datatype varnameN=valueN;
return-type methodname1(parameter-list);
return-type methodname2(parameter-list);
return-type methodname3(parameter-list);
--------------------
--------------------
--------------------
return-type methodnameN(parameter list);
}

the interface is the java keyword, the name is the name of the interface and can be any valid identifier. Notice that the method which has nobody is ended with the semicolon after the parameter list. Methods without parameters are an abstract method, there is no default implementation of methods specified within an interface. Each class that includes an interface must implement all of the methods.


The variable can be declared inside of interface declaration. They are implicitly final and static, they cannot be changed by the implementing class. They must also be initialized with a constant value. All methods and variables are implicitly public if the interface, itself, is declared as public.

We can combine the declaration of several variables onto one line as follow:
datatype varname1=value1...............varnameN=valueN;

Here, is an example of an interface definition. It declares a simple interface which contains one method called callback() that takes an integer parameter.
interface callback
{
void callback(int p);
}

Extending Interface:

An interface can be interfaced from another interface, using the keyword extends. The general format of extending interface as follows:
interface subclass extends baseclass
{
//variable declaration;
//method declaration;
}

Here interface and extends are java keyword.subclass is a new class and baseclass is an existing class.

Implementing interface:

Once an interface has been defined, one or more classes can implement that interface. To implement an interface, include the implement keyword in the class definition, and then create the method defined by the interface. The general form of a class is

class classname extends supperclass implements interface,[interface...........]]
{
//class body
}

classname is the name of the class. If the class implements more than one interface, the interface is separated with a comma. If a class implements two interfaces that declare the same method, then the same method will be used by both of the interfaces. The methods that implement an interface must be declared public. Also, the data type of the implementing method must match exactly the data type specified in the interface definition.

class salary
{
void show_salary()
{
System.out.println("salary:100000");
}
}
interface commission
{
void show_comm();
}
class income extends salary implements commission
{
public void show_comm()
{
System.out.println("commission:1000");
}
void show_income()
{
System.out.println("Total income includes");
show_salary();
show_comm();
}
public static void main(String args[])
{
income in=new income();
in.show_income();
}
}

So, the output is
salary:100000
commission:1000

Accessing implementation through interface reference:

The interface can be accessed by a variable as an object reference. Any instance of any class that implements the interface can be stored in this variable. This is the key feature of the interface. The method to be executed at the run time, allowing classes to be created later than the code which calls a method on them. The calling code can dispatch through an interface without having to know anything about the callee. The following example calls the show_income() method via an interface variable:
class totalsalary{
public static void main(String args[])
{
commission c=new income();
c.show_income();
}



Partial implementation of the interface:

If a class includes an interface but does not fully implement the method defined by that interface, then that class must be declared as abstract. For example,
abstract class incomplete implements callback
{
int a,b;
void show()
{
System.out.println(a+""+b)
}
//...............................
}
here, the class incomplete does not implement the methods callback() because it is declared as abstract.

Variables in the interface:

you can use interface to import the shared constants into multiple classes by simply declaring an interface that contains variable which is initialized to the desired value. when you include that interface in a class that is when you "implement" the interface, all of those variable names will be in scoop as constants. If an interface contains no method, The any class that includes such an interface does not actually implement anything. It is as if that class was importing the constant variable into the class namespace as the final variable.

import java.util.*;
interface sharedconstants
{
int no=0;
int yes=1;
int maybe=2;
int later=3;
int soon=4;
int never=5;
}
class question implements sharedconstant{
Random r=new Random();
int ask()
{
int p=int(100*r.nextDouble());
if(p<30)
return no;
else if(p<60)
return yes;
else if(p<75)
return later;
else if(p<98)
return soon;
else
return never;
}
}
class askme implements sharedconstant
{
static void answer(int result)
{
switch(result)
{
case no:
System.out.println("no");
break;
case yes:
System.out.println("yes");
break;
case maybe:
System.out.println("maybe");
break;
case later:
System.out.println("later");
break;
case soon:
System.out.println("soon");
break;
case never:
System.out.println("never");
break;
}
}
public static void main(String args[])
{
question q=new question();
answer(q.ask());
answer(q.ask());
answer(q.ask());
answer(q.ask());
}
}

Notice that this program makes use of one of java standard classes: Random. This class provides psuedorandom numbers. It contains several methods which allow you to obtain random numbers in the form required by your program.In this example ,the method nextDouble()is used.It returns random numbers in the range of 0.0 to 1.0.

In this sample program, the two classes, question, and askme, both implement the shared constants interface where no, yes, maybe, soon, later and neverare defined and inherited from them directly. Here is the sample output when you run this program note that the result is different each time it is run.

later

soon

no

yes



Interface inheritance:

one interface can inherit another by using the keyword extends. The syntax is the same as for inheriting classes. when a class implements an interface that inherits another interface, it must provide an implementation for all methods defined within the interface inheritance chain. The following is an example,

interface A
{
void math1();
void math2();
}

interface B extends A
{
void math3();
}
class myclass implements B
{
public void math1()
{
Syustem.out.println("implements math1()");
}
public void math2()
{
Syustem.out.println("implements math2()");
}
public void math3()
{
Syustem.out.println("implements math3()");
}
}
class iterfaceinheritance
{
public static void main(Strin args[])
{
myclass m=new myclass();
m.math1();
m.math2();
m.math3();
}
}

Difference between Classes and interface:

Classes

Interfaces

Classes have an instance as variables and methods with body.

Interfaces have instances as abstract methods and final constants variable.
Inheritance goes with extends keyword.

Inheritance goes with implements keywords.
The variable can have any access specifier.

The variable should be public, static, final.
Multiple inheritances are not possible.

It is possible
Classes are keyword by putting the keyword class prior to the classname.

The interface is created by putting the keyword interface prior to the interface-name
Classes contain any type of methods. Classes may or may not provide the abstraction.
The interface contains mostly abstract methods. Interfaces are exhibited fully abstraction.














Difference between  Abstract class and interface:

Abstract class

Interface

An abstract class is a class which contains one or more abstract methods, which has to be implemented by its subclasses.
The interface is the java object containing method declaration but no implementation. The classes which implement the interfaces must provide the method definition for all the methods.

An abstract class is a class prefix with an abstract keyword followed by class definition.
The interface is a pure abstract class which starts with the interface keyword.

An abstract class can also contain concrete methods.
Whereas, the interface contains all the abstract methods and final variable declaration

Abstract classes are useful in a situation that some general methods should be implemented and specialization behavior should be implemented by the child class.

Interfaces are useful in a situation that all properties should be implemented.