Theoretically Literals means any number, text or other information that represents a value.
By default, the Integer Literals data type is int. i.e. The compiler will consider the integer literal value as int type by default.
As the Java compiler considers the integer value as int data type by default, the following example will throw compiler error while assigning an integer value which is out of int range to a long data type variable.
Lets implement this on Eclipse IDE -
1. Launch Eclipse IDE, create a Java Project 'Project 28' as shown below -
2. Create a Java Class file 'ClassOne' as shown below -
3. As we know that the range of int type is from -2,147,483,648 to 2,147,483,647. Lets create a long type variable and assign a value which is inside the int type range i.e. say 2,147,483,647 as shown below -
Observe that no error is displayed, as the number 2147483647 is in the int type range and the int type literals are accepted by long type variable in Java.
4. As we know that the range of long data type is -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Lets create a long type variable and assign the value in long type range say 9,223,372,036,854,775,807 as shown below -
Observe that an error is displayed.
5. View the error message as shown below -
Though we have assigned a value which is in the range of long data type, we have got this error.
The reason behind this is by default Java compiler considers the integer literals as int data type by default and we have assigned the literal which is out of int type rage. Hence we got the error 'The literal 9223372036854775807 of type int is out of range'.
In order to overcome this we have to tell the compiler that this value is a long type literal by specifying a letter 'L' at the end of the literal as shown below and observe that the error got resolved -
So, when you are assigning a long type literal value to a long data type variable, you have to add the letter 'L' at the end of the value to let the compiler know that the value that you are going to assign is a long type literal. If not providing the 'L' at the end of the value, the value will be treated as int type literal by the compiler.
Please comment below to feedback or ask questions.