Java Boxing and Widening

Java Programming Java8Java Technologies Object Oriented Programming

Java automatically does a conversion of primitive data types into their wrapper classes when assigned. It is called boxing.

public class MyFirstJavaProgram {
   public static void main(String []args) {
      Integer testData = 10; //boxing
      System.out.println(testData);
   }
}

Whereas when we assigned a wrapper object to primitive data type, it is called unboxing.

public class MyFirstJavaProgram {
   public static void main(String []args) {
      Integer testData = new Integer(10);
      int a = testData; // unboxing
      System.out.println(a);
   }
}

Widening refers to passing a lower size data type like short to a higher size data type like int.

public class MyFirstJavaProgram {
   public static void main(String []args) {
      short a = 10;
      print(a);//widening
   }
   private static void print(int a){
       System.out.println(a);
   }
}
raja
Published on 22-Jan-2018 10:17:25
Advertisements