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;
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;
HelloWorld.java:19: error: incompatible types: Object cannot be converted to Integer
iObj = obj;
^
1 error
The above fails because the compile time type of iObj and obj are not matching. This is a signature of strongly typed languages. Similar code in Javascript would work fine.
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
All this lines are correct First you crwate object and tgen you create the integer and assing the value to that integer object This lines of code is totally correct