nerdexam
Oracle

1Z0-803 · Question #265

Given the code fragment: public class ForTest { public static void main(String[] args) { int[] array = {1, 2, 3}; for ( foo ) { } } Which three code fragments, when replaced individually for foo, enab

The correct answer is A. int i : array B. int i = 0;i< 1; C. ; ;. The for loop in Java offers flexible syntax, including the enhanced for-each loop and traditional loops where parts can be optional. Options A, B, and C provide syntactically correct for loop declarations that will compile.

Using Loop Constructs

Question

Given the code fragment:

public class ForTest { public static void main(String[] args) { int[] array = {1, 2, 3}; for ( foo ) { } } Which three code fragments, when replaced individually for foo, enables the program to compile?

Options

  • Aint i : array
  • Bint i = 0;i< 1;
  • C; ;
  • D; i < 1; i++
  • Ei = 0; i<1;

How the community answered

(67 responses)
  • A
    91% (61)
  • D
    3% (2)
  • E
    6% (4)

Why each option

The `for` loop in Java offers flexible syntax, including the enhanced for-each loop and traditional loops where parts can be optional. Options A, B, and C provide syntactically correct `for` loop declarations that will compile.

Aint i : arrayCorrect

`int i : array` is the correct syntax for an enhanced for loop (or for-each loop) in Java, which iterates over each element of the `array`.

Bint i = 0;i< 1;Correct

`int i = 0;i< 1;` is a valid traditional `for` loop declaration where the initialization (`int i = 0;`) and termination condition (`i < 1;`) are present, and the increment part is optional and can be omitted.

C; ;Correct

`; ;` is a syntactically valid `for` loop declaration that creates an infinite loop. All three parts of a traditional `for` loop (initialization, termination, and increment) are optional.

D; i < 1; i++

The fragment `; i < 1; i++` is missing the initialization part where the variable `i` is declared. Without `i` being declared prior to the loop, this will result in a compile-time error.

Ei = 0; i<1;

Similar to D, the fragment `i = 0; i<1;` is missing the declaration of the variable `i` in the initialization part, which leads to a compile-time error if `i` is not previously declared.

Concept tested: Java For Loop Syntax

Source: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html

Topics

#For loop syntax#Enhanced for loop#Loop constructs

Community Discussion

No community discussion yet for this question.

Full 1Z0-803 Practice