Java Reference
In-Depth Information
Testing for Equality Using Autoboxing
With the introduction of autoboxing, your code can essentially ignore the distinction
between a primitive type and its wrapper. One situation where you might need to make
the distinction is when you test for equality. When using = =, wrapped types are not
unboxed. For example, see if you can determine the output of the following code:
13. Integer one = new Integer(128);
14. Integer two = new Integer(128);
15. if(one == two)
16. System.out.println(“true”);
17. else
18. System.out.println(“false”);
19.
20. int three = 128;
21. if(one == three)
22. System.out.println(“true”);
23. else
24. System.out.println(“false”);
Line 15 is comparing two references that do not point to the same object, so the result is
false . On line 21, the Integer is unboxed to an int , so the comparison is made between
two equal int s, resulting in true . The output of the previous code is
false
true
Autoboxing and unboxing eliminates the tedious code of instantiating wrapper objects
using the new keyword and unwrapping the primitive types using the corresponding value
methods. Autoboxing is a new feature of Java, so there will certainly be a question or two
on the exam about it.
Strings
A string is a sequence of characters. Strings are not primitive types in Java; they are
objects. The Java API has three classes to represent string objects, each one declared in
the java.lang package: String , StringBuilder , and StringBuffer . The exam objectives
Search WWH ::




Custom Search