1Z0-803 · Question #117
Given: public class Natural { private int i; void disp() { while (i <= 5) { for (int i = 1; i <= 5; ) { System.out.print(i + " "); i++; } i++; } } public static void main (String args[]) { new Natural
The correct answer is D. Prints 1 2 3 4 5 six times. The code initializes an instance variable 'i' to 0, then an outer while loop iterates as long as this 'i' is less than or equal to 5, and an inner for loop prints 1 through 5, using a new local 'i' that shadows the instance variable.
Question
Given:
public class Natural { private int i; void disp() { while (i <= 5) { for (int i = 1; i <= 5; ) { System.out.print(i + " "); i++; } i++; } } public static void main (String args[]) { new Natural().disp(); } }
Options
- APrints 1 2 3 4 5 once
- BPrints 1 3 5 once
- CPrints 1 2 3 4 5 five times
- DPrints 1 2 3 4 5 six times
- ECompilation fails
How the community answered
(17 responses)- A6% (1)
- B12% (2)
- D65% (11)
- E18% (3)
Why each option
The code initializes an instance variable 'i' to 0, then an outer while loop iterates as long as this 'i' is less than or equal to 5, and an inner for loop prints 1 through 5, using a new local 'i' that shadows the instance variable.
A is incorrect because the outer loop causes the inner printing to occur multiple times, not just once.
B is incorrect because the inner loop iterates from 1 to 5, incrementing 'i' by 1 each time, leading to '1 2 3 4 5', not '1 3 5'.
C is incorrect because the outer loop iterates six times (for 'i' from 0 to 5), not five times.
D is correct. The outer loop uses the instance variable 'private int i;', which is initialized to 0 by default. The 'while (i <= 5)' condition runs for i = 0, 1, 2, 3, 4, 5, making six iterations. Inside, the 'for (int i = 1; i <= 5; )' loop declares a new local variable 'i' which shadows the instance 'i', always printing '1 2 3 4 5' and then exiting. After each inner loop completion, the instance 'i' is incremented by 'i++;', ensuring the outer loop progresses six times, thus printing '1 2 3 4 5' six times.
E is incorrect because the code compiles successfully; the variable shadowing is legal Java syntax.
Concept tested: Variable shadowing and loop execution flow
Source: https://docs.oracle.com/javase/tutorial/java/javaOO/variables.html
Topics
Community Discussion
No community discussion yet for this question.