nerdexam
Oracle

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…

Using Loop Constructs

Question

Given the code fragment:
  1. public static void main(String[] args) {
  2. int x = 5;
  3. while (isAvailable(x)) {
  4. System.out.print(x);
  5. }
  6. }
  7. public static boolean isAvailable(int x) {
  8. return x-- > 0 ? true : false;
  9. }
Which modification enables the code to print 54321?

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)
  • A
    4% (3)
  • B
    70% (49)
  • C
    19% (13)
  • D
    7% (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 (-x in print): Negates x for display purposes only but still doesn't decrement main's x, so it infinite-loops printing -5.
  • C (--x then print): The pre-decrement fires before printing, so it outputs 43210 instead of 54321.
  • D (inverted condition): Returns false when x > 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

#Post-decrement operator#Method parameters#While loop#Loop termination

Community Discussion

No community discussion yet for this question.

Full 1Z0-808 Practice