Multiple choice technology

Given: 10. public class Bar { 11. static void foo( int... x ) { 12. // insert code here 13. } 14. } Which two code fragments, inserted independently at line 12, will allow the class to compile? (Choose two.)

  1. foreach( x ) System.out.println(z);

  2. for( int z : x ) System.out.println(z);

  3. while( x.hasNext() ) System.out.println( x.next() );

  4. for( int i=0; i< x.length; i++ ) System.out.println(x[i]);

Reveal answer Fill a bubble to check yourself
B,D Correct answer
Explanation

The varargs parameter int... x is treated as an array. Option B uses enhanced for-loop to iterate over x. Option D uses traditional for-loop with x.length and array indexing. Option A is invalid syntax. Option C is wrong because arrays don't have hasNext()/next() methods.