Autoboxing/Unboxing in Expressions

Within an expression, a numeric object is automatically unboxed.

The outcome of the expression is reboxed, if necessary. For example, consider the following program:


public class Main {
  public static void main(String args[]) {
    Integer integerObject, integerObject2;
    
    integerObject = 1;
    System.out.println(integerObject);
    ++integerObject;
    System.out.println(integerObject);
    integerObject2 = integerObject + (integerObject / 3);
    System.out.println(integerObject2);
    int i = integerObject + (integerObject / 3);
    System.out.println(i);
  }
}

Auto-unboxing allows you to mix different types of numeric objects in an expression.


public class Main {
  public static void main(String args[]) {
    Integer integerObject = 10;
    Double doubleObject = 9.6;
    doubleObject = doubleObject + integerObject;
    System.out.println(doubleObject);
  }
}

Because of auto-unboxing, you can use integer numeric objects to control a switch statement.


public class Main {
  public static void main(String args[]) {
    Integer iOb = 10;
    switch (iOb) {
    case 1:
      System.out.println("one");
      break;
    case 2:
      System.out.println("two");
      break;
    default:
      System.out.println("error");
    }
  }
}

Autoboxing/Unboxing Boolean and Character Values


public class Main {
  public static void main(String args[]) {
    // Autobox/unbox a boolean.
    Boolean b = true;
    if (b == true){
      System.out.println("b is true");      
    }
    // Autobox/unbox a char.
    Character ch = 'x'; 
    char ch2 = ch; 
    System.out.println("ch2 is " + ch2);
  }
}
Home 
  Java Book 
    Language Basics  

Autoboxing Autounboxing:
  1. Autoboxing and auto-unboxing
  2. Autoboxing and Methods
  3. Autoboxing/Unboxing in Expressions