Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Difference between long a = 1 and long a = 1L

My question is long a = 1; an integer in reality? And is it the same as long a = 1L; in data type?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can see from the following experiments that the literals (not prefixed with L) are ints, but that there are automatic casts such that a long variable finaly always holds a long value:

long a = 2147483647 + 1;

long b = 2147483647;
b++;

long c = 2147483647L + 1;
  • For a, the literals are ints. The calclulation is done with ints, which overflows. Therefore long a gets assigned -2147483648L.
  • For b, the int literal is casted to long during assignment, which can be incremented to the final value b = 2147483648L without overflow.
  • For c, the calculation is already done with longs (the int literal 1 is automatically casted to 1L), giving c = 2147483648L in first place.

You can find the specification for numeric promotion in JLS 5.6 "Numeric Contexts"

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading