Search code examples
javadata-structuresboxingunboxing

Java DataStructures question boxing/unboxing


I am studying for a data structures exam tommorrow and need to know what lines in the following code are correct and which aren't and why

Object  obj = new Integer(42);
Integer iObj = 43;
iObj = obj;

Solution

  • Answer to your question is here under:

     Object  obj = new Integer(42); //auto boxing  // true
     Integer iObj = 43; //direct intialization   //true
     iObj = obj  // false
     iObj = (Integer) obj; // manual boxing 
    

    iObj = obj is false because obj is a reference to the Object and iObj is of Interger. Object is the parent of all and so Integer type iObj is child of obj and hence false.

     In short, child can be auto- boxed to parent but the vice-versa is not possible