Page 1 of 1
How's it work?
Posted: Tue Jun 27, 2006 4:32 am
by Roby
Can someone explain to me how Java examine this code:
Code: Select all
public class Everything
{
public static void main( String [] args )
{
Integer a = new Integer(5);
Integer b = new Integer(5);
if ( a == b )
System.out.println( "same" );
}
}
Why doesn't it worked? Thanx in advance

Posted: Tue Jun 27, 2006 1:17 pm
by Darko
evaluates if both a and b are referencing the same object. In this case they are not. You probably want to use
But, in Java 1.5 you can do this:
Code: Select all
Integer a = 5;
Integer b = 5;
if(a==b)...
Same thing has always been the case with Strings - if you declare them using literals like in the last example, a==b will evaluate to true - because of the way JVM stores the literals. I guess now it does it the same way with all the primitives wrapped into an object.
Posted: Thu Jun 29, 2006 4:03 am
by Roby
So, since java 1.5, the primitive which wrapped into object can be compared using that method...
OK, thanx Darco, just a bit confusing

Posted: Thu Jun 29, 2006 7:46 am
by impulser
hey how do the JVM handle the code for other java versions . Since, i think we won't upgrade the JVM versions .. as it is ported into the OS..
Hey Darko , can you be specific about the way JVM handles it..
Thanks ...

Posted: Thu Jun 29, 2006 6:15 pm
by Darko
Well, I'm not 100% sure, but this is how I understand it:
Code: Select all
Integer a = new Integer(5); // JVM allocates memory for Integer object and a points to it
Integer b = new Integer(5); // same as above
if(a==b)... // JVM checks if both a and b point to the same object (they don't)
if(a.equals(b))... // JVM checks if two Integers referenced (did I say "pointer" up there?:)) by a and b are equal according to the equals() implementation - if it weren't overridden in Integer class, it would have the same effect as a==b, but in this case it translates to
if(a.intValue() == b.intValue())...
Now, in the case of Strings:
Code: Select all
String a = new String("abc");
String b = new String("abc");
// this is exactly the same as with Integer example above
a==b - false
a.equals(b) - true
Now the fun part, if you do it this way (you could always do this with Strings):
Code: Select all
String a = "abc"; //JVM checks its pool of literal strings for "abc", if it is there, a points to it, if not, JVM adds "abc" to the pool and a points to it
String b = "abc"; // same as the above
a==b is true! (so is a.equals(b))
I hope that's what you wanted to know.
