Core Java - Multithreading


Java is a multithreaded programming language which means we can develop multithreaded program using Java. A multithreaded program contains two or more parts that can run concurrently and each part can handle different task at the same time making optimal use of the available resources specially when your computer has multiple CPUs.

By definition multitasking is when multiple processes share common processing resources such as a CPU. Multithreading extends the idea of multitasking into applications where you can subdivide specific operations within a single application into individual threads. Each of the threads can run in parallel. The OS divides processing time not only among different applications, but also among each thread within an application.

Multithreading enables you to write in a way where multiple activities can proceed concurrently in the same program.

Life Cycle of a Thread :
A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. Following diagram shows complete life cycle of a thread.

Multithreading

Above-mentioned stages are explained here:

  • 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.

  • Runnable : After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task.

  • 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.

  • 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.

  • Terminated : A runnable thread enters the terminated state when it completes its task or otherwise terminates.


  • Thread Priorities :
    Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled.
    Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5).

    Threads with higher priority are more important to a program and should be allocated processor time before lowerpriority threads. However, thread priorities cannot guarantee the order in which threads execute and very much platform dependentant.

    Create Thread by Implementing Runnable Interface:
    If your class is intended to be executed as a thread then you can achieve this by implementingRunnable interface. You will need to follow three basic steps:

    STEP 1 :
    As a first step you need to implement a run() method provided by Runnable interface. This method provides entry point for the thread and you will put you complete business logic inside this method. Following is simple syntax of run() method:
        public void run( )
    
    
    STEP 2 :
    At second step you will instantiate a Thread object using the following constructor:
        Thread(Runnable threadObj, String threadName);
    
    
    STEP 3 :
    Once Thread object is created, you can start it by calling start( ) method, which executes a call to run( ) method. Following is simple syntax of start() method:
      void start( );
    
    
    Eg:
      class RunnableDemo implements Runnable {
        private Thread t;
        private String threadName;
    
        RunnableDemo( String name){
        threadName = name;
        System.out.println("Creating " + threadName );
        }
        public void run() {
        System.out.println("Running " + threadName );
        try {
        for(int i = 4; i > 0; i--) {
        System.out.println("Thread: " + threadName + ", " + i);
        // Let the thread sleep for a while.
        Thread.sleep(50);
        }
        } catch (InterruptedException e) {
        System.out.println("Thread " + threadName + " interrupted.");
        }
        System.out.println("Thread " + threadName + " exiting.");
        }
    
        public void start (){
        System.out.println("Starting " + threadName );
        if (t == null){
        t = new Thread (this, threadName);
        t.start ();
        }
        }
      }
    
      public class TestThread {
        public static void main(String args[]) {
    
        RunnableDemo R1 = new RunnableDemo( "Thread-1");
        R1.start();
    
        RunnableDemo R2 = new RunnableDemo( "Thread-2");
        R2.start();
        }
      }
    
    
    Output :
    Creating Thread-1
    Starting Thread-1
    Creating Thread-2
    Starting Thread-2
    Running Thread-1
    Thread: Thread-1, 4
    Running Thread-2
    Thread: Thread-2, 4
    Thread: Thread-1, 3
    Thread: Thread-2, 3
    Thread: Thread-1, 2
    Thread: Thread-2, 2
    Thread: Thread-1, 1
    Thread: Thread-2, 1
    Thread Thread-1 exiting.
    Thread Thread-2 exiting.

    Create Thread by Extending Thread Class :
    The second way to create a thread is to create a new class that extends Thread class using the following two simple steps. This approach provides more flexibility in handling multiple threads created using available methods in Thread class.

    STEP 1 :
    You will need to override run( ) method available in Thread class. This method provides entry point for the thread and you will put you complete business logic inside this method.
    Syntax of run() method:
    
      public void run( )
    
    
    STEP 2 :
    Once Thread object is created, you can start it by calling start( ) method, which executes a call to run( ) method.
    Syntax of start() method:
    
      void start( );
    
    
    Eg:
      class ThreadDemo extends Thread {
        private Thread t;
        private String threadName;
    
        ThreadDemo( String name){
        threadName = name;
        System.out.println("Creating " + threadName );
        }
        public void run() {
        System.out.println("Running " + threadName );
        try {
        for(int i = 4; i > 0; i--) {
        System.out.println("Thread: " + threadName + ", " + i);
        // Let the thread sleep for a while.
        Thread.sleep(50);
        }
        } catch (InterruptedException e) {
        System.out.println("Thread " + threadName + " interrupted.");
        }
        System.out.println("Thread " + threadName + " exiting.");
        }
    
        public void start (){
        System.out.println("Starting " + threadName );
        if (t == null){
          t = new Thread (this, threadName);
        t.start ();
        }
        }
      }
    
      public class TestThread {
        public static void main(String args[]) {
    
        ThreadDemo T1 = new ThreadDemo( "Thread-1");
        T1.start();
    
        ThreadDemo T2 = new ThreadDemo( "Thread-2");
        T2.start();
        }
      }
    
    
    Output :
    Creating Thread-1
    Starting Thread-1
    Creating Thread-2
    Starting Thread-2
    Running Thread-1
    Thread: Thread-1, 4
    Running Thread-2
    Thread: Thread-2, 4
    Thread: Thread-1, 3
    Thread: Thread-2, 3
    Thread: Thread-1, 2
    Thread: Thread-2, 2
    Thread: Thread-1, 1
    Thread: Thread-2, 1
    Thread Thread-1 exiting.
    Thread Thread-2 exiting.

    Thread Methods :
    Following is the list of important methods available in the Thread class
    
     S.No             Methods                                                   Description
     ---- -----------------------------------------  --------------------------------------------------------------------------
      1    public void start()                        Starts the thread in a separate path of execution, then invokes the 
                                                      run() method on this Thread object.
    
      2    public void run()                          If this Thread object was instantiated using a separate Runnable target,  
                                                      the run() method is invoked on thatRunnable object.
    
      3    public final void setName(String name)     Changes the name of the Thread object. There is also a getName() method 
                                                      for retrieving the name.
    
      4    public final void setPriority(int          Sets the priority of this Thread object. The possible values are 
           priority)                                  between 1 and 10.
    
      5    public final void setDaemon(boolean on)    A parameter of true denotes this Thread as a daemon thread.
    
      6    public final void join(long millisec)      The current thread invokes this method on a second thread, causing  
                                                      the current thread to block until the second thread terminates or 
                                                      the specified number of milliseconds passes.
    
      7    public void interrupt()                    Interrupts this thread, causing it to continue execution if it was blocked 
                                                      for any reason.
    
      8    public final boolean isAlive()             Returns true if the thread is alive, which is any time after the thread  
                                                      has been started but before it runs to completion.
    
    
    The previous methods are invoked on a particular Thread object. The following methods in the Thread class are static. Invoking one of the static methods performs the operation on the currently running thread
    
      S.No              Methods                                                Description
      ---- -----------------------------------------   --------------------------------------------------------------------------
      1    public static void yield()                  Causes the currently running thread to yield to any other threads of the 
                                                       same priority that are waiting to bescheduled.
    
      2    public static void sleep(long millisec)     Causes the currently running thread to block for at least the specified 
                                                       number of milliseconds.
    
      3    public static boolean holdsLock(Object x)   Returns true if the current thread holds the lock on the given Object.
    
      4    public static Thread currentThread()        Returns a reference to the currently running thread, which is the thread 
                                                       that invokes this method.
    
      5    public static void dumpStack()              Prints the stack trace for the currently running thread, which is useful 
                                                       when debugging a multithreaded application.
    
    
    Eg:
    The following ThreadClassDemo program demonstrates some of these methods of the Thread class. Consider a class DisplayMessage which implements Runnable:
      // File Name : DisplayMessage.java
      // Create a thread to implement Runnable
      public class DisplayMessage implements Runnable{
        private String message;
        public DisplayMessage(String message){
        this.message = message;
        }
        public void run(){
        while(true){
        System.out.println(message);
        }
        }
      }
    
    
    Following is another class which extends Thread class:
      // File Name : GuessANumber.java
      // Create a thread to extentd Thread
      public class GuessANumber extends Thread{
        private int number;
        public GuessANumber(int number){
        this.number = number;
        }
        public void run(){
        int counter = 0;
        int guess = 0;
        do{
        guess = (int) (Math.random() * 100 + 1);
        System.out.println(this.getName() + " guesses " + guess);
        counter++;
        }while(guess != number);
        System.out.println("** Correct! " + this.getName() + " in " + counter + " guesses.**");
        }
      }
    
    
    Following is the main program which makes use of above defined classes:
      // File Name : ThreadClassDemo.java
      public class ThreadClassDemo{
        public static void main(String [] args){
        Runnable hello = new DisplayMessage("Hello");
        Thread thread1 = new Thread(hello);
        thread1.setDaemon(true);
        thread1.setName("hello");
        System.out.println("Starting hello thread...");
        thread1.start();
    
        Runnable bye = new DisplayMessage("Goodbye");
        Thread thread2 = new Thread(bye);
        thread2.setPriority(Thread.MIN_PRIORITY);
        thread2.setDaemon(true);
        System.out.println("Starting goodbye thread...");
        thread2.start();
        System.out.println("Starting thread3...");
        Thread thread3 = new GuessANumber(27);
        thread3.start();
    
        try{
        thread3.join();
        }catch(InterruptedException e){
        System.out.println("Thread interrupted.");
        }
        System.out.println("Starting thread4...");
        Thread thread4 = new GuessANumber(75);
    
        thread4.start();
        System.out.println("main() is ending...");
        }
      }
    
    
    Output :
    Starting hello thread...
    Starting goodbye thread...
    Hello
    Hello
    Hello
    Hello
    Hello
    Hello
    Goodbye
    Goodbye
    Goodbye
    Goodbye
    Goodbye
    .......

    Major Java Multithreading Concepts :
    While doing Multithreading programming in Java, you would need to have the following concepts very handy:

  • What is thread Synchronization?
  • Handling threads inter communication
  • Handling threads deadlock
  • Major thread operations


  • What is thread Synchronization ?
    When we start two or more threads within a program, there may be a situation when multiple threads try to access the same resource and finally they can produce unforeseen result due to concurrency issue. For example if multiple threads try to write within a same file then they may corrupt the data because one of the threads can overrite data or while one thread is opening the same file at the same time another thread might be closing the same file.
    So there is a need to synchronize the action of multiple threads and make sure that only one thread can access the resource at a given point in time. This is implemented using a concept called monitors. Each object in Java is associated with a monitor, which a thread can lock or unlock. Only one thread at a time may hold a lock on a monitor.
    Java programming language provides a very handy way of creating threads and synchronizing their task by using synchronized blocks. You keep shared resources within this block.

    Following is the general form of the synchronized statement:
    
      synchronized(objectidentifier) {
        // Access shared variables and other shared resources
      }
    
    
    Here, the objectidentifier is a reference to an object whose lock associates with the monitor that the synchronized statement represents. Now we are going to see two examples where we will print a counter using two different threads.
    When threads are not synchronized, they print counter value which is not in sequence, but when we print counter by putting inside synchronized() block, then it prints counter very much in sequence for both the threads.

    Multithreading example without Synchronization :
    Here is a simple example which may or may not print counter value in sequence and every time we run it, it produces different result based on CPU availability to a thread.
      class PrintDemo {
        public void printCount(){
        try {
        for(int i = 5; i > 0; i--) {
        System.out.println("Counter --- " + i );
        }
        } catch (Exception e) {
        System.out.println("Thread interrupted.");
        }
        }
      }
    
      class ThreadDemo extends Thread {
        private Thread t;
        private String threadName;
        PrintDemo PD;
        ThreadDemo( String name, PrintDemo pd){
        threadName = name;
        PD = pd;
        }
        public void run() {
        PD.printCount();
        System.out.println("Thread " + threadName + " exiting.");
        }
        public void start (){
        System.out.println("Starting " + threadName );
        if (t == null){
        t = new Thread (this, threadName);
        t.start ();
        }
        }
      }
    
      public class TestThread {
        public static void main(String args[]) {
        PrintDemo PD = new PrintDemo();
        ThreadDemo T1 = new ThreadDemo( "Thread - 1 ", PD );
        ThreadDemo T2 = new ThreadDemo( "Thread - 2 ", PD );
        T1.start();
        T2.start();
        // wait for threads to end
        try {
        T1.join();
        T2.join();
        } catch( Exception e) {
        System.out.println("Interrupted");
        }
        }
      }
    
    
    Output :
    Starting Thread - 1
    Starting Thread - 2
    Counter --- 5
    Counter --- 4
    Counter --- 3
    Counter --- 5
    Counter --- 2
    Counter --- 1
    Counter --- 4
    Thread Thread - 1 exiting.
    Counter --- 3
    Counter --- 2
    Counter --- 1
    Thread Thread - 2 exiting

    Multithreading example with Synchronization :
    Here is the same example which prints counter value in sequence and every time we run it, it produces same result
      class PrintDemo {
        public void printCount(){
        try {
        for(int i = 5; i > 0; i--) {
        System.out.println("Counter --- " + i );
        }
        } catch (Exception e) {
        System.out.println("Thread interrupted.");
        }
        }
      }
    
      class ThreadDemo extends Thread {
        private Thread t;
        private String threadName;
        PrintDemo PD;
        ThreadDemo( String name, PrintDemo pd){
        threadName = name;
        PD = pd;
        }
        public void run() {
        synchronized(PD) {
        PD.printCount();
        }
        System.out.println("Thread " + threadName + " exiting.");
        }
        public void start (){
        System.out.println("Starting " + threadName );
        if (t == null){
        t = new Thread (this, threadName);
        t.start ();
        }
        }
      }
    
      public class TestThread {
        public static void main(String args[]) {
        PrintDemo PD = new PrintDemo();
        ThreadDemo T1 = new ThreadDemo( "Thread - 1 ", PD );
        ThreadDemo T2 = new ThreadDemo( "Thread - 2 ", PD );
        T1.start();
        T2.start();
        // wait for threads to end
        try {
        T1.join();
        T2.join();
        } catch( Exception e) {
        System.out.println("Interrupted");
        }
        }
      }
    
    
    Output :
    Starting Thread - 1
    Starting Thread - 2
    Counter --- 5
    Counter --- 4
    Counter --- 3
    Counter --- 2
    Counter --- 1
    Thread Thread - 1 exiting.
    Counter --- 5
    Counter --- 4
    Counter --- 3
    Counter --- 2
    Counter --- 1
    Thread Thread - 2 exiting.

    Handling threads inter communication :
    If you are aware of interprocess communication then it will be easy for you to understand inter thread communication. Inter thread communication is important when you develop an application where two or more threads exchange some information.
    There are simply three methods and a little trick which makes thread communication possible. First let's see all the three methods listed below:
    
       S.No         Methods                                                Description
       ----- --------------------------    -----------------------------------------------------------------------------
        1     public void wait()             Causes the current thread to wait until another thread invokes the notify().
        2     public void notify()           Wakes up a single thread that is waiting on this object's monitor.
        3     public void notifyAll()        Wakes up all the threads that called wait( ) on the same object.
    
    
    These methods have been implemented as final methods in Object, so they are available in all the classes. All three methods can be called only from within a synchronized context.
    Eg:
    This examples shows how two thread can communicate using wait() and notify() method. You can create a complex system using the same concept.
      class Chat {
        boolean flag = false;
    
        public synchronized void Question(String msg) {
        if (flag) {
        try {
        wait();
        } catch (InterruptedException e) {
        e.printStackTrace();
        }
        }
        System.out.println(msg);
        flag = true;
        notify();
        }
    
        public synchronized void Answer(String msg) {
        if (!flag) {
        try {
        wait();
        } catch (InterruptedException e) {
        e.printStackTrace();
        }
        }
        System.out.println(msg);
        flag = false;
        notify();
        }
      }
    
      class T1 implements Runnable {
        Chat m;
        String[] s1 = { "Hi", "How are you ?", "I am also doing fine!" };
        public T1(Chat m1) {
        this.m = m1;
        new Thread(this, "Question").start();
        }
        public void run() {
        for (int i = 0; i < s1.length; i++) {
        m.Question(s1[i]);
        }
        }
      }
    
      class T2 implements Runnable {
        Chat m;
        String[] s2 = { "Hi", "I am good, what about you?", "Great!" };
        public T2(Chat m2) {
        this.m = m2;
        }
        public void run() {
        for (int i = 0; i < s2.length; i++) {
        m.Answer(s2[i]);
        }
        }
      }
    
      public class TestThread {
        public static void main(String[] args) {
        Chat m = new Chat();
        new T1(m);
        new T2(m);
        }
      }
    
    
    Output :
    Hi
    Hi
    How are you ?
    I am good, what about you?
    I am also doing fine!
    Great!

    Handling threads deadlock :
    Deadlock describes a situation where two or more threads are blocked forever, waiting for each other. Deadlock occurs when multiple threads need the same locks but obtain them in different order. A Java multithreaded program may suffer from the deadlock condition because the synchronized keyword causes the executing thread to block while waiting for the lock, or monitor, associated with the specified object.

    Eg:
      public class TestThread {
          public static Object Lock1 = new Object();
          public static Object Lock2 = new Object();
    
        private static class ThreadDemo1 extends Thread {
          public void run() {
          synchronized (Lock1) {
          System.out.println("Thread 1: Holding lock 1...");
          try { Thread.sleep(10); }
          catch (InterruptedException e) {}
          System.out.println("Thread 1: Waiting for lock 2...");
          synchronized (Lock2) {
          System.out.println("Thread 1: Holding lock 1 & 2...");
          }
          }
          }
        }
    
        private static class ThreadDemo2 extends Thread {
          public void run() {
          synchronized (Lock2) {
          System.out.println("Thread 2: Holding lock 2...");
          try { Thread.sleep(10); }
          catch (InterruptedException e) {}
          System.out.println("Thread 2: Waiting for lock 1...");
          synchronized (Lock1) {
          System.out.println("Thread 2: Holding lock 1 & 2...");
          }
          }
          }
        }
    
        public static void main(String args[]) {
          ThreadDemo1 T1 = new ThreadDemo1();
          ThreadDemo2 T2 = new ThreadDemo2();
          T1.start();
          T2.start();
          }
      }
    
    
    Output :
    Thread 1: Holding lock 1...
    Thread 2: Holding lock 2...
    Thread 1: Waiting for lock 2...
    Thread 2: Waiting for lock 1...

    Deadlock Solution Example :
    Let's change the order of the lock and run the same program to see if still both the threads waits for each other:
      public class TestThread {
        public static Object Lock1 = new Object();
        public static Object Lock2 = new Object();
    
        private static class ThreadDemo1 extends Thread {
          public void run() {
          synchronized (Lock1) {
          System.out.println("Thread 1: Holding lock 1...");
          try { Thread.sleep(10); }
          catch (InterruptedException e) {}
          System.out.println("Thread 1: Waiting for lock 2...");
          synchronized (Lock2) {
          System.out.println("Thread 1: Holding lock 1 & 2...");
          }
          }
          }
        }
    
        private static class ThreadDemo2 extends Thread {
            public void run() {
          synchronized (Lock1) {
          System.out.println("Thread 2: Holding lock 1...");
          try { Thread.sleep(10); }
          catch (InterruptedException e) {}
          System.out.println("Thread 2: Waiting for lock 2...");
          synchronized (Lock2) {
          System.out.println("Thread 2: Holding lock 1 & 2...");
          }
          }
          }
        }
    
        public static void main(String args[]) {
          ThreadDemo1 T1 = new ThreadDemo1();
          ThreadDemo2 T2 = new ThreadDemo2();
          T1.start();
          T2.start();
        }
      }
    
    
    Output :
    Thread 1: Holding lock 1...
    Thread 1: Waiting for lock 2...
    Thread 1: Holding lock 1 & 2...
    Thread 2: Holding lock 1...
    Thread 2: Waiting for lock 2...
    Thread 2: Holding lock 1 & 2...

    Major thread operations :
    Core Java provides a complete control over multithreaded program. You can develop a multithreaded program which can be suspended, resumed or stopped completely based on your requirements. There are various static methods which you can use on thread objects to control their behavior. Following table lists down those methods:
    
     S.No       Methods                                         Description
     ---- -----------------------  -----------------------------------------------------------------------------------------
      1   public void suspend()      This method puts a thread in suspended state and can be resumed using resume() method.
      2   public void stop()         This method stops a thread completely.
      3   public void resume()       This method resumes a thread which was suspended using suspend() method.
      4   public void wait()         Causes the current thread to wait until another thread invokes the notify().
      5   public void notify()       Wakes up a single thread that is waiting on this object's monitor.
    
    
    Be aware that latest versions of Java has deprecated the usage of suspend( ), resume( ), and stop( ) methods and so you need to use available alternatives
    Eg:
      class RunnableDemo implements Runnable {
        public Thread t;
        private String threadName;
        boolean suspended = false;
      
        RunnableDemo( String name){
        threadName = name;
        System.out.println("Creating " + threadName );
        }
    
        public void run() {
          System.out.println("Running " + threadName );
          try {
          for(int i = 10; i > 0; i--) {
          System.out.println("Thread: " + threadName + ", " + i);
          // Let the thread sleep for a while.
          Thread.sleep(300);
          synchronized(this) {
          while(suspended) {
          wait();
          }
          }
          }
          } catch (InterruptedException e) {
          System.out.println("Thread " + threadName + " interrupted.");
          }
          System.out.println("Thread " + threadName + " exiting.");
        }
    
        public void start (){
          System.out.println("Starting " + threadName );
          if (t == null){
          t = new Thread (this, threadName);
          t.start ();
          }
        }
    
        void suspend() {
          suspended = true;
        }
    
        synchronized void resume() {
        suspended = false;
        notify();
        }
      }
    
      public class TestThread {
        public static void main(String args[]) {
        RunnableDemo R1 = new RunnableDemo( "Thread-1");
        R1.start();
        RunnableDemo R2 = new RunnableDemo( "Thread-2");
        R2.start();
        try {
        Thread.sleep(1000);
        R1.suspend();
        System.out.println("Suspending First Thread");
        Thread.sleep(1000);
        R1.resume();
        System.out.println("Resuming First Thread");
        R2.suspend();
        System.out.println("Suspending thread Two");
        Thread.sleep(1000);
        R2.resume();
        System.out.println("Resuming thread Two");
        } catch (InterruptedException e) {
        System.out.println("Main thread Interrupted");
        }
        try {
        System.out.println("Waiting for threads to finish.");
        R1.t.join();
        R2.t.join();
        } catch (InterruptedException e) {
        System.out.println("Main thread Interrupted");
        }
        System.out.println("Main thread exiting.");
        }
      }
    
    
    Output :
    Creating Thread-1
    Starting Thread-1
    Creating Thread-2
    Starting Thread-2
    Running Thread-1
    Thread: Thread-1, 10
    Running Thread-2
    Thread: Thread-2, 10
    Thread: Thread-1, 9
    Thread: Thread-2, 9
    Thread: Thread-1, 8
    Thread: Thread-2, 8
    Thread: Thread-1, 7
    Thread: Thread-2, 7
    Suspending First Thread
    Thread: Thread-2, 6
    Thread: Thread-2, 5
    Thread: Thread-2, 4
    Resuming First Thread
    Suspending thread Two
    Thread: Thread-1, 6
    Thread: Thread-1, 5
    Thread: Thread-1, 4
    Thread: Thread-1, 3
    Resuming thread Two
    Thread: Thread-2, 3
    Waiting for threads to finish.
    Thread: Thread-1, 2
    Thread: Thread-2, 2
    Thread: Thread-1, 1
    Thread: Thread-2, 1
    Thread Thread-1 exiting.
    Thread Thread-2 exiting.
    Main thread exiting.


    WRAPPER CLASSES


    In Java, these are the classes which will respective primitive datatypes to achieve boxing and unboxing.
    What is boxing?
    The process of converting primitive datatypes into non-primitive datatype is called as boxing.
  • In java, to achieve boxing, we will use valueof method
  • 
                                          (or)
    
    
    The wrapper class in Java provides the mechanism to convert primitive into object and object into primitive.
    Since J2SE 5.0, autoboxing and unboxing feature convert primitives into objects and objects into primitives automatically. The automatic conversion of primitive into an object is known as autoboxing and vice-versa unboxing.

    Use of Wrapper classes in Java :
    Java is an object-oriented programming language, so we need to deal with objects many times like in Collections, Serialization, Synchronization, etc. Let us see the different scenarios, where we need to use the wrapper classes.
  • Change the value in Method : Java supports only call by value. So, if we pass a primitive value, it will not change the original value. But, if we convert the primitive value in an object, it will change the original value.
  • Serialization : We need to convert the objects into streams to perform the serialization. If we have a primitive value, we can convert it in objects through the wrapper classes.
  • Synchronization : Java synchronization works with objects in Multithreading.
  • java.util package : The java.util package provides the utility classes to deal with objects.
  • Collection Framework : Java collection framework works with objects only. All classes of the collection framework (ArrayList, LinkedList, Vector, HashSet, LinkedHashSet, TreeSet, PriorityQueue, ArrayDeque, etc.) deal with objects only.

  • The eight classes of the java.lang package are known as wrapper classes in Java. The list of eight wrapper classes are given below:
    
          S.No      Primitive Type	    Wrapper class
         ------    ---------------   -----------------
           1         boolean              Boolean
           2         char                 Character
           3         byte                 Byte
           4         short                Short
           5         int                  Integer
           6         long                 Long
           7         float                Float
           8         double               Double
    
    
    Autoboxing :
    The automatic conversion of primitive data type into its corresponding wrapper class is known as autoboxing, for example, byte to Byte, char to Character, int to Integer, long to Long, float to Float, boolean to Boolean, double to Double, and short to Short.
    Since Java 5, we do not need to use the valueOf() method of wrapper classes to convert the primitive into objects.
    
      //Java program to convert primitive into objects  
      //Autoboxing example of int to Integer  
      public class WrapperExample1{  
        public static void main(String args[]){  
        //Converting int into Integer  
        int a=20;  
        Integer i=Integer.valueOf(a);//converting int into Integer explicitly  
        Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally  
        System.out.println(a+" "+i+" "+j);  
        }
      }
    
    
    Output :
    20 20 20

    Unboxing :
    The automatic conversion of wrapper type into its corresponding primitive type is known as unboxing. It is the reverse process of autoboxing. Since Java 5, we do not need to use the intValue() method of wrapper classes to convert the wrapper type into primitives.
    
      //Java program to convert object into primitives  
      //Unboxing example of Integer to int  
      public class WrapperExample2{    
        public static void main(String args[]){    
        //Converting Integer to int    
        Integer a=new Integer(3);    
        int i=a.intValue();//converting Integer to int explicitly  
        int j=a;//unboxing, now compiler will write a.intValue() internally    
            
        System.out.println(a+" "+i+" "+j);    
        }
      }    
    
    
    Output :
    3 3 3

    Now we are going to example for the wrapper classes
    
      //Java Program to convert all primitives into its corresponding   
      //wrapper objects and vice-versa  
      public class WrapperExample3{  
        public static void main(String args[]){  
        byte b=10;  
        short s=20;  
        int i=30;  
        long l=40;  
        float f=50.0F;  
        double d=60.0D;  
        char c='a';  
        boolean b2=true;  
          
        //Autoboxing: Converting primitives into objects  
        Byte byteobj=b;  
        Short shortobj=s;  
        Integer intobj=i;  
        Long longobj=l;  
        Float floatobj=f;  
        Double doubleobj=d;  
        Character charobj=c;  
        Boolean boolobj=b2;  
          
        //Printing objects  
        System.out.println("---Printing object values---");  
        System.out.println("Byte object: "+byteobj);  
        System.out.println("Short object: "+shortobj);  
        System.out.println("Integer object: "+intobj);  
        System.out.println("Long object: "+longobj);  
        System.out.println("Float object: "+floatobj);  
        System.out.println("Double object: "+doubleobj);  
        System.out.println("Character object: "+charobj);  
        System.out.println("Boolean object: "+boolobj);  
          
        //Unboxing: Converting Objects to Primitives  
        byte bytevalue=byteobj;  
        short shortvalue=shortobj;  
        int intvalue=intobj;  
        long longvalue=longobj;  
        float floatvalue=floatobj;  
        double doublevalue=doubleobj;  
        char charvalue=charobj;  
        boolean boolvalue=boolobj;  
          
        //Printing primitives  
        System.out.println("---Printing primitive values---");  
        System.out.println("byte value: "+bytevalue);  
        System.out.println("short value: "+shortvalue);  
        System.out.println("int value: "+intvalue);  
        System.out.println("long value: "+longvalue);  
        System.out.println("float value: "+floatvalue);  
        System.out.println("double value: "+doublevalue);  
        System.out.println("char value: "+charvalue);  
        System.out.println("boolean value: "+boolvalue);  
        }
      }  
    
    
    Output :
    ---Printing object values---
    Byte object: 10
    Short object: 20
    Integer object: 30
    Long object: 40
    Float object: 50.0
    Double object: 60.0
    Character object: a
    Boolean object: true
    ---Printing primitive values---
    byte value: 10
    short value: 20
    int value: 30
    long value: 40
    float value: 50.0
    double value: 60.0
    char value: a
    boolean value: true



    PARSING


    In Java, we can see parsing where the process of converting given string into primitive datatypes is called as parsing. In Order, to achieve parsing we should use parse() which is present in the given wrapper classes.
    We can see the use of following declaration for parsing :
      S.No   Wrapper      parse Method        Example Statement
    
      1     Integer       parseInt(String)      int x = Integer.parseInt(“100”);
    
      2     Short         parseShort(String)    short x = Short.parseShort(“100”);
    
      3     Long          parseLong(String)     long x = Long.parseLong(“100”);
    
      4     Byte          parseByte(String)     byte x = Byte.parseByte(“100”);
    
      5     Float         parseByte(String)     float x = Float.parseFloat (“19.95”);
    
      6     Double        parseByte(String)     double x = Double.parseDouble (“19.95”);
    
      7     Boolean       parseBoolean          boolean x = Boolean.parseBoolean
    
    
    Note : The runtime string should be a number format, otherwise we will get NumberFormatException during runtime.

    Eg:
      public Class Parsing{
        public static void main(String [] args){
          String s="10";
          //byte <--- String
          byte res1=Byte.parseByte(s);
          System.out.println("String : " + s);
          System.out.println("byte primitive datatype : " + res1);
          //short <--- String
          short res2=Short.parseShort(s);
          System.out.println("Short primitive datatype :" + res2)
        }
      }
    
    
    Output :
    String : 10
    byte primitive datatype : 10
    Short primitive datatype :10

    (Core Java - Swing)