programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# problem with infinite loop

sovan chatt
Ranch Hand
Posts: 43
the above code prints small x once..why??while loop is a infinite loop and if condition never gets exected.but still i got the output?!!

John Jai
Rancher
Posts: 1776
Once the maximum value of int is reached, then the value of x starts from the minimum value.

Try below code and check what happens.

Pavan Kumar Dittakavi
Ranch Hand
Posts: 108
It is an infinite loop. No doubt about that.

when I ran the application that you have given us, I could see the following output:

small x-2147483648

Also, it is interesting to note that the range of an int in java is [-2,147,483,648 and +2,147,483,647]. So, initially 'x' is set to 0 and it increments each time and finally at a certain time, its sign bit is toggle to 1 making it a negative number and entering the if clause and exiting the loop [as x is now negative].

Thanks,
Pavan.

Rob Spoor
Sheriff
Posts: 21135
87
Pavan Kumar Dittakavi wrote:It is an infinite loop. No doubt about that.

No it's not. You've seen for yourself that the loop ends.

Campbell Ritchie
Marshal
Posts: 56570
172
I tried it and the loop terminated after < 4 seconds.

Manoj Kumar Jain
Ranch Hand
Posts: 198
• 3
This is not an infinite loop.

Initially the value of x is 5 and it will increment till 2147483647 (max integer range).
As x is always greater than 3 (x is incresing from 5 to 2147483647 ), so if block will not execute till now.

As soon as we now increment to this value(2147483647 ) by 1 we get the x as -2147483648 now this will qualify the if block and will execute the statement inside the if block

when the condition is checked for the next iteration in the while(-2147483648>1) it fails and program execution stops.