3

Today while reading boxing and auto-boxing i came up with scenario and found that peculiar behavior where i was stuck in infinite loop .

I checked my code twice but i did not find any mistake. If any one can look and suggest me where i am doing wrong so that i will come out this infinite loop

kindly find the below code.

public class InTheLoop {

public static final int END = Integer.MAX_VALUE;
public static final int START = END - 100;

public static void main(String[] args) {
    int count = 0;
     //Infinite loop starts.
    for (int i = START; i <= END; i++) {
        count++;
        System.out.println(count);
    }

 // This never got printed.
    System.out.println("hi I am out of for loop" +count);
  }
}
Kurenai Kunai
  • 1,842
  • 2
  • 12
  • 22
T-Bag
  • 10,916
  • 3
  • 54
  • 118

4 Answers4

4

Note that your END is equal to the maximum possible value that an Integer can hold (the value being 2147483647). That means that for any value that i could possibly hold, i <= END is always true. When i actually reaches 2147483647, it is still <= END. On the very next iteration you attempt to increment it by one, which causes overflow, and i becomes -2147483648, which is still <= END, and the loop continues forever.

Ishamael
  • 12,583
  • 4
  • 34
  • 52
2

It is becuase you have set i<=END, Once it reaches Integer.MAX_VALUE, increment (i++) is executed, which makes it -2147483648(Integer.MAX_VALUE+1).

So thats why it is not breaking and keep on running.

Change ,

 for (int i = START; i <= END; i++) {

to

for (int i = START; i < END; i++) {

will solve .

Naruto
  • 4,221
  • 1
  • 21
  • 32
  • Mark the answer as ACCEPTED if it helped to solve your problem.In this way it will help others looking for similar problem – Naruto Dec 07 '15 at 14:50
1

for (int i = START; i <= END; i++) { ==> Here i <= END; is the culprit.

When the loop runs, i is incremented by one on each iteration, then it is compared to end. So,

initially - i = 2147483547

As soon as i reaches 2147483647 (Integer.Max_VALUE), it is again incremented by 1, So, you get an overflow and the loop

Something like this happens :

2147483645
2147483646
2147483647
-2147483648
-2147483647
-2147483646.

Change your code to : for (int i = START; i < END; i++) {

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
0

The START value is 2147483547 You've put it to iterate to END value 2147483647

After START reaches 2147483647 it begins with -2147483648

It's the integer overflow in your program. As int data type is 32 bit in Java, any value that surpasses 32 bits gets rolled over. In numerical terms, it means that after incrementing 1 on Integer.MAX_VALUE (2147483647), the returned value will be -2147483648. There is no warning or exception raised by the JVM when such a condition occurs.

This has been dealt in Java 8 an ArithmeticException is thrown on an overflow Check this & this.

Community
  • 1
  • 1
underdog
  • 4,447
  • 9
  • 44
  • 89