nerdexam
Oracle

1Z0-819 · Question #5

Given: public class Foo { public static void main(String... args) { for (var x : args) { System.out.println(x); } } } What is the type of the local variable x?

The correct answer is D. String. var uses local variable type inference (introduced in Java 10), so the compiler infers x's type from the iterable being looped over. Since args is declared as String... args (a varargs parameter, which is a String[] at runtime), each element yielded by the enhanced for-loop is…

Working with Java Data Types

Question

Given: public class Foo { public static void main(String... args) { for (var x : args) { System.out.println(x); } } } What is the type of the local variable x?

Options

  • ACharacter
  • Bchar
  • CString[]
  • DString

How the community answered

(43 responses)
  • A
    2% (1)
  • B
    12% (5)
  • C
    5% (2)
  • D
    81% (35)

Explanation

var uses local variable type inference (introduced in Java 10), so the compiler infers x's type from the iterable being looped over. Since args is declared as String... args (a varargs parameter, which is a String[] at runtime), each element yielded by the enhanced for-loop is a String, making D correct. Option C (String[]) is the type of args itself - the whole array - not the individual element. Options A (Character) and B (char) are character types, completely unrelated to iterating over a String array; they would only appear if you were somehow iterating over the characters within a single String.

Memory tip: In for (var x : someArray), think of var as "peel one layer" - it infers the element type of the array or collection, not the container itself. String[]String.

Topics

#Type Inference#Varargs#Enhanced For Loop#Local Variables

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice