Java Reference
In-Depth Information
Converting Primitive Types to Objects and Vice
Versa
One thing you can't do under any circumstance is cast from an object to a primitive data
type, or vice versa.
Primitive types and objects are very different things in Java, and you can't automatically
cast between the two.
As an alternative, the
java.lang
package includes classes that correspond to each primi-
tive data type:
Float
,
Boolean
,
Byte
, and so on. Most of these classes have the same
names as the data types, except that the class names begin with a capital letter (
Short
instead of
short
,
Double
instead of
double
, and the like). Also two classes have names
that differ from the corresponding data type:
Character
is used for
char
variables, and
Integer
is used for
int
variables.
Using the classes that correspond to each primitive type, you can create an object that
holds the same value. The following statement creates an instance of the
Integer
class
with the integer value
7801
:
Integer dataCount = new Integer(7801);
After you have an object created in this manner, you can use it as you would any object
(although you cannot change its value). When you want to use that value again as a
primitive value, there are methods for that, as well. For example, if you wanted to get an
int
value from a
dataCount
object, the following statement would be apt:
int newCount = dataCount.intValue(); // returns 7801
A common translation you need in programs is converting a
String
to a numeric type,
such as an integer. When you need an
int
as the result, this can be done by using the
parseInt()
class method of the
Integer
class. The
String
to convert is the only argu-
ment sent to the method, as in the following example:
String pennsylvania = “65000”;
int penn = Integer.parseInt(pennsylvania);
The following classes can be used to work with objects instead of primitive data types:
Boolean
,
Byte
,
Character
,
Double
,
Float
,
Integer
,
Long
,
Short
, and
Void
. These
classes are commonly referred to as
object wrappers
because they provide an object rep-
resentation that contains a primitive value.