user13316090
user13316090

Reputation: 89

Having trouble understanding Java Overflow and Compile error

I am a Java newbie and studying int overflow! While playing with some integers I was surprised with some weird results

    int x = 2147483647 + 1;    
    x == > - 2147483648 

    int x = 2147483647 + 2;
    x ==> -2147483647
    
    int x = 2147483647 + 2147483647;
    x ==> -2

    int x = 2147483647 + 2147483648; 
    **compile error**

I thought integer overflow would not cause any compile error. Also, it is hard for me to understand how outputs for the overflow are calculated (ex. why int x = 2147483647 + 1 // x ==> -2147483648) Can anybody please expalin the logic of these results?

Thanks!!

Upvotes: 0

Views: 227

Answers (3)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79085

Also, it is hard for me to understand how outputs for the overflow are calculated (ex. why int x = 2147483647 + 1 // x ==> -2147483648)

Whenever you the overflow or underflow happens, the value starts from the other end e.g.

public class Main {
    public static void main(String[] args) {
        System.out.println(Integer.MAX_VALUE);
        System.out.println(Integer.MAX_VALUE + 1);// Will be equal to Integer.MIN_VALUE
        System.out.println(Integer.MIN_VALUE);
        System.out.println(Integer.MIN_VALUE - 1);// Will be equal to Integer.MAX_VALUE
    }
}

Output:

2147483647
-2147483648
-2147483648
2147483647

Upvotes: 2

Andy Turner
Andy Turner

Reputation: 140319

From the language spec:

The largest decimal literal of type int is 2147483648 (2^31).

All decimal literals from 0 to 2147483647 may appear anywhere an int literal may appear. The decimal literal 2147483648 may appear only as the operand of the unary minus operator - (§15.15.4).

It is a compile-time error if the decimal literal 2147483648 appears anywhere other than as the operand of the unary minus operator; or if a decimal literal of type int is larger than 2147483648 (2^31).

You can't use 2147483648 as an int literal because an int literal is an int expression, and thus must have an int value; but 2147483648 is too large to be used as an int value.

Upvotes: 4

azro
azro

Reputation: 54148

You can get IntegerOverflow while computing values together as your first 3 examples

The problem here about 2147483648 is kind of the same but difference, as Integer.MAX_VALUE is 2147483647 you cannot store more in an int that's why you get an compilation error 2147483648 is too big to fit in. Even before runtime you already can't fit the value in an int, which is different of the overflow that occurs at runtime

Upvotes: 2

Related Questions