Java Reference
In-Depth Information
Autoboxing
Autoboxing
is the automatic conversion between a primitive value and a cor-
responding wrapper object. For example, in the following code, an
int
value is
assigned to an
Integer
object reference variable:
Integer obj1;
int
num1 = 69;
obj1 = num1;
// automatically creates an Integer object
The reverse conversion, called unboxing, also occurs automatically when needed.
For example:
Integer obj2 =
new
Integer(69);
int
num2;
num2 = obj2;
// automatically extracts the int value
Assignments between primitive types and object types
are generally incompatible. The ability to autobox occurs
only between primitive types and corresponding wrapper
classes. In any other case, attempting to assign a primitive
value to an object reference variable, or vice versa, will
cause a compile-time error.
KEY CONCEPT
Autoboxing provides automatic con-
versions between primitive values
and corresponding wrapper objects.
SELF-REVIEW QUESTIONS
(see answers in Appendix N)
SR 3.32
How can we represent a primitive value as an object?
SR 3.33
What wrapper classes correspond to each of the following primitive
types:
byte,
int,
double,
char
,
and
boolean
?
SR 3.34
Suppose that an
int
variable named
number
has been declared and ini-
tialized and an
Integer
variable named
holdNumber
has been declared.
Show two approaches in Java for having
holdNumber
represent the
value stored in
number
.
SR 3.35
Write a statement that prints out the largest possible
int
value.
3.9
Components and Containers
In the Graphics Track sections of Chapter 2 we introduced the Java capabilities
to draw shapes using the
Graphics
and
Color
classes from the Java standard
class library. We also defined the concept of an applet, a Java program that is
intended to be embedded in a Web page and executed through a browser. Recall
that, in contrast to applets, Java applications are stand-alone programs that are
not executed through the Web.
Search WWH ::
Custom Search