Paritosh Ahuja Paritosh Ahuja - 1 year ago 70
Java Question

Understanding the code output, Java Integer class

Integer i1 = new Integer(123);
Integer i2 = i1;

if (i1 == i2)
System.out.println("equal 1");
if (i1 == i2)
System.out.println("equal 2");

Prints equal 1, at first both refer to same memory location. What happened after i2++? I know value got incremented to 124 but weren't they pointing to same memory location?

P.S : Please don't bash me for asking this silly question :)

Answer Source

The Java boxed classes don't work like usual reference objects.. if they would, your example would change the 'global' 123 to 124.

Not a Java guru, but if I had to guess between the assignment i2 = i1 creating a new instance or the incrementation i2++ changing i2 (since underneath it is a store operation) I would choose the latter. Anyway, this probably doesn't even matter for most use cases.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download