dineshonjava

Daemon Thread

In Java, any thread can be a Daemon thread. Daemon threads are like a service providers for other threads or objects running in the same process as the daemon thread. Daemon threads are used for background supporting tasks and are only needed while normal threads are executing.

In java we have two types of Threads: Daemon Thread and User Threads. Generally all threads created by programmer are user thread (unless you specify it to be daemon or your parent thread is a daemon thread). It provides services to the user thread. Its life depends on the user threads i.e. when all the user threads dies, JVM terminates this thread automatically.

Points to remember for Daemon Thread:
It provides services to user threads for background supporting tasks. It has no role in life than to serve user threads.
  • Its life depends on user threads.
  • It is a low priority thread.
  • User thread is generally meant to run our program code. JVM doesn’t terminate unless all the user thread terminate.
On the other hand we have Daemon threads. Typically these threads are service provider threads. They should not be used to run your program code but some system code. These threads run parallel to your code but survive on the mercy of the JVM. When JVM finds no user threads it stops and all daemon thread terminate instantly. Thus one should never rely on daemon code to perform any program code.

For better understanding consider a well known example of Daemon thread: Java Garbage collector. Garbage collector runs as a daemon thread to reclaim any unused memory. When all user threads terminates, JVM may stop and garbage collector also terminates instantly.

Why JVM terminates the daemon thread if there is no user thread remaining?
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 Daemon thread:
The java.lang.Thread class provides two methods related to daemon thread
  1. public void setDaemon(boolean status): is used to mark the current thread as daemon thread or user thread.
  2. public boolean isDaemon(): is used to check that current is daemon.
Example of Daemon thread:
class DeamonThread extends Thread{
   public void run(){
      System.out.println("Name: "+Thread.currentThread().getName());
      System.out.println("Daemon: "+Thread.currentThread().isDaemon());
   }

  public static void main(String[] args){
     DeamonThread t1 = new DeamonThread();
     DeamonThread t2 = new DeamonThread();
     t1.setName("Dinesh on Java");     
     t1.setDaemon(true);
  
     t1.start();
     t2.start();
 }
}
output:
Daemon Thread

Note: If you want to make a user thread as Daemon, it must not be started otherwise it will throw IllegalThreadStateException.
class DeamonThread extends Thread{
   public void run(){
      System.out.println("Name: "+Thread.currentThread().getName());
      System.out.println("Daemon: "+Thread.currentThread().isDaemon());
   }

  public static void main(String[] args){
     DeamonThread t1 = new DeamonThread();
     DeamonThread t2 = new DeamonThread();
     t1.setName("Dinesh on Java");
     t1.start();     
     t1.setDaemon(true);
  
     t2.start();
 }
}

Output:
Daemon

What is difference between User and Daemon Thread in Java?
Java makes a distinction between a user thread and another type of thread known as a daemon thread. The daemon threads are typically used to perform services for user threads. The main() method of the application thread is a user thread. Threads created by a user thread are user thread. JVM doesn't terminates unless all the user thread terminate.

You can explicitly specify a thread created by a user thread to be a daemon thread by calling setDaemon(true) on a Thread object. For example, the clock handler thread, the idle thread, the garbage collector thread, the screen updater thread, and the garbage collector thread are all daemon threads. A new created thread inherits the "daemon-status" of the thread that created it unless you explicitly calling setDaemon on that Thread object to change its status.

Note that the setDaemon() method must be called before the thread's start() method is invoked.Once a thread has started executing (i.e., its start() method has been called) its daemon status cannot be changed. To determine if a thread is a daemon thread, use the accessor method isDaemon().


The difference between these two types of threads is straightforward: If the Java runtime determines that the only threads running in an application are daemon threads (i.e., there are no user threads in existence) the Java runtime promptly closes down the application, effectively stopping all daemon threads dead in their tracks. In order for an application to continue running, it must always have at least one live user thread. In all other respects the Java runtime treats daemon threads and user threads in exactly the same manner.



<<Previous <<   || Index ||   >>Next >>

Priority of a Thread

In Java, thread scheduler can use the thread priorities in the form of integer value to each of its thread to determine the execution schedule of threads. Thread gets the ready-to-run state according to their priorities. The thread scheduler provides the CPU time to thread of highest priority during ready-to-run state.
3 constants defined in Thread class:
  1. public static int MIN_PRIORITY
  2. public static int NORM_PRIORITY
  3. 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.

When a Java thread is created, it inherits its priority from the thread that created it. At any given time, when multiple threads are ready to be executed, the runtime system chooses the runnable thread with the highest priority for execution. In Java runtime system, preemptive scheduling algorithm is applied. If at the execution time a thread with a higher priority and all other threads are runnable then the runtime system chooses the new higher priority thread for execution. On the other hand, if two threads of the same priority are waiting to be executed by the CPU then the round-robin algorithm is applied in which the scheduler chooses one of them to run according to their round of time-slice.
Thread Scheduler
In the implementation of threading scheduler usually applies one of the two following strategies:

Preemptive scheduling ? If the new thread has a higher priority then current running thread leaves the runnable state and higher priority thread enter to the runnable state.

Time-Sliced (Round-Robin) Scheduling ? A running thread is allowed to be execute for the fixed time, after completion the time, current thread indicates to the another thread to enter it in the runnable state.
Example of priority of a Thread:
class ThreadPriorityDemo extends Thread{
 public void run(){
     System.out.println("Running thread is "+Thread.currentThread().getName());
     System.out.println("Running thread priority is "+Thread.currentThread().getPriority());
  }
public static void main(String args[]){
   ThreadPriorityDemo t1 = new ThreadPriorityDemo();
   ThreadPriorityDemo t2 = new ThreadPriorityDemo();
   ThreadPriorityDemo t3 = new ThreadPriorityDemo();
   t1.setPriority(Thread.MIN_PRIORITY);
   t2.setPriority(Thread.MAX_PRIORITY);
   t3.setPriority(Thread.NORM_PRIORITY);
   t1.setName("Dinesh on Java");
   t2.setName("DAV JavaServices");
   t3.setName("dineshonjava.com");
   t1.start();
   t2.start();
   t3.start();
 }
}

