Java OCA OCP Practice Question 1840

Question

Identify the valid for loop constructs assuming the following declarations:

Object o = null;
Collection c = //valid collection object.
int [][] ia = //valid array

Select 2 options

  • A. for (o: c){ }
  • B. for (final Object o2:c){ }
  • C. for (int i: ia) { }
  • D. for (Iterator it: c.iterator ()){ }
  • E. for (int i: ia [0]){ }


Correct Options are  : B E

Note

For A.

Cannot use an existing/predefined variable in the variable declaration part.

For B.

final is the only modifier (excluding annotations) that is allowed here.

For C.

Each element of ia is itself an array. Thus, they cannot be assigned to an int.

For D.

c.iterator () does not return any Collection. Note that the following would have been valid:

Collection<Iterator> c = //some collection that contains
Iterator objects
for (Iterator it  : c){  }

For E.

Since ia [0] is an array of ints, this is valid.




PreviousNext

Related