Java: Literals


Java Literals Reference

This Java video tutorial examines some of the basic uses of literals in Java. Literals are simply representations of data values that are used in Java programs. The compiler reads literals and interprets them as data values. There are Java literals for all of the primitive data types, as well as some of the more complex data types.

int iMyInt1 = 2959774;
int iMyInt2 = 2_959_774;

The most basic literal is an integer literal like 2959774. However, long integer literals get more difficult to read. So, Java allows the use of under score characters in numeric literals, as long as they do not come at the beginning or end. This means that the literal 2_959_774 is equivalent to 2959774. The under scores allow the read to break up the number on to more manageable pieces, much like the ordinary use of commas after every three digits in standard notation: 2,959,774. Integer literals may be used with any integer-valued type, as well as the floating-point data types.

double iMyDouble1 = 28.63;
double iMyDouble2 = 3.64e3;
double iMyDouble2 = 923.34e-4;

In addition to integer literals, floating-point data types can store literals with a fractional part. This includes literals with a simple decimal point like 28.63, as well as numbers with as exponent attached; this notation is similar to scientific notation in that the number is multiplied by a power of 10. For example, we could write a literal as 3.64e3, which is equal to 3640. We can also use negative exponents like 923.34e-4 which is equal to .092334.

boolean bMyBool1 = true;
boolean bMyBool2 = false;

For the boolean data type, we have exactly two literals. These are simply the words true and false.

char cMyChar = 'X';

The char literals are single letters enclosed in quotes: 'X'. Similar to the char literals, are the String literals which consist of one or more characters enclosed in double quotes: "XoaX.net". Note that 'X' and "X" are different; the first is a char and the second is a String, and they can not be used interchangeably. Also, we have been using String literals up to this point. However, we have not yet introduced the String data type.

The remaining literals are involve alternative number bases, character codes, and escape sequences. These subjects will be coverd in upcoming lessons.