Home > Software engineering >  Why is this code printing a negative number?
Why is this code printing a negative number?

Time:12-08

public class Program {
    public static void main(String[] args) {
        int x = 1;
        for (int i = 1; i < 31; i  ) {
        x = x   2 * x;
        }
        System.out.println(x);
    }
}

It keeps outputting -1010140999 and I don't know why it's outputting a negative number.

CodePudding user response:

Final output is a very long number which will exceed the max integer capaxity. Hence we need to use long data type. Please check the correct code below with x value at each iteration

public class Program {
    public static void main(String[] args) {
        long x = 1;
        for (int i = 1; i < 31; i  ) {
            x = x   2l * x;
            System.out.println(i  " "  x);
        }
    }
}

Output

1 3
2 9
3 27
4 81
5 243
6 729
7 2187
8 6561
9 19683
10 59049
11 177147
12 531441
13 1594323
14 4782969
15 14348907
16 43046721
17 129140163
18 387420489
19 1162261467
20 3486784401
21 10460353203
22 31381059609
23 94143178827
24 282429536481
25 847288609443
26 2541865828329
27 7625597484987
28 22876792454961
29 68630377364883
30 205891132094649

CodePudding user response:

An integer in Java is stored with 32 bits, of which one is used to indicate whether the value is positive or negative. This means an int's value is between -2^31 and 2ˆ31 - 1.

Once you add or subtract past those limits, you wrap around in the corresponding direction since an overflow/underflow occurs.

public class OverflowExample {
    public static void main(String args[]) {
        int largest_int  = Integer.MAX_VALUE;
        int smallest_int = Integer.MIN_VALUE;
        
        System.out.println(largest_int);     //  2ˆ31 - 1 = 2147483647
        System.out.println(largest_int   1); // -2147483648
        System.out.println(smallest_int);    // -2^31, same as above
    }
}
  •  Tags:  
  • java
  • Related