Java Reference
In-Depth Information
Comparing Objects
We've seen that primitive types and reference types differ significantly in the way
they are assigned to variables, passed to methods, and copied. The types also differ
in the way they are compared for equality. When used with primitive values, the
equality operator ( == ) simply tests whether two values are identical (i.e., whether
they have exactly the same bits). With reference types, however, == compares refer‐
ences, not actual objects. In other words, == tests whether two references refer to the
same object; it does not test whether two objects have the same content. Here's an
a x
String letter = "o" ;
String s = "hello" ; // These two String objects
String t = "hell" + letter ; // contain exactly the same text.
if ( s == t ) System . out . println ( "equal" ); // But they are not equal!
byte [] a = { 1 , 2 , 3 };
// A copy with identical content.
byte [] b = ( byte []) a . clone ();
if ( a == b ) System . out . println ( "equal" ); // But they are not equal!
When working with reference types, there are two kinds of equality: equality of ref‐
erence and equality of object. It is important to distinguish between these two kinds
of equality. One way to do this is to use the word “identical” when talking about
equality of references and the word “equal” when talking about two distinct objects
that have the same content. To test two nonidentical objects for equality, pass one of
them to the equals() method of the other:
String letter = "o" ;
String s = "hello" ; // These two String objects
String t = "hell" + letter ; // contain exactly the same text.
if ( s . equals ( t )) { // And the equals() method
System . out . println ( "equal" ); // tells us so.
All objects inherit an equals() method (from Object ), but the default implementa‐
tion simply uses == to test for identity of references, not equality of content. A class
that wants to allow objects to be compared for equality can define its own version of
the equals() method. Our Point class does not do this, but the String class does,
as indicated in the code example. You can call the equals() method on an array, but
it is the same as using the == operator, because arrays always inherit the default
equals() method that compares references rather than array content. You can com‐
pare arrays for equality with the convenience method java.util.Arrays.equals() .
Boxing and Unboxing Conversions
Primitive types and reference types behave quite differently. It is sometimes useful
to treat primitive values as objects, and for this reason, the Java platform includes
wrapper classes for each of the primitive types. Boolean , Byte , Short , Character ,
Integer , Long , Float , and Double are immutable, final classes whose instances each
Search WWH ::

Custom Search