Output:
Priority of a Thread

In the above output of program we are observing that the output of same program is vary, its means that the outputs are depends on the OS. JVM can not guaranteed about the scheduling of threads.



<<Previous <<   || Index ||   >>Next >>


Java Thread Join using join() method

In this part of tutorial we will learn how to use the join method in the Thread. Then We will create an example of Thread with the use of join method.
  • Java Join method join the next thread at the end of the current thread
  • After current thread stops execution then next thread executes.
Syntax:
public void join() throws InterruptedException
public void join(long miliseconds) throws InterruptedException

class JoinDemo extends Thread{
 public void run(){
  for(int i=1;i<=5;i++){
   try{
    Thread.sleep(500);
   }catch(Exception e){
     System.out.println(e);
   }
   System.out.println("Dinesh on Java "+i);
   }
  }
public static void main(String args[]){
 JoinDemo t1 = new JoinDemo();
 JoinDemo t2 = new JoinDemo();
 JoinDemo t3 = new JoinDemo();
 t1.start();
 try{
  t1.join();
 }catch(Exception e){
   System.out.println(e);
 }

 t2.start();
 t3.start();
 }
}
As you can see in the above example,when t1 completes its task then t2 and t3 starts executing.
output:
Java Thread Join using join() method

//Example of join(long miliseconds) method
class JoinDemo extends Thread{
 public void run(){
  for(int i=1;i<=5;i++){
   try{
    Thread.sleep(500);
   }catch(Exception e){
     System.out.println(e);
   }
   System.out.println("Dinesh on Java "+i);
   }
  }
public static void main(String args[]){
 JoinDemo t1 = new JoinDemo();
 JoinDemo t2 = new JoinDemo();
 JoinDemo t3 = new JoinDemo();
 t1.start();
 try{
  t1.join(1500);
 }catch(Exception e){
   System.out.println(e);
 }

 t2.start();
 t3.start();
 }
}
In the above example,when t1 is completes its task for 1500 milliseconds(3 times) then t2 and t3 starts executing.
output:

Java Threads Join
Naming a thread:
The Thread class provides methods to change and get the name of a thread.
Using getName(), setName(String) and getId() method:
public String getName()//is used to return the name of a thread.
public void setName(String name)//is used to change the name of a thread.
public long getId()//is used to return the id of a thread.

class JoinDemo extends Thread{
 public void run(){
  for(int i=1;i<=5;i++){
   try{
    Thread.sleep(500);
   }catch(Exception e){
     System.out.println(e);
   }
   System.out.println("Running thread is "+Thread.currentThread().getName()+" : "+i);
   }
  }
public static void main(String args[]){
 JoinDemo t1 = new JoinDemo();
 JoinDemo t2 = new JoinDemo();
 JoinDemo t3 = new JoinDemo();
 t1.setName("Dinesh on Java");
 System.out.println("id of t1:"+t1.getId());
 System.out.println("id of t2:"+t2.getId());
 System.out.println("id of t3:"+t3.getId());
 t1.start();
 try{
  t1.join(1500);
 }catch(Exception e){
   System.out.println(e);
 }

 t2.start();
 t3.start();
 }
}
The currentThread() method:
The currentThread() method returns a reference to the currently executing thread object.
output:
Threads Join() method



<<Previous <<   || Index ||   >>Next >>

Sleeping a thread using sleep() method

The Thread.sleep() method effectively "pauses" the current thread for a given period of time. We used it in our very first threading example to make threads display a message periodically, sleeping between messages. From the outset, it's important to be aware of the following:
  • it is always the current thread that is put to sleep;
  • the thread might not sleep for the required time (or even at all);
  • the sleep duration will be subject to some system-specific granularity, typically 1ms;
  • while sleeping, the thread still owns synchronization locks it has acquired;
  • the sleep can be interrupted (sometimes useful for implementing a cancellation function);
  • calling sleep() with certain values can have some subtle, global effects on the OS (see below), and vice versa, other threads and processes running on the system can have subtle effects on the observed sleep duration.
Syntax of sleep() method:
The Thread class provides two methods for sleeping a thread:
  1. public static void sleep(long miliseconds)throws InterruptedException
  2. public static void sleep(long miliseconds, int nanos)throws InterruptedException
class MultiThreadDemo extends Thread{
  public void run(){
  for(int i=1;i<5;i++){
     try{
         Thread.sleep(500);
     }catch(InterruptedException e){
         System.out.println(e);
    }
    System.out.println("Dinesh on Java Thread Application "+i);
  }
 }
 public static void main(String args[]){
  MultiThreadDemo t1 = new MultiThreadDemo();
  MultiThreadDemo t2 = new MultiThreadDemo();
 
  t1.start();
  t2.start();
 }
}
Output:
Sleeping a thread using sleep() method

As you know well that at a time only one thread is executed. If you sleep a thread for the specified time,the thread scheduler picks up another thread and so on. 



<<Previous <<   || Index ||   >>Next >>

Thread Scheduling in Java

Features :
  • The JVM schedules using a preemptive , priority based scheduling algorithm.
  • All Java threads have a priority and the thread with he highest priority is scheduled to run by the JVM.
  • In case two threads have the same priority a FIFO ordering is followed.

A different thread is invoked to run in case one of the following events occur:

1.The currently running thread exits the Runnable state ie either blocks or terminates.
2. A thread with a higher priority than the thread currently running enters the Runnable state. The lower priority thread is preempted and the higher priority thread is scheduled to run.

Time Slicing is dependent on the implementation.

