Integer i3 = 10;
Integer i4 = 10;
if(i3 == i4) System.out.println("same object");
if(i3.equals(i4)) System.out.println("meaningfully equal");
This example produces the output:
same object
meaningfully equal
Integer i3 = 128;
Integer i4 = 128;
if(i3 == i4) System.out.println("same object");
if(i3.equals(i4)) System.out.println("meaningfully equal");
This example produces the output:
meaningfully equal
SCJP 5.0, SCWCD
SCJP 5.0, SCWCD
The String pool is filled when classes are loaded and when Strings are created with String s1 = "Hello"; ...it's also my guess.
"If someone asks you to do something you don't know how to, don't tell I don't know, tell I can learn instead." - Myself
Plz somebody throw some light on pools and how it works in java.
SCJP 5.0, SCWCD
Together, we will win!
Originally posted by Huifen Lu:
Agree with Srilatha that the result is depending on JVM. I have tested the code on my machine and the result for i3==i4 is false. Seems the data ranger doesn't matter that much.
By the way,
Integer i3 = 10;
Integer i4 = 10;
won't go through compiler, they should be declared as
Integer i3 = new Integer(10);
Integer i4 = new Integer(10);
Pls correct me if I am wrong.
Thanks,
Fen
Together, we will win!
Here i3==i4 will be true sometime and false sometime depending on JVM .IN EXAM it is always false because it is not consistent through all JVM's
Integer i4 = 10 ;// gives you a compiler error
Integer i3 = new Integer(10); Integer i4 = new Integer(10); i3 = i4; if(i3 == i4) System.out.println("same object"); if(i3.equals(i4)) System.out.println("meaningfully equal");
Integer i3 = 10;
Integer i4 = 10;
if(i3 == i4) System.out.println("same object");
if(i3.equals(i4)) System.out.println("meaningfully equal");
This example produces the output:
same object
meaningfully equal
And what happen is if you allocate the number within range -128 to 127 two different object reference point to same object in heap memory ie i3 an i4 are pointing to one object in heap memory. But if you change the value beyond this range they start pointing two different objects in heap memory.
Cannot understand why???
SCJP 5.0, SCWCD
Da Clone in programming world
Consider Paul's rocket mass heater. |