Site Search:

Develop code that uses wrapper classes such as Boolean, Double, and Integer.

Back OCAJP
Each java primitive type has a corresponding wrapper class. Constructing a wrapper class creates an object. You don't have to construct a wrapper class before using, because java support auto-boxing -- wherever a method or constructor expect a wrapper class, you can pass in the corresponding primitive type data, java will automatically convert the primitive type into the wrapping class.


Let's take a look at examples.

auto-boxing


OCAJP>cat test.java 
import java.util.*;
class test {
  public static void main(String[] args) {
    ArrayList<Integer> list = new ArrayList<>();  //list expect Integer object
    list.add(1);  //auto boxing, java auto convert int 1 to new Integer(1);
    list.add(new Double(1.1).intValue());
    for(long j : list) {  //auto unboxing, convert Integer to int, then type cast to long
      System.out.println(j);
    }
    for(Integer k : list) {
      System.out.println(k + 1.1f);  //auto unboxing to int, then promote to float
    }
  }
}
OCAJP>javac test.java 
OCAJP>java test
1
1
2.1
2.1


Wrapper constructor and functions.

new Type()
<type>Value()
parse<Type>()


OCAJP>cat test.java 
class test {
  public static void main(String[] args) {
    Boolean b = new Boolean(true);
    boolean b1 = b.booleanValue();
    //boolean b2 = Boolean.parseBoolean(b1);  //boolean cannot be converted to String
    boolean b3 = Boolean.parseBoolean("true");
    Boolean b4 = Boolean.valueOf("true");
    Boolean b5 = Boolean.parseBoolean("tree");
    System.out.println("b5 = " + b5);

    Byte bt = new Byte((byte)1);  
    //Byte bt2 = new Byte(1);  //possible lossy conversion from int to byte
    Byte bt3 = new Byte("1");
    Byte bt4 = new Byte(Byte.parseByte("1"));
    Byte bt5 = Byte.valueOf("1");
    Byte bt6 = Byte.valueOf((byte)1);
    //Byte bt6 = Byte.valueOf(1);  //possible lossy conversion from int to byte
    byte bt7 = Byte.parseByte("1");
    byte bt8 = bt6.byteValue();
    short s0 = bt6.shortValue();
    int i0 = bt6.intValue();
    //Byte bt9 = Byte.valueOf("1.999");//java.lang.NumberFormatException
    long l0 = bt6.longValue();
    float f0 = bt6.floatValue();
    double d0 = bt6.doubleValue();
    System.out.println("d0=" + d0);

    Short s = new Short((short)1);
    short s1 = s.shortValue();
    byte b9 = s.byteValue();
    
    Integer i = new Integer(1);

    //System.out.println(new Integer(null));  //java.lang.NumberFormatException: null
    Long l = new Long(1);
    Float f = new Float(1);
    Double d = new Double(1);
    System.out.println("d="+d);
    
    Double d1 = new Double(i);
    Double d2 = new Double(d1);

    Character c = new Character('A');
    char c1 = c.charValue();
  }
}
OCAJP>javac test.java 
OCAJP>java test
b5 = false
d0=1.0
d=1.0
Back OCAJP