Java Reference
In-Depth Information
float f = (float)3.0;
float f = 3;
The same applies when storing an
int
into a
short
,
char
, or
byte
:
public
public static
static
void
void
main
(
String
[]
argv
) {
int
int
i
;
double
double
j
=
2.75
;
i
=
j
;
// EXPECT COMPILE ERROR
i
= (
int
int
)
j
;
// with cast; i gets 2
System
.
out
.
println
(
"i ="
+
i
);
byte
byte
b
;
b
=
i
;
// EXPECT COMPILE ERROR
b
= (
byte
byte
)
i
;
// with cast, i gets 2
System
.
out
.
println
(
"b ="
+
b
);
}
The lines marked EXPECT COMPILE ERROR do not compile unless either commented out
or changed to be correct. The lines marked “with cast” show the correct forms.
Converting Numbers to Objects and Vice Versa
Problem
You need to convert numbers to objects and objects to numbers.
Solution
Use the Object Wrapper classes listed in
Table 5-1
at the beginning of this chapter.
Discussion
Often you have a primitive number and you need to pass it into a method where an
Object
is
required, or vice versa. Long ago you had to invoke the conversion routines that are part of
the
wrapper
classes, but now you can generally use automatic conversion (called “autobox-
ing"/"autounboxing”). See
Example 5-1
for examples of both.
Example 5-1. AutoboxDemo.java