A thread can voluntarily yield control through the yield() method. Whenever a thread yields control of the CPU another thread of the same priority is scheduled to run. A thread voluntarily yielding control of the CPU is called Cooperative Multitasking.
Thread Priorities
JVM selects to run a Runnable thread with the highest priority.


  • All Java threads have a priority in the range 1-10.
  • Top priority is 10, lowest priority is 1.Normal
  • priority ie. priority by default is 5.
  • Thread.MIN_PRIORITY - minimum thread priority
  • Thread.MAX_PRIORITY - maximum thread priority
  • Thread.NORM_PRIORITY - maximum thread priority

Whenever a new Java thread is created it has the same priority as the thread which created it.
Thread priority can be changed by the setpriority() method.

Java Based Round-Robin Scheduler
(An example)
public class Scheduler extends Thread

{
public Scheduler(){
timeSlice = DEFAULT_TIME_SLICE;
queue = new Circularlist();
}

public Scheduler(int quantum){
timeSlice = quantum;
queue = new Circularlist();
}

public addThread(Thread t) {
t.setPriority(2);
queue.additem(t);
}

private void schedulerSleep() {
try{
Thread.sleep(timeSlice );
} catch (InterruptedException e){};
}
public void run(){
Thread current;

This.setpriority(6);
While (true) {
// get the next thread
current = (Thread)qeue.getnext();
if ( (current != null) && (current.isAlive()) ){
current.setPriority(4);
schedulerSleep();
current.setPriority(2)
}
}
}

private CircularList queue;
private int timeSlice;
private static final int DEFAULT_TIME_SLICE = 1000;
}
public class TesScheduler
{
public static void main()String args[]) {
Thread.currentThread().setpriority(Thread.Max_Priority);
Schedular CPUSchedular = new Scheduler ();
CPUSchedular.start()
TestThread t1 = new TestThread("Thread 1");
t1.start()
CpuSchedular.addThread(t1);
TestThread t2 = new TestThread("Thread 2");
t2.start()
CpuSchedular.addThread(t2);
TestThread t3 = new TestThread("Thread 1");
t3.start()
CpuSchedular.addThread(t3);
}
}



<<Previous <<   || Index ||   >>Next >>

Creating a thread in Java

In Java, an object of the Thread class can represent a thread. Thread can be implemented through any one of two ways:
  1. Extending the java.lang.Thread Class
  2. Implementing the java.lang.Runnable Interface
Creating a thread in Java
Extending the java.lang.Thread Class

For creating a thread a class have to extend the Thread Class. For creating a thread by this procedure you have to follow these steps:
  1. Extend the java.lang.Thread Class.
  2. Override the run( ) method in the subclass from the Thread class to define the code executed by the thread.
  3. Create an instance of this subclass. This subclass may call a Thread class constructor by subclass constructor.
  4. Invoke the start( ) method on the instance of the class to make the thread eligible for running.
By extend the Thread class of java.lang package.
Syntax...........
class MyThread extends Thread
{
-----------------;
-----------------;
}
Override the run( ) Method-The run( ) method has to be Overridden by writing codes required for the thread. The thread behaves as per this code segment.
public void run()
{
----------------;
----------------;
}
Commonly used Constructors of Thread class:
  • Thread()
  • Thread(String name)
  • Thread(Runnable r)
  • Thread(Runnable r,String name)
Commonly used methods of Thread class:
  • public void run(): is used to perform action for a thread.
  • public void start(): starts the execution of the thread.JVM calls the run() method on the thread.
  • public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.
  • public void join(): waits for a thread to die.
  • public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
  • public int getPriority(): returns the priority of the thread.
  • public int setPriority(int priority): changes the priority of the thread.
  • public String getName(): returns the name of the thread.
  • public void setName(String name): changes the name of the thread.
  • public Thread currentThread(): returns the reference of currently executing thread.
  • public int getId(): returns the id of the thread.
  • public Thread.State getState(): returns the state of the thread.
  • public boolean isAlive(): tests if the thread is alive.
  • public void yield(): causes the currently executing thread object to temporarily pause and allow other threads to execute.
  • public void suspend(): is used to suspend the thread(depricated).
  • public void resume(): is used to resume the suspended thread(depricated).
  • public void stop(): is used to stop the thread(depricated).
  • public boolean isDaemon(): tests if the thread is a daemon thread.
  • public void setDaemon(boolean b): marks the thread as daemon or user thread.
  • public void interrupt(): interrupts the thread.
  • public boolean isInterrupted(): tests if the thread has been interrupted.
  • public static boolean interrupted(): tests if the current thread has been interrupted.
Extending Thread class Example

This is a way to create a thread by a new class that extends Thread class and create an instance of that class. The extending class must override run() method which is the entry point of new thread.
class MyThread extends Thread
{
   public void run()
   {
     System.out.println("Concurrent thread started running..");
   }
}

class MyThreadDemo
{
   public static void main( String args[] )
   {
     MyThread mt = new  MyThread();
     mt.start();
   }
}
In this case also, as we must override the run() and then use the start() method to start and run the thread. Also, when you create MyThread class object, Thread class constructor will also be invoked, as it is the super class, hence MyThread class object acts as Thread class object.
output:
Creating a threads in Java
What if we call run() method directly without using start() method ?
In above program if we directly call run() method, without using start() method,
public static void main( String args[] )
{
   MyThread mt = new MyThread();
   mt.run();
}
Doing so, the thread won't be allocated a new call stack, and it will start running in the current call stack, that is the call stack of the main thread. Hence Multithreading won't be there.
thread-without-new-call-stack
Can we Start a thread twice ?
No, a thread cannot be started twice. If you try to do so, IllegalThreadStateException will be thrown.
public static void main( String args[] )
{
   MyThread mt = new MyThread();
   mt.start();
   mt.start();     //Exception thrown
}
When a thread is in running state, and you try to start it again, or any method try to invoke that thread again using start() method, exception is thrown.

