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…
Question
Options
- ACharacter
- Bchar
- CString[]
- DString
How the community answered
(43 responses)- A2% (1)
- B12% (5)
- C5% (2)
- D81% (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
Community Discussion
No community discussion yet for this question.