Type conversion (JDK1.5)Tag(s): String/Number

JDK1.5 simplifies the operation of conversion between primitive types (such as int) and wrapper types (such as Integer). This feature is called Autoboxing/Unboxing.
public class Test15 {
  public static void main(String ... args) {
    Integer integer = 1;        // int into Integer
    System.out.println(integer);

    int i = integer + 3;        // mix Integer and ints
    System.out.println(i);
    
    // output :
    //  1 
    //  4
  }
}
In the next example, a boolean is being stored and then retrieved from an ArrayList. The 1.5 version leaves the conversion required to transition to an Boolean and back to the compiler.
import java.util.Collection.*;
import java.util.*;

public class Test15 {
  public static void main(String ... args) {
  ArrayList<Boolean> list = new ArrayList<Boolean>();
  list.add(0, true);
  boolean flag = list.get(0);
  System.out.println(flag);
  }
}
The old way (pre 1.5) is more cryptic...
import java.util.Collection.*;
import java.util.*;

public class Test15 {
  public static void main(String args[]) {
  ArrayList list = new ArrayList();
  list.add(0, new Boolean(true));
  boolean flag = ((Boolean)list.get(0)).booleanValue();
  System.out.println(flag);
  }
}
Note : To be able to compile that code with the JDK1.5, you need to specify the switch -source 1.4 on the javac command line.


If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2012
[ home ]