Implementing the Runnable Interface:
The easiest way to create a thread is to create a class that implements the runnable interface. After implementing runnable interface , the class needs to implement the run() method, which is of form,
public void run()
  • run() method introduces a concurrent thread into your program. This thread will end when run() returns.
  • You must specify the code for your thread inside run() method.
  • run() method can call other methods, can use other classes and declare variables just like any other normal method.
class MyThread implements Runnable
{
   public void run()
   {
     System.out.println("concurrent thread started running..");
   }
}

class MyThreadDemo
{
    public static void main( String args[] )
    {
      MyThread mt = new MyThread();
      Thread t = new Thread(mt);
      t.start();
   }
}
To call the run() method, start() method is used. On calling start(), a new stack is provided to the thread and run() method is called to introduce the new thread into the program.

threads



<<Previous <<   || Index ||   >>Next >>


Life Cycle of A Thread

When you are programming with threads, understanding the life cycle of thread is very valuable. While a thread is alive, it is in one of several states.

A thread can be in one of the five states in the thread. According to sun, there is only 4 states 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 is controlled by JVM. The thread states are as follows:
  1. New
  2. Runnable(Ready)
  3. Running
  4. Non-Runnable (Blocked, Sleeping, Waiting)
  5. Terminated(Dead)
Life Cycle of A Thread

States of thread- A thread has one of the following States.

New-A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread.

1-Runnable- After invocation of start() method on new thread, the thread becomes runnable.After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task.
2-Running-A thread is in running state that means the thread is currently executing. There are several ways to enter in Runnable state but there is only one way to enter in Running state: the scheduler select a thread from runnable pool.
3-Blocked- This is the state when a thread is waiting for a lock to access an object.
4-Waiting-Sometimes a thread transitions to the waiting state while the thread waits for another thread to perform a task.A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing.

5-Timed waiting- A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs.
6-Not Runnable- after Runnable states these three states are assumed to be in a not Runnable state. These three states are waiting, Timed_waiting(sleeping) and Terminated.
7-Terminated- In this state the thread is dead.



<<Previous <<   || Index ||   >>Next >>


Multithreading in Java

In this article you can learn the basic steps of creating a thread; this article provides two ways for creating your own thread in Java.

Multithreading is a process of executing multiple threads simultaneously. A program can be divided into a number of small processes. Each small process can be addressed as a single thread (a lightweight process). Multithreaded programs contain 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 spelling check.

Thread is basically a lightweight subprocess, a smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking. But we use multithreading than mulitprocessing because threads share a common memory area. They don't allocate separate memory area so save memory, and context-switching between the threads takes less time than processes.
Multithreading is mostly used in games, animation etc.

Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU. Multitasking can be achieved by two ways:
  • Process-based Multitasking(Multiprocessing)
  • Thread-based Multitasking(Multithreading)
In Java, the Java Virtual Machine (JVM) allows an application to have multiple threads of execution running concurrently. It allows a program to be more responsible to the user. When a program contains multiple threads then the CPU can switch between the two threads to execute them at the same time.
Multithreading in Java
In this diagram, two threads are being executed having more than one task. The task of each thread is switched to the task of another thread.
thread-call-stack in Java

1)Process-based Multitasking (Multiprocessing)
  • Each process have its own address in memory i.e. each process allocates separate memory area.
  • Process is heavyweight.
  • Cost of communication between the process is high.
  • Switching from one process to another require some time for saving and loading registers, memory maps, updating lists etc.

2)Thread-based Multitasking (Multithreading)
  • Threads share the same address space.
  • Thread is lightweight.
  • Cost of communication between the thread is low.
  • Note:At least one process is required for each thread.
Advantages of multithreading over multiprocessing :
  • Reduces the computation time.
  • Improves performance of an application.
  • Threads share the same address space so it saves the memory.
  • Context switching between threads is usually less expensive than between processes.
  • Cost of communication between threads is relatively low.



<<Previous <<   || Index ||   >>Next >>


Nested Interface in Java

A nested interface is just a regular interface defined inside another class or interface. They are actually defined inside the body of the parent class, not only in the same file. The feature is useful for grouping related interfaces and for encapsulating interfaces in the classes where they are used.

Nested interfaces facts:
  • when declared inside another interface they can only be public
  • when declared inside classes they can accept any access modifiers
  • they are implicitly static
  • they can be implemented by any class (package level, nested or inner) as long as the access modifiers permit visibility
  • as with regular package level interfaces variables defined inside are considered to be constants (static public) regardless of whether the modifiers are specified
  • like the package level interfaces they can declare nested classes and interfaces
While declaring nested interfaces in classes is useful and can help maintain a clean design, other constructs like classes nested in interfaces and interfaces nested in interfaces are of little benefit and seem outright weird and even dangerous.
Syntax of nested interface which is declared within the interface
interface interface_name{
 ...
 interface nested_interface_name{
  ...
 }
}

Syntax of nested interface which is declared within the class
class class_name{
 ...
 interface nested_interface_name{
  ...
 }
}

Example of nested interface which is declared within the interface

interface Designable{
   void design();
   interface Message{
       void dispaly();
  }
}

class NestedDemo implements Designable.Message{
   public void dispaly(){
     System.out.println("Hello nested interface at Dinesh on Java");
   }

  public static void main(String args[]){
     Designable.Message message = new NestedDemo();//upcasting here
     message.dispaly();
  }
}

output:
Nested Interface in Java

As you can see in the above example, we are accessing the Message interface by its outer interface Designable because it cannot be accessed directly. It is just like Almira inside the room, we cannot access the Almira directly because we must enter the room first. In collection framework, sun micro-system has provided a nested interface Entry. Entry is the sub interface of Map i.e. accessed by Map.Entry.

After compiling we get the following class files
  1. NestedDemo.class
  2. Designable$Message.class
  3. Designable.class

Internal code generated by the java compiler for nested interface Message
The java compiler internally creates public and static interface as displayed below:
public static interface Designable$Message
  {
    public abstract void dispaly();
  }

