Literals

Any constant value which can be assigned to the variable is called Literals

error

Integer type literal:For integral data type we can specify literal value in the following way.

1.Decimal literal (base 10):
example:

int x = 10;

2.Octal form literal (base 8):
example:

int x = 010;

3.Hexadecimal literal (base 16):
example:

int x = 0x0010;

Floating-point literal:For floating data type we can specify literal value only in decimal form and we cannot specify in octal and hexadecimal form.

float f = 123.456; (we get compile time error because JVM by-default considered literals as Double )

float f = 123.456f; (valid because we explicit double into float)

double d = 13.258; (valid)

** By-default every floating point literal is of double type and we cannot assign directly to the float variable.But we can specify floating point literal as float type by suffixed with f or F.

**we can assign integral literal directly to floating point variables but we cannot assign a integral variables with floating point literal.

double d = 10; (valid)

int x = 10.2; (invalid)

boolean literal:The only allowed value for boolean data type are true or false.

boolean b = true; (valid)

boolean b= 10; (invalid because we assign integer value to boolean type)

boolean b= True; (invalid because the value of boolean literals should be in lowercase)

char literal:We can specify char literal as single character within single quotes.

char ch = 'a'; (valid)

char ch = "a"; (invalid because we cannot assign a string literal to char data type)

char ch = 'ab'; (invalid because we can only assign single alphabet character to char data type.)

** We can specify char literal as integral literal which represent unicode value of the character and that integral can be specified either in decimal,octal and hexadecimal forms.But allowed range is 0 to 65535.

char ch = 97; (valid)

char ch = 0777; (valid)

char ch = 0xface; (valid)

** We can represent char literal in Unicode representation which is nothing but '\uxxxx' .

char ch = '\u0062'; (valid)

String literal:Any sequence of character within double quotes is treated as String literal.

String s = "hello world";

NOTE:

1.For integral data type until 1.6 version we can specify literal value in the following ways:

Decimal form,Octal form and Hexadecimal form.

But from 1.7 version onwards we can specify literal value even in Binary form also(allowed digit are 0 & 1):

Literal value should be prefixed with 0b or 0B.

int x = 0b1111;

2.Usage of underscore symbol in numeric literal from 1.7 version onwards we can use underscore(_) symbol between digit of numeric literal.

double d = 1_23_456.7_8_9;

int x = 123_32_43;










NEXT PAGE



PREVIOUS PAGE