What will the program print when it is compiled and run?
import java.util.ArrayList; import java.util.Collection; public class Main { public static void main(String[] args) { int sum = 0;//from w ww . j a v a2 s . c o m for (int i : makeCollection()) sum += i; System.out.println(sum); } static Collection<Integer> makeCollection() { System.out.println("A collection coming up."); Collection<Integer> collection = new ArrayList<Integer>(); collection.add(10); collection.add(20); collection.add(30); return collection; } }
Select the one correct answer.
(a) A collection coming up. 60 (b) A collection coming up. A collection coming up. A collection coming up. 60 (c) The program does not compile. (d) None of the above.
(a)
The expression in the for(:) loop header (in this case, the call to the makeCollection()
method) is only evaluated once.