Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer in parentheses not compiling - Why?

I'm initializing two integers a and b.

It compiles fine for a but there is an error for b.

public class Main_1 {
    public static void main(String[] args) {
        int a = -2147483648; //Working fine
        int b = -(2147483648); //Compilation error: The literal 2147483648 of type int is out of range 
    }
}

Please help me understand this behavior ?

like image 586
Sachin Sachdeva Avatar asked Nov 17 '15 08:11

Sachin Sachdeva


3 Answers

The reason is that the int datatype has valid values in the range [-2147483648, 2147483647].

When you wrap 2147483648 inside parentheses, it becomes an expression that will be evaluated as an int. However, 2147483648 is too big to fit in an int (too big by one).

The problem does not happen for -2147483648 because it is a valid int value.

Relevant parts of the JLS:

  • adding parentheses creates a "Parenthesized Expressions" (section 15.8.5)
  • an integer literal, such as 2147483648, is treated as an int by default (section 3.10.1)

    An integer literal is of type long if it is suffixed with an ASCII letter L or l (ell); otherwise it is of type int (§4.2.1).

like image 120
Tunaki Avatar answered Nov 10 '22 10:11

Tunaki


int values go from -2147483648 to 2147483647. So -(2147483648) is OutOfRange because the value inside the brackets is evaluated as an int. The max value you can put into the brackets is

Integer.MAX_VALUE //Which is equals to 2147483647
like image 11
ThomasThiebaud Avatar answered Nov 10 '22 08:11

ThomasThiebaud


The compilation error is pretty clear: you are using the int literal which is out of range. If you really want to do it, you may use long literal:

int b = (int) -(2147483648L);

Or double literal:

int b = (int) -(2147483648.0);
like image 7
Tagir Valeev Avatar answered Nov 10 '22 08:11

Tagir Valeev