Example of nested interface which is declared within the class
Let's see how can we define an interface inside the class and how can we access it.
class Design{
    interface Message{
       void dispaly();
  }
}

class NestedDemo implements Design.Message{
   public void dispaly(){
     System.out.println("Hello nested interface at Dinesh on Java");
   }

  public static void main(String args[]){
     Design.Message message = new NestedDemo();//upcasting here
     message.dispaly();
  }
}

output:
Nested Interface

After compiling we get the following class files
  1. NestedDemo.class
  2. Design$Message.class
  3. Design.class

define a class inside the interface
If we define a class inside the interface, java compiler creates a static nested class. Let's see how can we define a class within the interface:
interface INT{
  class Demo{}
}



<<Previous <<   || Index ||   >>Next >>

static nested classes in java

A nested class that is declared static is called a static nested class. Memory to the objects of any static nested classes are allocated independently of any particular outer class object. A static nested class use the instance variables or methods defined in its enclosing class only through an object reference. A static nested class interacts with the instance members of its outer class or any other class just like a top-level class.

Given below is the syntax of the Static nested class that defines static nested class having keyword static in the outer class.
class OuterClass {
  ....
  static class StaticNestedClass {
    ....
  }
  class InnerClass {
  .... 
    }
  }
Static nested classes can be accessed by using the enclosing class name:
uterClass.StaticNestedClass
If we want to make an object of the static nested class then we have to write down the following code:
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();

Static nested class facts:
  • is defined as a static member of the parent class
  • accepts all accessibility modifiers
  • it is NOT linked to an outer instance (it can live independently)
  • has direct access to static members of the parent class regardless of the access modifiers declared in the parent class
  • has direct access to all members of an instance of the parent class regardless of the access modifiers declared in the parent class
Program of static nested class that have instance method
class StaticNested{
   static String message = "Dinesh on Java";

  static class Inner{
     void display()
     {
        System.out.println("message is "+message);
     }
  }
 
  public static void main(String args[]){
      StaticNested.Inner obj = new StaticNested.Inner();
      obj.display();
  }
}

output:
static nested classes in java

In this example, you need to create the instance of static nested class because it has instance method display(). But you don't need to create the object of StaticNested outer class because nested class is static and static properties, methods or classes can be accessed without object.

There are following class files are generated after the compilation of the program.
  1. StaticNested$Inner.class
  2. StaticNested.class
Internal code generated by the compiler for static nested class
import java.io.PrintStream;

static class StaticNested$Inner
{
    StaticNested$Inner(){
   
    }

   void display(){
      System.out.println((new StringBuilder()).append("message is ")
      .append(StaticNested.message).toString());
   }
    
}

Program of static nested class that have static method
class StaticNested{
   static String message = "Dinesh on Java";

  static class Inner{
     static void display()
     {
        System.out.println("message is "+message);
     }
  }
 
  public static void main(String args[]){
      StaticNested.Inner.display();//no need to create the instance of static nested class
  }
}
output:
static nested classes

The advantage of a static nested class is that it doesn't need an object of the containing class to work. This can help you to reduce the number of objects your application creates at runtime.



<<Previous <<   || Index ||   >>Next >>

Local Inner Classes Example in Java

If an inner class has been defined within a code block (typically within the body of a method), then such an inner class is called a local inner class. A local inner class is not a member of the enclosing class and hence it can not have any access specifier. A local inner class will have access to all the members of the enclosing class and it'll have access to the local final variables in the scope it's defined.

Program of local inner class:
class LocalInner{
   private String message = "dineshonjava.com";//instance variable
   void display(){
      class Local{
        void msg(){
          System.out.println(message);
        }
      }
     Local loc = new Local();
     loc.msg();
   }
   public static void main(String args[]){
      LocalInner obj = new LocalInner();
      obj.display();
   }
}
output:
Local Inner Classes Example in Java
After compiling we will get the following class files
  1. LocalInner$1Local.class
  2. LocalInner.class
Internal code generated by the compiler for local inner class:
In such case, compiler creates a class named LocalInner$1Local.class that have the reference of the outer class.
import java.io.PrintStream;
class LocalInner$1Local
{
    final LocalInner this$0;

    LocalInner$1Local()
    {   
        super();
        this$0 = LocalInner.this;
    }
    void msg()
    {
        System.out.println(LocalInner.access$000(LocalInner.this));
    }
}

Rule: Local variable can't be private, public or protected.

Rules for Local Inner class
1) Local inner class cannot be invoked from outside the method.
2) Local inner class cannot access non-final local variable.
Program of accessing non-final local variable in local inner class

class LocalInner{
   private String message = "dineshonjava.com";//instance variable
   void display(){
     int data = 20;//local variable must be final
      class Local{
        void msg(){
          System.out.println(message+" : "+data);//compile time error
        }
      }
     Local loc = new Local();
     loc.msg();
   }
   public static void main(String args[]){
      LocalInner obj = new LocalInner();
      obj.display();
   }
}

Output: Compile Time Error

Local Inner Classes Example

Program of accessing final local variable in local inner class:
class LocalInner{
   private String message = "dineshonjava.com";//instance variable
   void display(){
     final int data = 20;//local variable must be final
      class Local{
        void msg(){
          System.out.println(message+" : "+data);
        }
      }
     Local loc = new Local();
     loc.msg();
   }
   public static void main(String args[]){
      LocalInner obj = new LocalInner();
      obj.display();
   }
}
Output:
Local Inner Classes

A local inner class is defined within a method, and the usual scope rules apply to it. It is only accessible within that method, therefore access restrictions (public, protected, package) do not apply. However, because objects (and their methods) created from this class may persist after the method returns, a local inner class may not refer to parameters or non-final local variables of the method.



<<Previous <<   || Index ||   >>Next >>


Annonymous inner class in java

Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.

The inner class which is declared inside the body of a method is known as the local inner classes. The class declared inside the body of a method without naming it is known as anonymous inner classes.

