Table of Contents
The values assigned to variables are called literals. Here are the different types of literals assigned to variables of the corresponding type,
Integer literals can be any whole numbers. Decimal values with base 10 from 0 to 9, such as 40, binary values with base 2, that is 0 and 1, such as 0c01001, hexadecimal values with base 16, that is, numbers 0 to 9 and letters A to F, such as 0x1d.
Floating-point literals are numbers with fractional components such as 2.9, 2.11, etc. The use of E or e at the end of the number indicates exponentiation. For example, 8.37E6, e+394, etc. With Java SE 7, the support for the underscore (_) character in numeric literals was added to improve the readability of large data.
However, a number cannot begin or end with an underscore. An underscore cannot be placed beside the decimal point in a floating-point number, before a suffix, L or F, before or after binary/hexadecimal symbols like b or x. Some examples of valid use of underscore are 9449_3848_3948_2944L, 2.43_37F, 0b11010111_11100100_00010111. Examples of invalid use of underscores are _3837, 2.43_37F, 0x_83.
Character literals can be symbols such as letters or numbers and are enclosed in single quotes, for example, c, $, etc. For characters that cannot be enclosed in single quotes, escape sequences are used.
Boolean literals have only two values, true and false.
The null literal is assigned to a reference variable that does not point to any memory address. That is, the variable still does not refer to any object. For example, Vehicle bike = null;
A String literal is a sequence of characters within double quotes, for example, “This is a string literal”, “One\nTwo”, etc.
An escape sequence is used to represent characters that cannot be passed as values directly to a string. It is symbolized by the backslash () character which indicates everything succeeding it has a special meaning.
An example is the new line character or tab character. Similarly, characters that have special meaning in Java such as \ or “, also need escape sequences. They are also used to provide formatted output. Here are the escape sequences supported by Java,
- \b: Backspace
- \t: Horizontal tab
- \n: New line
- \’: Single quote
- \\: Backslash
- \r: Carriage return
- \”: Double quotes
- \f: Form feed
- \xxx: Octal value xxx between 000 and 0377
- \uxxxx: Unicode with encoding xxxx with one to four hexadecimal digits
The hexadecimal escape sequence contains a \u symbol followed by four hexadecimal digits. The octal escape sequence contains a backslash followed by three digits.