Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Primitives range calculation [duplicate]

In Java when we declare

short number=1024*1024*1024;  

it will give compile time error but

short number=1024 * 1024 * 1024 * 1024; 

compiles fine. Why does this happen?

like image 778
Jekin Kalariya Avatar asked Jul 16 '14 05:07

Jekin Kalariya


1 Answers

The compiler will, in this case, evaluate the calculation (because it contains only constants) and try to assign the result to the variable. This calculation is done with type int and only converted to short on assignment, if at all possible.

In your case, the first calculation is too large to fit into a short (1073741824). The second one will overflow the int and end up in a range that short supports (0). So the assignment works in that case.

Mind you, you probably don't ever want to rely on these things in code.

like image 176
Joey Avatar answered Sep 20 '22 21:09

Joey