The anonymous inner classes is very useful in some situation. For example consider a situation where you need to create the instance of an object without creating subclass of a class and also performing additional tasks such as method overloading.

A class that have no name is known as anonymous inner class.
Anonymous class can be created by:
  1. Class (may be abstract class also).
  2. Interface
Program of anonymous inner class by abstract class
abstract class Employee{
    abstract void work();
}

class Manager{
  public static void main(String args[]){
     Employee emp = new Employee(){
        void work()
        {
           System.out.println("Manage the team");}
        };
      emp.work();
   }
}

Output:
Annonymous inner class in java
After compiling we will get the following class files.
  • Employee.class
  • Manager$1.class
  • Manager.class
  1. A class is created but its name is decided by the compiler which extends the Employee class and provides the implementation of the work() method.
  2. An object of Anonymous class is created that is referred by emp reference variable of Employee type. As you know well that Parent class reference variable can refer the object of Child class.
The internal code generated by the compiler for annonymous inner class
import java.io.PrintStream;
static class Manager$1 extends Employee
{
   Manager$1(){
    
   }
   void work()
    {
        System.out.println("Manage the team");
    }
}
Program of anonymous inner class by interface:
interface Employee{
    void work();
}

class Manager{
  public static void main(String args[]){
     Employee emp = new Employee(){
        void work()
        {
           System.out.println("Manage the team");}
        };
      emp.work();
   }
}

Output:
Annonymous inner class

The internal code generated by the compiler for annonymous inner class
import java.io.PrintStream;
static class Manager$1 implements Employee
{
   Manager$1(){
    
   }
   void work()
    {
        System.out.println("Manage the team");
    }
}



<<Previous <<   || Index ||   >>Next >>

Member inner class

A class that is declared inside a class but outside a method is known as member inner class.
Invocation of Member Inner class
  1. From within the class
  2. From outside the class
Example of member inner class that is invoked inside a class
In this example, we are invoking the method of member inner class from the display method of Outer class.
class Outer{
   private int value = 70;
   class Inner{
      void show(){
          System.out.println("value is "+value );
      }
    }
 
   void display(){
     Inner in = new Inner();
     in.show();
   }
  public static void main(String args[]){
    Outer obj = new Outer();
    obj.display();
  }
}
output:
Member inner class

See in the directory there are the two following class files after compiling.
Outer.class
Outer$Inner.class

Internal code generated by the compiler for member inner class:
The java compiler creates a class file named Outer$Inner in this case. The Member inner class have the reference of Outer class that is why it can access all the data members of Outer class including private.
import java.io.PrintStream;

class Outer$Inner
{
    final Outer this$0;
    Outer$Inner()
    {   super();
        this$0 = Outer.this;
    }

    void show()
    {
        System.out.println((new StringBuilder()).append("value is ")
                    .append(Outer.access$000(Outer.this)).toString());
    }
 }


Example of member inner class that is invoked outside a class

In this example, we are invoking the show() method of Inner class from outside the outer class i.e. Test class.

//Program of member inner class that is invoked outside a class
class Outer{
  private int value = 70;
  class Inner{
   void show(){System.out.println("value is "+value);}
  }
}

class Test{
  public static void main(String args[]){
    Outer obj = new Outer();
    Outer.Inner in = obj.new Inner();
    in.show();
  }
}

output:
Member inner class in java

Rules for Inner Classes:
Following properties can be noted about Inner classes:
  • The outer class (the class containing the inner class) can instantiate as many number of inner class objects as it wishes, inside it’s code.
  • If the inner class is public & the containing class as well, then code in some other unrelated class can as well create an instance of the inner class.
  • In above case the inner class can be created as follows:
<OuterClassName> outerObj = new <OuterClassName>(arguments);
outerObj.<InnerClassName> innerObj = outerObj.new <InnerClassName>(arguments);
  • No inner class objects are automatically instantiated with an outer class object.
  • If the inner class is static, then static inner class can be instantiated without an outer class instance, otherwise, the inner class object must be associated with an instance of the outer class.
  • Inner class code has free access to all elements of the outer class object that contains it, by name (no matter what the access level of the elements is), if the inner class has a varible with same name then the outer class’s variable can be access like this:
<OuterClassName>.this.<variableName>
  • The outer class can call even the private methods of the inner class



<<Previous <<   || Index ||   >>Next >>


Inner Nested Classes in Java

A class declared inside a class is known as nested class. We use nested classes to logically group classes in one place so that it can be more readable and maintainable code. Moreover, it can access all the members of outer class including private members.

Syntax of Nested class
class OuterClass {
    ...
    class NestedClass {
        ...
    }
}
difference between nested class and inner class?
Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are simply called static nested classes. Non-static nested classes are called inner classes. Inner class is a part of nested class. Non-static nested classes are known as inner classes.
A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class. As a member of the OuterClass, a nested class can be declared private, public, protected, or package private. (Recall that outer classes can only be declared public or package private.)

Why Use Nested Classes?

There are several compelling reasons for using nested classes, among them:

  1. It is a way of logically grouping classes that are only used in one place.
  2. It increases encapsulation.
  3. Nested classes can lead to more readable and maintainable code.
  • Logical grouping of classes—If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined.
  • Increased encapsulation—Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared private. By hiding class B within class A, A's members can be declared private and B can access them. In addition, B itself can be hidden from the outside world.
  • More readable, maintainable code—Nesting small classes within top-level classes places the code closer to where it is used.

Types of Nested class:
There are two types of nested classes non-static and static nested classes.The non-static nested classes are also known as inner classes.
  1. non-static nested class(inner class)
    • a)Member inner class
    • b)Annomynous inner class
    • c)Local inner class
  2. static nested class
Inner Nested Classes in Java

Static Nested Classes

As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class — it can use them only through an object reference.

Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.
Static nested classes are accessed using the enclosing class name:
OuterClass.StaticNestedClass
For example, to create an object for the static nested class, use this syntax:
OuterClass.StaticNestedClass nestedObject =
new OuterClass.StaticNestedClass();

