December 22, 2009

Equality in Java

One of the few methods that comes with all Java classes is equals(). By convention, it tests for MEANINGFUL equality. Therefore, this code


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

boolean test1 = i1.equals(i2);
boolean test2 = i2.equals(i1);


should produce true for both calls.

On the other hand, the equality operator (==) tests to see whether two references actually point at the same object. It "simply looks at the bits in the variable, and they're either identical or they're not" -K. Sierra & B. Bates, SCJP Sun Certified Programmer for Java 6 Study Guide (Exam 310-065). So, the values in the previous example would be false, but this code:


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

boolean test = i1 == i2;


will produce true.

No comments:

Post a Comment