In: Computer Science
Explain the difference between a data literal and a variable and how Java interprets numeric literals in your code
Q1. Explain the difference between a data literal and a variable.
A variable is a container that holds values that are used in a Java code. Every variable must be declared beforehand to use in program.
A data literal is a constant value in Java created by using a literal representation of it. In other words, literal is a notation for representing a fixed (constant) value.
Note that value stored in variables can change while literal is a constant value
Ex - int A;
A = 1;
Here 'A' is a variable while the constant '10' is a literal
Q2. How Java interprets numeric literals in your code?
1. Integer literal is implicit integer value
By default, the Java compiler treats all integer literals as of type int. For example consider the byte declaration of variable
byte a = 200;
After its compilation, compiler will generate a error message: loss of precision as 200 does not fit in the range of byte which is from -127 to 128.
2. Decimal literal is implicit double value
By default, the Java compiler treats all decimal literals as of type double. For example consider the float declaration of variable
float a = 58.6;
After its compilation, compiler will generate a error message: loss of precision as 58.6 will be treated as a double value by the compiler and conversion from float to double value will lead to loss of precision. Hence, we must use the suffic f or F for forcing conversion.
float a = 58.6f;
3. Representing numeric literals in other bases
int decimal = 223;
int binary = 0b1101101;
int octal = 0255;
int hexadecimal = 0x48;
4. Underscores can be used in numeric literals
We can use underscores in numeric literals to increase readability of our code and thus leading to a better undertstanding, helpful in debugging of the code. This change was introduced with the Java 7.
5. Conversion from one numeric type to another
int can be converted to long implicitly but not vice versa
int x = 20;
// This is correct as long can hold values of type int
long y = x;
long y = 20;
// This is not correct as int can't hold values of type long
// Hence compiler will report an error message: loss of precision
int x = y;
long y = 20;
// Explicit conversion is required, called typecasting
int x = (int) y;