why don't we need suffix on long in java?

后端 未结 3 1182
悲&欢浪女
悲&欢浪女 2021-01-21 19:18

While writing some code I noticed that long(primitive) data type does not need to have the suffix l or L. My code compiles and run fine with this. Can anyone explain the logic B

相关标签:
3条回答
  • 2021-01-21 19:56

    When you do:

    long l=435;
    

    The compiler considers it as an int, and then, since the data type you have given is a long, so it does automatic conversion to long data type. So you don't need a suffix.

    However, if you try it with a really long number, like:

    long l = 9999999999;
    

    The compiler will throw an error (integer number too large). Because, it will try to consider it as an int, but it is too big to be an int. So, here, you need a suffix. If you do:

    long l = 9999999999L;
    

    Then it will compile.
    Simply, a suffix is needed for a number which can only fit in a long data type.

    0 讨论(0)
  • 2021-01-21 19:59

    Because an int type can automatically be converted to long.

    0 讨论(0)
  • 2021-01-21 20:06

    Try assigning a really bug number, like long l = 0xFFFFFFFFF;.

    When you initialize a literal like 0xFFFFFFFFF, if there is no suffix and the variable is an integral type(int, long, etc), the value is assumed to be an int. And, an int can hold 32 bits, not 36 bits (9 x 0xF = 9 x '1111') like you will be trying if you type long l = 0xFFFFFFFFF;. So, you have to use a long that has a capacity of 64 bits. Appending 'L' or 'l' to the end of the value, like 0xFFFFFFFFFL, should take care of the compiler error. [Reference]

    In general, since the type conversion to long will happen anyway, it is a good idea to be explicit about that L.

    0 讨论(0)
提交回复
热议问题