Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

Converting Objects and Simple Variables 131

That program would have been more useful if it took a number submitted
by a user and displayed its square root. This requires conversion from a
string to an integer. All command-line arguments are stored as elements of
a Stringarray, so you must cast them to numbers before using them in
mathematical expressions.


To create an integer value based on the contents of a string, the
Integer.parseInt()method is called with the string as the only argu-
ment, as in Line 5:


number = Integer.parseInt(args[0]);


The args[0]array element holds the first command-line argument submit-
ted when the application is run. When the program was run with “169” as
an argument, the string “169” was cast to the int169.


Autoboxing and Unboxing


Every one of the basic data types in Java has a corresponding object class:
boolean(Booleanclass), byte(Byte), char(Character), double(Double),
float(Float), int(Integer), long(Long), and short(Short).


For each of these pairs, the information has identical value. The only differ-
ence between them is the format the value takes. An integer value such as
413 could be represented by either an intor the Integerclass.


Java’s autoboxing and unboxing capabilities make it possible to use the
basic data type and object forms of a value interchangeably.


Autoboxing casts a simple variable value to the corresponding class.


Unboxing casts an object to the corresponding simple value.


These features work behind the scenes, assuring that when you are expect-
ing a simple data type like float, an object is converted to the matching
data type with the same value. When you’re expecting an object like Float,
a data type is converted to an object as necessary.


FIGURE 10.3
The output of the NewRoot
program.
Free download pdf