The Java library has eight classes in the java.lang package to represent each of the eight primitive types.
These classes are called wrapper classes as they wrap a primitive value in an object.
Primitive Type | Wrapper Class |
---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
char | Character |
boolean | Boolean |
All wrapper classes are immutable. They provide two ways to create their objects:
Each number wrapper class provides at least two constructors: one takes a value of the corresponding primitive type and another takes a String.
Character class provides only one constructor that takes a char.
The following snippet of code creates objects of some wrapper classes:
public class Main { public static void main(String[] args) { // Creates an Integer object from an int Integer intObj1 = new Integer(100); // Creates an Integer object from a String Integer intObj2 = new Integer("1234"); // Creates a Double object from a double Double doubleObj1 = new Double(10.45); // Creates a Double object from a String Double doubleObj2 = new Double("1234.56"); // 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"); }//from ww w. j a v a2s . co m }
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:
public class Main { public static void main(String[] args) { Integer intObj1 = Integer.valueOf(100); Integer intObj2 = Integer.valueOf("1234"); Double doubleObj1 = Double.valueOf(10.45); Double doubleObj2 = Double.valueOf("1234.60"); Character charObj1 = Character.valueOf('A'); }/*from w w w. j a va2 s . c o m*/ }
The Difference Between Using Constructors and valueOf( ) Method to Create Integer Objects
public class Main { public static void main(String[] args) { // Create two Integer objects using constructors Integer iv1 = new Integer(25); Integer iv2 = new Integer(25); System.out.println("iv1 = iv1 = " + iv1 + ", iv2 = " + iv2); // Compare iv1 and iv2 references System.out.println("iv1 == iv2: " + (iv1 == iv2)); // Let's see if they are equal in values System.out.println("iv1.equals(iv2): " + iv1.equals(iv2)); System.out.println("\nUsing the valueOf() method:"); // Create two Integer objects using the valueOf() Integer iv3 = Integer.valueOf(25); Integer iv4 = Integer.valueOf(25); System.out.println("iv3 = " + iv3 + ", iv4 = " + iv4); // Compare iv3 and iv4 references System.out.println("iv3 == iv4: " + (iv3 == iv4)); // Let's see if they are equal in values System.out.println("iv3.equals(iv4): " + iv3.equals(iv4)); }/* w ww. ja v a2s . c o m*/ }