2

I have a question about declaring a long variable in Java:

This compiles: long x = 10;
This gives a compiler error: long x = 1000000000000
This compiles: long x = 1000000000000L
Why don't i need to put a L after the number in the first case? How does this relate to the compiler automatically casting a long to an int value (because Iguess that is what's happening in the first example) ?

Also the same question about float's:

This doesn't compile: float f = 10.1;
This compiles: float f = 10;
This compiles: float f = 10.1f;

Why does the first example not compile? Why is the f-prefix not needed in the second example? And how does this relate with the complier automatically casting to a double?

Thanks in advance!

  • 1
    because without the L suffix, the number is an int and 1000000000000 is too large for int –  Feb 28 '16 at 12:05
  • *"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)."* - 1000000000000 cannot fit into an `int`. – Maroun Feb 28 '16 at 12:06
  • For the float, the compiler tells you why: "error: incompatible types: possible lossy conversion from double to float" –  Feb 28 '16 at 12:06

1 Answers1

6

Numeric constants without any postfix have default types. If they are integer (i.e. they have no floating point), the default type is int. If they have a floating point, the default type is double.

Therefore an integer constant without the L suffix (which denotes a long literal) can't be larger than Integer.MAX_VALUE, and the double constant 10.1 can't be assigned to a float variable without an explicit cast.

On the other hand, the int 10 can be assigned to a float variable, as well as the float 10.1f.

Eran
  • 387,369
  • 54
  • 702
  • 768