Java Program to wrap a Primitive DataType in a Wrapper Object

Java 8Object Oriented ProgrammingProgramming

Every Java primitive data type has a class dedicated to it. These classes wrap the primitive data type into an object of that class. Therefore, it is known as wrapper classes.

The following is the program that displays a Primitive DataType in a Wrapper Object.

Example

 Live Demo

public class Demo {
   public static void main(String[] args) {
      Boolean myBoolean = new Boolean(true);
      boolean val1 = myBoolean.booleanValue();
      System.out.println(val1);

      Character myChar = new Character('a');
      char val2 = myChar.charValue();
      System.out.println(val2);

      Short myShort = new Short((short) 654);
      short val3 = myShort.shortValue();
      System.out.println(val3);

      Integer myInt = new Integer(878);
      int val4 = myInt.intValue();
      System.out.println(val4);

      Long myLong = new Long(956L);
      long val5 = myLong.longValue();
      System.out.println(val5);

      Float myFloat = new Float(10.4F);
      float val6 = myFloat.floatValue();
      System.out.println(val6);

      Double myDouble = new Double(12.3D);
      double val7 = myDouble.doubleValue();
      System.out.println(val7);
   }
}

Output

True
a
654
878
956
10.4
12.3

In the above program, we have taken every data type one by one. An example can be seen is for boolean. Our wrapper is −

Boolean myBoolean = new Boolean(true);

Now, the Primitive DataType is wrapped in a Wrapper Object

boolean val1 = myBoolean.booleanValue();
raja
Published on 13-Nov-2018 07:38:45
Advertisements