Java OCA OCP Practice Question 1776

Question

Which one of these for statements is valid?.

Select the one correct answer.

  • (a) int j=10; for (int i=0, j+=90; i<j; i++) { j--; }
  • (b) for (int i=10; i=0; i--) {}
  • (c) for (int i=0, j=100; i<j; i++, --j) {;}
  • (d) int i, j; for (j=100; i<j; j--) { i += 2; }
  • (e) int i=100; for ((i>0); i--) {}


(c)

Note

Only (c) contains a valid for loop.

The initializer in a for statement can contain either declarations or a list of expression statements, but not both as attempted in (a).

The loop condition must be of type boolean.

(b) tries to use an assignment of an int value (notice the use of = rather than ==) as a loop condition and is, therefore, not valid.

The loop condition in the for loop (d) tries to use the uninitialized variable i, and the for loop in (e) is syntactically invalid, as there is only one semicolon.




PreviousNext

Related