There are 2 topics here, namely shallow vs. deep comparisons and autoboxing.
shallow vs. deep comparisons (== vs. equals):
!= and == represent shallow comparison. In order for == to return true, the 2 object references must reference the object found in the same memory location.
In order for != to return true, the 2 object references must reference objects found in different memory locations.
!object.equal() and !object.equal() represent deap comparison. These methods of comarison do not care about the the location of the objects involved in the comparison, but rather the contents there of.
Autoboxing:
To gain a better understanding of autoboxing read this:
http://today.java.net/pub/a/today/2005/03/24/autoboxing.html. The supports what Keith Lynn was stating.
The following class might help you Run the following class
public class
test {
public test() {
}
public static void main (
String[] args)
{
// String comarisons included so you can see comparisons using String objects
String s1="hello";
String s2="hello";
String s3= new String("hello");
if(s1 != s2)System.out.println("s1 not referencing same string as s2");// returns false
if(s1 == s2)System.out.println("s1 referencing same string as s2");// returns true
if(s1.equals(s2))System.out.println("equal str content in s1 and s2");// returns true
if(s1 != s3)System.out.println("s1 not referencing same string as s3");// returns true
if(s1.equals(s3))System.out.println("equal str content in s1 and s3");// returns true
// mutable value comparison because value is greater than 127
Integer i1=1000;
Integer i2=1000;
if(i1 != i2)System.out.println("i1 and i2 reference different objects");// returns true because they are different objects
if(i1 == i2)System.out.println("i1 and i2 reference same object");// returns false
if(i1.equals(i2))System.out.println("i1 and i2 contents are the same");// returns true
// immutable value comparison because value is between -128 and 127
Integer i5 = 100;
Integer i6 = 100;
if(i5 != i6)System.out.println("i5 and i6 reference different objects");// returns false
if(i5 == i6)System.out.println("i5 and i6 reference same object");// returns true
if(i5.equals(i6))System.out.println("i5 and i6 contents are the same");// returns true
// immutable, but reference different objects
Integer i7 = 100;
Integer i8 = new Integer(100);
if (i7!=i8) System.out.println("i7 and i8 reference different objects");// returns true
if (i7==i8) System.out.println("i7 and i8 reference same object");// returns false
if (i7.equals(i8)) System.out.println("i7 and i8 contents are the same");// returns true
}
}