0

I just learned about using "L" after long values to signify that they're long types, just like when you use "f" after float types. I was wondering what happens when you write;

long value = 3;

instead of

long value = 3L;

So I was wondering;

Does the compiler consider 3 an integer and then just convert it implicitly to a long?

Then I tried to check the type of the value "3" by using instanceof (but I can't use it since it is a primitive type) or reflection (getClass(), but obviously I can't because it isn't a reference type). Is there anyway to check what type the value "3" is or is this impossible since Java is statically typed?

Thanks, Bernard

Bernard Borg
  • 1,225
  • 1
  • 5
  • 18

1 Answers1

1

According to section 3.10.1 Integer Literals of the Java 14 Language Specification:

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).

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
  • 1
    This answers my initial question of whether "3" is int or long, but doesn't answer the question whether or not there is any way to check the type of a primitive value. – Bernard Borg Aug 16 '20 at 13:32
  • @BernardBorg: again, the answers in the duplicate question answers this "second part" completely. – DontKnowMuchBut Getting Better Aug 16 '20 at 13:33
  • @BernardBorg: The Java Language Specification tells you the type of `3`. You can check it by looking it up there. – Jörg W Mittag Aug 16 '20 at 13:36
  • A literal is literally the value it represents. The literal is composed of a sequence of 'marks' (my term) in source code. You can always determine the type by looking at the marks, and as a programmer you need to know how to do that -- you need to know 3 is an int, 3L is a long int, '3' is a char, and "3" is a string. So given you must know this when you write the code, there is no need for runtime facilities to check. – user13784117 Aug 16 '20 at 14:04