Java Reference
In-Depth Information
■
the
new
operator always creates a new object. If you do not need new objects of the primitive values, use the
valueOf()
factory method of the wrapper class instead of using the constructors. the
equals()
methods in the wrapper
classes have been reimplemented to compare the wrapped primitive values in wrapper objects, not their references.
Tip
Numeric Wrapper Classes
Byte
,
Short
,
Integer
,
Long
,
Float
, and
Double
classes are numeric wrapper classes. They are all inherited from the
Number
class. The
Number
class is declared abstract. You cannot create an object of the
Number
class. However, you can
declare reference variables of the
Number
class. You can assign an object reference of any of the six numeric wrapper
classes to a reference of the
Number
class.
The
Number
class contains six methods. They are named
xxxValue()
where
xxx
is one of the six primitive data
types (
byte
,
short
,
int
,
long
,
float
, and
double
). The return type of the methods is the same as
xxx
. That is, the
byteValue()
method returns a
byte
, the
intValue()
method returns an
int
, etc. The following snippet shows how to
retrieve different primate type values from a numeric wrapper object:
// Creates an Integer object
Integer intObj = Integer.valueOf(100);
// Gets byte from Integer
byte b = intObj.byteValue();
// Gets double from Integer
double dd = intObj.doubleValue();
System.out.println("intObj = " + intObj);
System.out.println("byte from intObj = " + b);
System.out.println("double from intObj = " + dd);
// Creates a Double object
Double doubleObj = Double.valueOf("329.78");
// Gets different types of primitive values from Double
double d = doubleObj.doubleValue();
float f = doubleObj.floatValue();
int i = doubleObj.intValue();
long l = doubleObj.longValue();
System.out.println("doubleObj = " + doubleObj);
System.out.println("double from doubleObj = " + d);
System.out.println("float from doubleObj = " + f);
System.out.println("int from doubleObj = " + i);
System.out.println("long from doubleObj = " + l);