Wednesday 23 November 2011

Literals in Java

Integer literals can be decimal, octal, or hexadecimal.

Octal literals begin with zero and only digits 0 through 7 are allowed. For instance:

011


Hexadecimal literals begin with 0x or oX, the digits allowed are 0 through 9 and a through f (or A through F). For instance:

0x0001;


All integer literals are of type int by default. To define them as long, we can place a suffix of L or l after the number.

For char literals, a single character is enclosed in single quotes. You can also use the prefix \u followed by four hexadecimal digits representing the 16-bit Unicode character:

'\u004E', 'A', 'a'


For float literals, we need to attach the suffix F or f. For instance:

float f = 23.6F;
double d = 23.6;


In the case of double literals, we can add D or d to the end, however this is optional.

Uninitialized variables

Static and instance variables of a class are initialized with default values for the particular datatype. Local variables are never given a default value; they have to be explicitly initialized before use. When an array is created, all its elements are initialized to their default values, even if the array is declared locally.

2 comments: