Saturday 7 April 2012

Convert Wrapper objects to Primitive types in Java

When you need to convert the value of a wrapper object to a primitive, use one of the many xxxValue() methods. Each of the six numeric wrapper classes (Byte,Short,Integer,Long,Float and Double) has the following six methods, so that any numeric wrapper can be converted to any primitive numeric type.
  • byte byteValue()
  • short shortValue()
  • int intValue()
  • long longValue()
  • float floatValue()
  • double doubleValue()
The Boolean and Character wrapper classes has boolean booleanValue() and char characterValue() methods respectively.

For example:


        Double d = 3.14;
        byte b = d.byteValue();
        short s = d.shortValue();
        int i = d.intValue();
        long l = d.longValue();
        float f = d.floatValue();
        double d1 = d.doubleValue();

Wrapper objects to Primitive types using Auto-unboxing

 

Java 5 and above supports automatic conversion of wrapper objects (Integer, Float, Double etc.) to their primitive types(int, float, double,....) in assignments and method and constructor invocations. This conversion is known as Auto-unboxing.

Please visit Autoboxing and Unboxing in Java to learn more about this topic.

For example :

        Float f = 3.14f; // Autoboxing

        float f_primitive = f; //Auto-unboxing.

        double d_primitive = f; //Auto-unboxing.Widening from Float to double
      
        int i_primitive = f;  /*Compilation error.Narrowing from Float to int
                                        is not possible with Auto-unboxing*/


Notice that using auto-unboxing, the wrapper objects can be converted to their associated primitive types and widen primitive types.But auto-unboxing to narrow primitive types is not possible, causes compilation error.It this scenario you can only use above mentioned xxxValue() method.

2 comments:

  1. very interesting information tks.

    ReplyDelete

  2. Thanks, this is generally helpful.
    Still, I followed step-by-step your method in this Java online training
    Java online course

    ReplyDelete