Inner Classes

As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. Also, because an inner class is associated with an instance, it cannot define any static members itself.

Objects that are instances of an inner class exist within an instance of the outer class. Consider the following classes:
class OuterClass {
    ...
    class InnerClass {
        ...
    }
}
An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance. The next figure illustrates this idea.
Inner Nested Classes

To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
Additionally, there are two special kinds of inner classes: local classes and anonymous classes.


<<Previous <<   || Index ||   >>Next >>

String In Switch-Java 7 New Concept

In this article we will discuss String in a switch statement; a new feature of Java 7. So for explaining this topic we take a short look at switch, string and some switch cases.

Introduction

In this article we will discuss String in a switch statement; a new feature of Java 7. So for explaining this topic we take a short look at switch, string and some switch cases.

Strings In Java

String are widely used in Java, they are a sequence of characters (sometimes called a character array). In Java, strings are objects.

Java provides the String class to create and manipulate strings.

How to Create a String

The general way to create a string is:
String welcome="welcome to Java world";
Let's see an example to display the simple string "Welcome".
public class StringEx
{
  public static void main(String args[])
  {
    char[] WelcomeArray = { 'W', 'e', 'l', 'c', 'o', 'm', 'e'};
    String WelcomeString = new String(WelcomeArray); 
    System.out.println( WelcomeString );
  }   
}
Output:
Welcome

Switch case in Java

Switch statements reduce the workload, since without a switch we use if and else many times instead of the switch. Let's see a sample of if and else without a switch:
if (x == 0) doSomework0();
else if (x == 1) doSomework1();
else if (x == 2) doSomework2();
else if (x == 3) doSomework3();
else if (x == 4) doSomework4();
else doSomeworkElse();
Java has a shorthand for these types of multiple if statements, the switch-case statement. Here's how you'd write the above using a switch-case:
switch (x)
{
case 0: 
doSomework0();
break;
case 1: 
doSomework1();
break;
case 2: 
doSomework2();
break;
case 3: 
doSomework3();
break;
case 4: 
doSomework4();
break;
default: 
doSomeworkElse();
}
In this example x must be a variable. x is compared to each case value. In case 0 the x must be compared with x==0 if it is then subsequent code will execute, similarly x will work according to other cases. If no cases are matched then the default action is triggered.

Purpose of switch

The if statement only evaluates a boolean value (only two possible values True and False). The switch statement will execute on many expressions based on an integer (including char) or enum value.

Switch keywords

switch

The Switch statement is followed by an expression in parenthesis, that is followed by the cases, all enclosed in braces. The Switch statement works using cases dependent on the value of expressions.

Case
The case contain a colon and an integer constant.

default

If no case value matches the switch expression value then execution falls to the default clause. This is the equivalent of the last "else" for a series of if statements.

break

The break statement causes execution to exit to the statement after the end of the switch. If there is no break then execution flows thru into the next case. Flowing directly into the next case is nearly always an error.

Example

Let's see an example of how switch cases work!

import java.io.*;
public class SwitchEx
  {
    public static void main(String args[]) throws Exception
      {
        int choice;
        // we make a month chart to test switch cases
        System.out.println("Enter 1 for January.");
        System.out.println("Enter 2 for Febrary");
        System.out.println("Enter 3 for March.");
        System.out.println("Enter 4 for April.");
        System.out.println("Enter 5 for May.");
        System.out.println("Enter 6 for June.");
        System.out.println("Enter 7 for July.");
        System.out.println("Enter 8 for August.");
        System.out.println("Enter 9 for September.");
        System.out.println("Enter 10 for October.");
        System.out.println("Enter 11 for November.");
        System.out.println("Enter 12 for December.");
        System.out.print("\n Whats your choice : ");
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        try
          {
            choice=Integer.parseInt(in.readLine());
            switch(choice)
              { 
                case 1: System.out.println("January");
                break;
                case 2: System.out.println("Febrary");
                break;
                case 3: System.out.println("March");
                break;
                case 4: System.out.println("April");
                break;
                case 5: System.out.println("May");
                break;
                case 6: System.out.println("June");
                break;
                case 7: System.out.println("July");
                break;
                case 8: System.out.println("August");
                break;
                case 9: System.out.println("September");
                break;
                case 10: System.out.println("October");
                break;
                case 11: System.out.println("November");
                break;
                case 12: System.out.println("December");
                break;
                default: System.out.println("Wrong entry!");
                break;
                }
           }
        catch(NumberFormatException ey)
          {
            System.out.println(ey.getMessage() + " enter only numeric value.");
            System.exit(0);
          }
      }
  }

Output:
String In Switch-Java 7 New Concept

String in switch: Java 7 new feature

Switch statements work either with primitive types (e.g byte, short, long, int, etc) or enumerated types. Java 7 introduced another type that we can use in Switch statements: the String type.

The method of working on strings is crude. Java 7 improves the program by enhancing the Switch statement, that takes a String type as an argument.

Let's see a previous example using a String in a switch this time. In this example a string is invoked in the switch statement which can't be end in prior versions of Java. So it might be helpful for reducing if-else statements.

public class StringSwitchEx
  {
    public static int getMonthNumber(String month)
      {
        int monthNumber = 0;
        if (month == null)
          {
            return monthNumber;
          }
        switch (month.toLowerCase())
          {
            case "january":
            monthNumber = 1;
            break;
            case "february":
            monthNumber = 2;
            break;
            case "march":
            monthNumber = 3;
            break;
            case "april":
            monthNumber = 4;
            break;
            case "may":
            monthNumber = 5;
            break;
            case "june":
            monthNumber = 6;
            break;
            case "july":
            monthNumber = 7;
            break;
            case "august":
            monthNumber = 8;
            break;
            case "september":
            monthNumber = 9;
            break;
            case "october":
            monthNumber = 10;
            break;
            case "november":
            monthNumber = 11;
            break;
            case "december":
            monthNumber = 12;
            break;
            default: 
            monthNumber = 0;
            break;
          }
        return monthNumber;
      }
    public static void main(String[] args)
      {
        String month = "June";
        int returnedMonthNumber =StringSwitchEx.getMonthNumber(month);
        if (returnedMonthNumber == 0)
          {
            System.out.println("Invalid month");
          }
        else
          {
            System.out.print("The selected month no is : ");
            System.out.print(returnedMonthNumber);
          }
      }
  }
