Java Reference
In-Depth Information
Line 9: y = 24
Line 10: The value of 2 * num1 + num2 = 32
Line 11: The value of x * num2 - num1 = 184
Line 12: The value of num1 <= num2 is true
Line 13: The value of 2 * num1 <= x is false
Line 14: The value of 2 * num1 >= num2 is true
For the most part, the preceding sample run is self-explanatory. Let us look at some of the
statements. The statement in Line 3 autoboxes the value 8 into an Integer object and
stores the address of that object into the reference variable num1 . The meaning of the
statement in Line 4 is similar.
The statement in Line 6 unboxes the value of the object to which num1 points, adds 4 to
that value, and stores the result in x . Similarly, the statement in Line 8 unboxes the values
of objects pointed to by num1 and num2 , adds the values, and stores the result in y .
The statement in Line 12 unboxes the values of the objects pointed by num1 and num2 ,
and then compares the values using the relational operator < ¼ . (Note that we are not
using the operator ¼¼ , so autoboxing occurs here.)
The class Double also has methods similar to the methods shown in Table 6-6. A program
that illustrates the autoboxing and -unboxing of double values into Double objects can be
found with the Additional Student Files at www.cengagebrain.com. The program is named
DoubleClassExample.java . However, to compare the values, for equality, of the wrapper
classes objects, you should use the method equals . See the following example.
EXAMPLE 6-5
//Program illustrating how the operator == and the
//method equals works with Double objects.
public class DoubleClassMethodEquals
{
public static void main(String[] args)
{
Double num1, num2;
//Line 1
num1 = 2567.58;
//Line 2
num2 = 2567.58;
//Line 3
System.out.println("Line 4: num1 = " + num1
+ ", num2 = " + num2);
//Line 4
System.out.println("Line 5: The value of "
+ "num1.equals(num2) is "
+ num1.equals(num2));
//Line 5
Search WWH ::




Custom Search