Saturday, June 14, 2014

Java - autoboxing and unboxing - my interview notes

this is conversion from primitive types to the java wrapper classes made to elegantly handle the primitive data types

e.g.

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes.

e.g. converting an int to an Integer, a double to a Double, and so on.

If the conversion goes the other way, this is called unboxing.

Here is the simplest example of autoboxing:
Character ch = 'a';


 The Java compiler applies autoboxing when a primitive value is:
  • Passed as a parameter to a method that expects an object of the corresponding wrapper class.
  • Assigned to a variable of the corresponding wrapper cla
Converting an object of a wrapper type (Integer) to its corresponding primitive (int) value is called unboxing. The Java compiler applies unboxing when an object of a wrapper class is:
  • Passed as a parameter to a method that expects a value of the corresponding primitive type.
  • Assigned to a variable of the corresponding primitive type.

Here is the table as declared by oracle

Primitive typeWrapper class
booleanBoolean
byteByte
charCharacter
floatFloat
intInteger
longLong
shortShort
doubleDouble


No comments:

Post a Comment