ReferenceToIntegerConversion
DRAFT

Misconception:

You can get the address of an object by converting an object reference to an int, and you can convert the address of an object, given as an int, to an object reference. E.g., Object o = (Object)12345678; or int i = (int)new Object();.

Incorrect

One can cast between references and ints

Correct

One cannot cast between references and ints

Correction
Here is what's right.

Java is a type-safe language. An object reference is opaque; there is no way to convert it to an integer address.

However, Java allows auto-boxing and auto-unboxing. Which means that Java automatically can e.g., convert an int into an Integer and vice versa. This doesn’t have anything to do with the object’s address, however!

So Integer i = 5; is correct. And given that Object is a supertype of Integer, even Object o = 5; is correct, and Object o = (Object)5; likewise.

Conversely, int i = new Integer(5); is correct, and int i = (int)new Integer(5);' is correct. However, int i = (int)new Object(); is not correct, because Object is not a subtype of Integer and thus new Object() can’t possibly be cast into an Integer object for unboxing into an int.

Stay up-to-date

Follow us on  twitter to hear about new misconceptions.