Literals
A constant value which can be assigned to a variable is called Literal.
eg: int x = 10;
int - data type
x - variable name
10 - constant value/ literal
Integral Literals :
For integral data types (byte, short, int, long) we can specify literal value in the following ways-
1) Decimal Literals (base 10)
Allowed digits : 0 to 9
ex: int x = 10;
2) Octal Literals (base 8)
Allowed digits : 0 to 7
Literal value should be prefixed with 0.
eg: int x = 010;
3) Hexa-Decimal form (base 16)
Allowed digit : 0 - 9 , a - f or A - F (for extra digits a to f we can use both lower or upper case characters. This is one of very few areas where JAVA is not case sensitive).
Literal value should be prefixed with 0x or 0X.
eg : int x = 0x10; or int x = 0X10;
These are only possible ways to specify literal value for integral data types.
INTERVIEW FAQS.
int x = 10; valid
int x = 07789; invalid CE: integer number too large. in octal only 0 to 7 is allowed
int x = 777; valid
int x = 0xFace; valid
int x = 0xBeef; valid
int x = 0xBeer; invalid r not allowed
class Test{
public static void main(String [] args){
int x = 10; //10
int y = 010; //8
int z = 0x10; //16
System.out.println(x + ".." + y + ".." + z);
}
}
o/p: 10..8..16
* by default every integral literal is of int type. But we can specify explicitly long type by suffixed with l or L
ex: int x = 10; valid
long l = 10l; valid
long l = 10; valid
int x = 10l; invalid CE: Possible loss of precision found long required int
* there is no direct way to specify byte and short literals explicitly, but indirectly we can specify. Whenever we are assigning integral literal to the byte variable & if the value within the range of byte then compiler treats it automatically as byte literal. Similarly short literal also.
eg: byte b = 10;
byte b = 127;
byte b = 128; CE: Possible loss of precision found int required byte

Comments
Post a Comment