Java autoboxing unboxing in expressions

Introduction

Within an expression, a numeric object is automatically unboxed.

The outcome of the expression is reboxed, if necessary.


// Autoboxing/unboxing occurs inside expressions. 
 
public class Main { 
  public static void main(String args[]) { 
     /*w  w w.  jav a2  s.  c o m*/
    Integer iOb, iOb2; 
    int i; 
 
    iOb = 100; 
    System.out.println("Original value of iOb: " + iOb); 
 
    // unboxes iOb, performs the increment, and then reboxes the result
    ++iOb; 
    System.out.println("After ++iOb: " + iOb); 
 
    // iOb is unboxed, the expression is  
    // evaluated, and the result is reboxed and assigned to iOb2. 
    iOb2 = iOb + (iOb / 3); 
    System.out.println("iOb2 after expression: " + iOb2); 
 
    // result is not reboxed. 
    i = iOb + (iOb / 3); 
    System.out.println("i after expression: " + i); 
 
  } 
}

Once the values are unboxed, the standard type promotions and conversions are applied.

public class Main {  
  public static void main(String args[]) {  
  
    Integer iOb = 100;  //from  w  ww .j a  v  a  2 s  .  c  o m
    Double dOb = 98.6;  
  
    dOb = dOb + iOb;  
    System.out.println("dOb after expression: " + dOb);  
  }  
} 



PreviousNext

Related