Newsletter:

(Quiz) SCJP Mock Questions

Quiz : SCJP Mock Questions

Question

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.)
A. foreach(x) System.out.println(z);
B. for(int z : x) System.out.println(z);
C. while( x.hasNext()) System.out.println( x.next());
D. for( int i=0; i< x.length; i++ ) System.out.println(x[i]);


Answer: BD

Answer:
type... x is used in function arguments where type can be any data type
for example:
int... x

which can take variable arguments
for example a function named var having declarations

var(int... x)

we can pass var(1); , var(1,1); , var(1,2,3);

so it can take 1 to any number of integers as arguments


int... x here x is just like an array and we can iterate over its elements using simple and enhanced for loop

other options are invalid

foreach is a method which is not defined
And hasnext() is used to iterate over collections(sets,lists,maps)

Hence the answer is B,D