Calculation of a range of Java primitives

In Java, when we declare

short number=1024*1024*1024; 

it will give a compile time error but

 short number=1024 * 1024 * 1024 * 1024; 

compiles fine. Why is this happening?

+62
java integer-arithmetic
Jul 16 '14 at 5:39
source share
2 answers

In this case, the compiler evaluates the calculation (because it contains only constants) and tries to assign the result to a variable. This calculation is performed with type int and is converted to short when assigned, if at all possible.

In your case, the first calculation is too large to fit in short ( 1073741824 ). The second overflows int and ends in the range supported by short ( 0 ). Thus, the assignment works in this case.

Remember, you probably never want to rely on these things in code.

+72
Jul 16 '14 at 5:41
source share

You are facing a problem as your number wraps around . In the first case, it does not wrap and, therefore, overflows the range shorter. But in the second case, it wraps after the calculation and, therefore, it falls into the short range and therefore you do not have a compile-time error.

Loss of accuracy means that you are losing information about a given value (the short data type is a 16-bit signed integer of two additions, the minimum value is 32.768 and the maximum value is 32,767 (inclusive).) In your first case, the range of short ones intersects (1073741824 ), and therefore you are losing information.

Narrowing the conversion of a signed integer to an integral type T simply discards everything except n bits of the lower order, where n is the number of bits used to represent type T.

EDIT: -

From JLS ยง3.10.1 (very correctly indicated in this similar question)

This is a compile-time error if the decimal literal of type int is greater than 2147483648 (2 31 ), or if the decimal literal 2147483648 appears anywhere other than the operand of the unary minus operator ( ยง15.15.4 ).

+11
Jul 16 '14 at 5:46
source share



All Articles