Java Reference
In-Depth Information
Note that this code demonstrates the common Java technique of executing
several commands in a single line. The line executes from left to right.
First, the valueOf() method returns a Double object, which then has its
doubleValue() method called.
We saw here how to convert a string representation of a number to a primitive
type value. Going in the other direction, you can convert a primitive type to
a string in several ways. The String class provides several overloaded static
valueOf() methods as well as the overloaded “+ operator. For example, in
the following code we first convert numerical values to strings using the String
class's valueOf() methods (there is one for each primitive type) and then using
the “+ operator:
double d = 5.0;
int i = 1;
String dStr = String.valueOf (d);
String iStr = String.valueOf (i);
String aStr ="d ="+ dStr;
String bStr ="i ="+ iStr;
Now the dStr and iStr variables reference the strings “5.0 and “1 , respec-
tively, while aStr references “d = 5.0 and bStr references “i = 1 .We
discuss more about strings and string helper classes in Chapter 10.
3.7.2 Autoboxing and unboxing
In all versions of Java prior to J2SE 5.0, conversions between wrapper classes and
the corresponding primitive types (and vice versa) are somewhat messy, as seen
above. As another example, creating a Float object from a float primitive is
straightforward:
float primitive - float = 3.0f;
Float wrapper - float = new Float (primitive - float);
Going in the other direction, however, is not quite as simple. It requires explicitly
calling the floatValue() method on the Float object:
float primitive - float = wrapper - float.floatValue ();
In J2SE 5.0, the code to create the wrapper object can be simplified to
Float wrapper - float = primitive - float;
Here, the “wrapping” is done automatically! There is no need to explicitly call the
Float constructor. This “wrapping” is called “autoboxing” in the sense that the
primitive value is automatically “boxed up” into the wrapper object. Autoboxing
is available for all the primitive/wrapper types.
 
Search WWH ::




Custom Search