Java: Why can't I declare integer types using scientific notation?

exponent, integer, java, long-integer, scientific-notation

Solution

It's because when you use the scientific notation you create a floating point number (a double in your example). And you can't assign a floating point to an integer (that would be a narrowing primitive conversion, which is not a valid assignment conversion).

So this would not work either for example:

int y = 2d; //can't convert double to int

You have a few options:

- explicitly cast the floating point to an integer: `int y = (int) 2e6;`

- with Java 7+ use a thousand separator: `int y = 2_000_000;`

Problem

I can easily read `2e15` as "two quadrillion" at a glance, but for `2000000000000000` I have to count the zeroes, which takes longer and can lead to errors. Why can't I declare an `int` or `long` using a literal such as `2e9` or `1.3e6`? I understand that a negative power of 10, such as `2e-3`, or a power of 10 that is less than the number of decimal places, such as `1.0003e3`, would produce a floating point number, but why doesn't Java allow such declarations, and simply truncate the floating-point part and issue a mild warning in cases where the resulting value is non-integral? Is there a technical reason why this is a bad idea, or is this all about type-safety? Wouldn't it be trivial for the compiler to simply parse a statement like `long x = 2e12` as `long x = 2000000000000 //OK for long` and `int y = 2.1234e3` as `int y = 2123.4 //warning: loss of precision`

Original source