Machine-translated by Google. Questions are authored in English.
Top

Discussion

What will be the output of the program?

import java.util.*;

public class Item93
{
    public static void main(String[] args)
    {
        List<Integer> l = new ArrayList<Integer>();
        l.add(1);
        l.add(null);
        int total = 0;
        for (Integer v : l) total += v;
        System.out.println(total);
    }
}

  • A.A NullPointerException is thrown.
  • B.The program prints 0
  • C.Compilation fails.
  • D.The program prints 1

Answer: A

The list happily stores a null, and the loop variable is an Integer, so no conversion happens there. The unboxing occurs in the addition, where the null Integer must become an int, and that throws NullPointerException on the second iteration after the first has already succeeded.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.