Jekin Kalariya Jekin Kalariya - 5 months ago 32
Java Question

Java Primitives range calculation

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?


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.