ArrayLists and Iterators

21. Boxing and Unboxing


Answer:

    Double value = 2.5; double sum = value + 5.7;

Yes, this works. It is shorthand for

    Double value = new Double( 2.5 ); double sum = value.doubleValue() + 5.7;

Boxing and Unboxing

Here is a program that creates an ArrayList of Integer references. The arguments to add() look like int literals, but at runtime, the ints are autoboxed into Integer objects.

import java.util.* ;
public class WrapperExampleTwo
{
  public static void main ( String[] args)
  {
    ArrayList<Integer> data = new ArrayList<Integer>();

    // Autoboxing used here to create Integer objects
    data.add( 1 );
    data.add( 3 );
    data.add( 17 );
    data.add( 29 );

    int sum = 0;
    for ( Integer val : data )
      sum += val;                 // Unboxing used here to extract the ints
      
    System.out.print(  "sum = " + sum );

    System.out.println( );
  }
}

The for-each loop visits the Integer objects one by one. The statement

sum += val;                 // Unboxing used here to extract the ints

requires a primitive int to add to the sum. Unboxing extracts the int from the Integer that val points to.


Question 21:

Do you think that the following fragment will work:

    Double total, meal, tax; meal = 20.00; tax = meal*0.12; total = meal+tax; System.out.println("Total Cost: " + total );