Java Reference
In-Depth Information
All wrapper classes are immutable. They provide two ways to create their objects:
Using constructors
valueOf() factory methods
Each wrapper class, except Character , provides at least two constructors: one takes a value of the corresponding
primitive type and another takes a String . The Character class provides only one constructor that takes a char .
The following snippet of code creates objects of some wrapper classes:
Using the
// Creates an Integer object from an int
Integer intObj1 = new Integer(100);
// Creates an Integer object from a String
Integer intObj2 = new Integer("1969");
// Creates a Double object from a double
Double doubleObj1 = new Double(10.45);
// Creates a Double object from a String
Double doubleObj2 = new Double("234.60");
// Creates a Character object from a char
Character charObj1 = new Character('A');
// Creates a Boolean object from a boolean
Boolean booleanObj1 = new Boolean(true);
// Creates Boolean objects from Strings
Boolean booleanTrue = new Boolean("true");
Boolean booleanFalse = new Boolean("false");
Another way to create objects of wrapper classes is to use their valueOf() methods. The valueOf() methods are
static. The following snippet of code creates objects of some wrapper classes using their valueOf() methods:
Integer intObj1 = Integer.valueOf(100);
Integer intObj2 = Integer.valueOf("1969");
Double doubleObj1 = Double.valueOf(10.45);
Double doubleObj2 = Double.valueOf("234.60");
Character charObj1 = Character.valueOf('A');
Use of this method to create objects for integer numeric values ( byte , short , int , and long ) is preferred over
constructors as this method caches some objects for reuse. the wrapper classes for these primitive types cache wrapper
objects for primitive values between -128 and 127. For example, if you call Integer.valueOf(25) multiple times, the
reference of the same Integer object from the cache is returned. however, when you call new Integer(25) multiple
times, a new Integer object is created for each call.
Note
 
 
Search WWH ::




Custom Search