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" );
}
}
![:)](./images/smilies/icon_smile.gif)
Moderator: Board moderators
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" );
}
}
Code: Select all
a==b
Code: Select all
a.equals(b)
Code: Select all
Integer a = 5;
Integer b = 5;
if(a==b)...
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())...
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
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))