output:
Java 7 New Concept



<<Previous <<   || Index ||   >>Next >>

Multiple Exceptions In Java 7 New Concept

Introduction

In this article we will discuss multiple exceptions in Java 7. Its a new feature released by Java 7 to remove redundancy of code since we don't need to write a catch statement again and again. First we discuss exceptions and exception handling and after that multiple exceptions in Java 7.

Exception in Java

In terms of dictionaries, an exception is an abnormal condition. When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.

In Java, an exception is an event that disrupts the normal flow of a program.

When we execute our program, sometimes an error is generated for some of reasons given below, when this error is generated during execution it is called an exception. The exception can occur:


  • When the user has entered incorrect data or we can say invalid data.
  • When we opened a file that's needed in the program but can't be found.
  • Sometimes when the network connection is lost during execution of the program.
To understand exceptions in Java, you need to understand the two categories of exceptions; they are:


  1. Checked Exception (also called a compile-time exception)
  2. Unchecked Exception (also called a run-time exception)
Checked Exception

It is also called a compile-time exception since they checked at compile time of the program. For example, ServletException, ClassNotFoundException, NoSuchFieldException etc.

Unchecked Exception

It is also called a run-time exception since they occur during run-time. Such an exception is not checked at compile time, in other words NullPointerException, OutOfMemoryError, etc.

example
public class RunTimeExcpn 
  { 
    public static void main(String[] args) 
      { 
        String str = null;
        int len = str.length();
      } 
  }

Output:
Multiple Exceptions In Java 7 New Concept

Now the subject arises of how to overcome this problem of exception, for that Java provides am exception handler technique. Now we discuss exception handling in Java.

Exception Handling in Java

It is a powerful feature provided in Java. It is a mechanism to handle run-time errors, so that the normal flow of the program is maintained.

Exception handling consists of the following five keywords:

  1. Try
  2. Catch
  3. Finally
  4. Throw
  5. Throws
Now, we show an example for exception handling:
class Demo
  {
    public static void main(String args[])
      {
        try
          {
            int data=50/0;
          }
        catch(ArithmeticException e) 
          {
            System.out.println(e);
          }
        System.out.println("remaining code");
      }
  }

Output:

In this program an arithmetic exception occurs that is sometimes called "divide by null error" problem, for handling this exception we use a "try-catch block". In the try block we write the code where the problem occurs and in the catch block we catch the exception as determined by its type. In this program the arithmetic exception is generated so we use a catch(ArithmeticException e) statement to maintain the flow of the program.

Multiple Exceptions In Java

We are not going into the details of Exception Handling; our topic is "multiple exceptions in Java 7". So for discussing our topic we take a short look at "exception" and "exception handling" in Java.

Multiple Exception in Java 7 new concept

It provides a way of "Handling More Than One Type of Exception". Java 7 made it possible to catch various exceptions in the same catch block that is not possible in prior versions of Java. This is also known as multi-catch.

In prior versions of Java:
catch (IOException ey)
  {
    logger.log(ey);
    throw ey;
catch (SQLException ey) 
  {
    logger.log(ey);
    throw ey;
  }
catch(Exception e) 
  {
    logger.severe(e);
  }

In prior versions of Java 7, it is difficult to create a common method to remove the repeated code because the variable "ey" has various types.

The following example is valid in Java 7 and later, it eliminates the need for repeated code:
catch (IOException | SQLException ey) 
  {
    logger.log(ey);
    throw ey;
  }
The catch defines the types of exceptions, and each exception type is separated with a vertical bar ( | ).

Advantages of Multiple Exception in Java 7


  1. Single-line catching might help in JDBC, formatting date and Java IO in Java. For throwing an exception in IO related code we use IOException, in JDBC code we use SQLException, and for date formatting we use ParseException, that can't be handled in a single catch block prior to Java 7. Catching java.lang.Exception works for all kinds of exceptions but it is not a good practice. With multiple exceptions in Java 7 we catch both exceptions in one catch block.
  2. The exception handling changes in Java SE 7 allow you to program more concisely.
  3. They also allow you to partially handle an exception and then let it bubble up.
  4. Reduce a substantial amount of workload.
  5. Remove redundancy of code since we don't need to write a catch statement again and again.
Now in following example we show a difference between exception handling in Java 7 and in prior versions of Java.

Exception handling in Java

class ExceptionEx1
  {
    public static void main(String args[])
      {
        try
          {
            int a[]=new int[5];
            a[5]=345/0;
          }
        catch(ArithmeticException e)
          {
            System.out.println("work 1 done");
          }
        catch(ArrayIndexOutOfBoundsException e)
          {
            System.out.println("work 2 completed");
          }
        catch(Exception e)
          {
            System.out.println("Common task completed");
          }
        System.out.println("remaining part of the code");
      }
  }
Output:
Multiple Exceptions

Exception handling in Java 7
class ExceptionEx2
{
   public static void main(String args[])
   {
    try
    {
     int a[]=new int[5];
     a[5]=345/0;
    }
    catch(ArithmeticException | ArrayIndexOutOfBoundsException e)
    {
     System.out.println("work 1 done");
    }
    catch(Exception e)
    {
      System.out.println("Common task completed");
    }
    System.out.println("remaining part of the code");
  }
}
Output:
Multiple Exceptions In Java  New Concept


<<Previous <<   || Index ||   >>Next >>