Java Reference
In-Depth Information
To compare the values of two Integer objects, you can use the method compareTo ,
described in Table 6-6. If you want to compare the values of two Integer objects only
for equality, then you can use the method equals .
Suppose you have the following statements:
Integer num1 = 24;
Integer num2 = 35;
Now consider the following statements:
if (num1.equals(num2))
System.out.println("The values of the "
+ "objects num1 and num2 "
+ "are the same.");
else
System.out.println("The values of the "
+ "objects num1 and num2 "
+ "are not the same.");
The expression in the if statement determines if the value of the object num1 , which is
24 , is the same as the value of the object num2 , which is 35 . Next, consider the following
statements:
if (num1 == num2)
System.out.println("Both num1 and num2 "
+ "point to the same "
+ "object.");
else
System.out.println("num1 and num2 "
+ "do not point to the "
+ "same object.");
It follows that when the operator ¼¼ is used with reference variables of the Integer
type, it compares whether the objects point to the same object. Therefore, if you want to
compare the values of two Integer objects, then you should use the method equals of
the class Integer . On the other hand, if you want to determine whether two reference
variables of Integer type points to the same Integer object, then you should use the
operator ¼¼ .
The preceding discussion of comparing Integer objects also applies to other wrapper
classes' objects.
Autoboxing and -unboxing of primitive types is a new feature of Java and is available in
Java 5.0 and higher versions. It automatically boxes and unboxes primitive type values
into appropriate objects. For example, as explained above, int values can be automati-
cally boxed and unboxed into Integer objects. Example 6-4 further illustrates autobox-
ing and auto-unboxing of Integer objects.
 
Search WWH ::




Custom Search