Java Reference
In-Depth Information
Self-Test Exercises
14. What values are returned by each of the following?
Math.round(3.2), Math.round(3.6),
Math.floor(3.2), Math.floor(3.6),
Math.ceil(3.2), and Math.ceil(3.6).
15. Suppose answer is a variable of type double. Write an assignment statement to
assign Math.round(answer) to the int variable roundedAnswer .
16. Suppose n is of type int and m is of type long . What is the type of the value
returned by Math.min(n, m )? Is it int or long ?
Wrapper Classes
Java treats the primitive types, such as int and double , differently from the class types,
such as the class String and the programmer-defined classes. For example, later in this
chapter you will see that an argument to a method is treated differently depending on
whether the argument is of a primitive or class type. At times, you may find yourself in
a situation where you want to use a value of a primitive type but you want or need the
value to be an object of a class type. Wrapper classes provide a class type correspond-
ing to each of the primitive types so that you can have an object of a class type that
behaves somewhat like its corresponding value of a primitive type.
To convert a value of a primitive type to an “equivalent” value of a class type, you
create an object of the corresponding wrapper class using the primitive type value as an
argument to the wrapper class constructor. The wrapper class for the primitive type
int is the predefined class Integer . If you want to convert an int value, such as 42 , to
an object of type Integer , you can do so as follows:
wrapper class
Integer class
Integer integerObject = new Integer(42);
The variable integerObject now names an object of the class Integer that corre-
sponds to the int value 42 . (The object integerObject does, in fact, have the int
value 42 stored in an instance variable of the object integerObject .) This process of
going from a value of a primitive type to an object of its wrapper class is sometimes
called boxing , and as you will see in the next subsection, you can let Java automati-
cally do all the work of boxing for you.
To go in the reverse direction, from an object of type Integer to the corresponding
int value, you can do the following:
boxing
int i = integerObject.intValue();
Search WWH ::




Custom Search