1

Hi Guys when am running below program

package com.test;

public class Test1 {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    int i=5;
     for(;;i++){

        if(i<0){
            System.out.println("Break");
            break;
        }
    }

}

}

Output : Break.

How it is possible ? Can any one explain

thanks in Advance.

Clarence
  • 896
  • 1
  • 9
  • 27
  • 4
    Hint: what's the biggest `int` value? If `i` has that value, what is the new value of it after `i++` executes? – Jon Skeet May 18 '16 at 10:45
  • 2
    It is called an integer overflow. See [this question](http://stackoverflow.com/questions/3001836/how-does-java-handle-integer-underflows-and-overflows-and-how-would-you-check-fo) for more information. – Turing85 May 18 '16 at 10:46

3 Answers3

0

If you add this line to your code

public static void main(String[] args) {
    // TODO Auto-generated method stub
    int i=5;
     for(;;i++){
        System.out.println("Current i: " + i);
        if(i<0){
            System.out.println("Break");
            break;
        }
    }

}

You will see that after Integer.MAX_VALUE it will start over at Integer.MIN_VALUE and reach eventually zero at some time.

Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107
0

i initialize with five and loop will iterate till int maximum value of +2147483647 after that value comes again start from lowest value of int that is -2147483648 so when negative value starts if condition satisfied and print break.

Pankaj Saboo
  • 1,125
  • 1
  • 8
  • 27
0

this is the case of number system definition in number system definition.(Digital electronics and Number Systems).

Any progarmming language thers is number system for example for 8 bit signed integer it is -128 to 127.

so if you will put 128 it will be counted as -128. if you put 130 it will be counted as -126.

sowhen max positive integer values exceeds number becomes negative and condtion becomes true. thats why breakis out put .

insert sop(i) in the loop , you will understand.

Shaurya
  • 136
  • 1
  • 4
  • 20