-2
for (int x=0 ; x != 0 ; x++) {}

(A) will the loop run 4 billion times because x will start at 0 then approach max value (2^31-1)

(B) will the loop run 2 billion times because x will approach max value then an error will appear

(C) will it run forever because x will approach infinity

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216

2 Answers2

1

It won't loop at all.

You initialize x = 0 and then check x != 0. So loop will ends immediately.

If you initialize x = 1 then you get "2^32-1" iterations.

talex
  • 17,973
  • 3
  • 29
  • 66
1

The loop body will run exactly zero times. On the first iteration, x != 0 will be false.

In the general case of a for loop:

for (<initializations>; <condition>; <post> ) {
    <body>
}

the execution sequence is:

  1. <initializations>
  2. if <condition> then end
  3. <body>
  4. <post>
  5. go to 2.

(A) will the loop run 4 billion times because x will start at 0 then approach max value (2^31-1)

Nope. The arithmetic is wrong. 2^31-1 is not 4 billion. It is a bit over 2 billion.

(B) will the loop run 2 billion times because x will approach max value then an error will appear.

Nope. Integer overflow in Java doesn't raise an error / exception.

(C) will it run forever because x will approach infinity

Nope. It wouldn't approach infinity. An int value cannot be larger than Integer.MAX_VALUE

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216