Testing Object Equality
It is a source of great confusion to novice programmers that Java has two ways of thinking about the equality of objects. When used with object references, the == operator returns true only if both references are to the same object. This is illustrated in the following code fragment in which we create and compare some Integer object references:
1. Integer x1 = new Integer( 5 ) ; 2. Integer x2 = x1 ; 3. Integer x3 = new Integer( 5 ) ; 4. if( x1 == x2 ) System.out.println("x1 eq x2" ); 5. if( x2 == x3 ) System.out.println("x2 eq x3" );
Executing this code will print only "x1 eq x2" because both variables refer to the same object. To test for equality of content, you have to use a method that can compare the content of ...
Get Java 2™ Programmer Exam Cram™ 2 (Exam CX-310-035) now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.