-2

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;
Preston
  • 3
  • 3
  • 2
    What do *you* think the answer is, and why? You are the one who is taking the exam, there is little point in just telling you. – Andy Turner Nov 06 '18 at 08:35

3 Answers3

1
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.

Sid
  • 4,893
  • 14
  • 55
  • 110
  • Ok I thought that line wouldn't work. So for it to work you would have to typecast it, something like this? iObj = (int)obj; – Preston Nov 06 '18 at 08:35
0

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
Jayanth
  • 746
  • 6
  • 17
0

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