1Z0-808 · Question #58
Given the code fragment: 3. public static void main(String[] args) { 4. int x = 5; 5. while (isAvailable(x)) { 6. System.out.print(x); 7. } 8. } 9. 10. public static boolean isAvailable(int x) { 11…
The correct answer is B. At line 7, insert x --. Option B works because inserting x--; after the print statement decrements x in main's scope on each iteration. Since isAvailable receives a primitive copy, the x-- inside it never affects main's x - so without the fix, x stays 5 forever and the loop is infinite. With x…
Question
- public static void main(String[] args) {
- int x = 5;
- while (isAvailable(x)) {
- System.out.print(x);
- }
- }
- public static boolean isAvailable(int x) {
- return x-- > 0 ? true : false;
- }
Options
- AReplace line 6 with System. out. print (-x);
- BAt line 7, insert x --;
- CReplace line 6 with --x; and, at line 7, insert System. out. print (x);
- DReplace line 12 With return (x > 0) ? false: true;
How the community answered
(70 responses)- A4% (3)
- B70% (49)
- C19% (13)
- D7% (5)
Explanation
Option B works because inserting x--; after the print statement decrements x in main's scope on each iteration. Since isAvailable receives a primitive copy, the x-- inside it never affects main's x - so without the fix, x stays 5 forever and the loop is infinite. With x-- inserted at line 7, the loop prints 5, then 4, 3, 2, 1 before isAvailable(0) returns false and exits.
Why the distractors fail:
- A (
-xin print): Negates x for display purposes only but still doesn't decrementmain'sx, so it infinite-loops printing-5. - C (
--xthen print): The pre-decrement fires before printing, so it outputs43210instead of54321. - D (inverted condition): Returns
falsewhenx > 0, so the loop never enters at all - no output.
Memory tip: In Java, primitives are pass-by-value - any mutation inside a called method is invisible to the caller. Whenever a loop counter lives in a method that only receives a copy, you must decrement it in the calling scope to actually make progress.
Topics
Community Discussion
No community discussion yet for this question.