Saturday, 3 January 2015

Java Literals

Integer Literals

An integer literal/constant can be of any one of the following types. It is like C/C++.


  • int (187, -98, 0 etc.)
  • long (897, 776L, -656L)
  • octal (017, 033, -034 etc.)
  • hexadecimal (0x11, 0x1B etc.)
A decimal integer  constant is treated as an int by default. If a decimal integer constant is larger than the range of the int, it is declared to be of type long. A decimal integer constant can be made long by appending l or L to it. A leading zero placed at the beginning of an integer constant indicates that it is an octal integer constant. A leading 0x or 0X placed at the beginning of an integer constant indicates that it is a hexadecimal constant.

Floating Point Literals

Floating point literals represent real values. They may have a fractional part in addition to the integral part. The default data type of a floating-point literal is double, but it can be explicitly designated by appending the suffix d (or D) to the real constant. A floating-point literal can be specified to be a float by appending the suffix f (or F).

Boolean literals

Java defines two boolean literals  true and false.

Character Literals

There are many ways of expressing character literals:

  • Enclosing character within single quotes (as in C/C++)
  • Escape sequences  (as in C/C++)
  • Octal Notation  (as in C/C++)
  • Unicode Notation  (different from C/C++)
Characters literals can be expressed by enclosing the character in single quotes:

'A', 'B', 'a' etc.

Character literals can also be expressed using escape sequence:

'\n', '\t', '\r', '\b' etc.

Characters can be expressed using octal notation. The ASCII code of the character is enclosed in single quote prefixed with '\':

'\71', '\101' etc.

A Java character is of two bytes. Escape sequence and octal notation can be used only to represent ASCII characters. Unicode characters can be represented using Unicode notation:

'\u000a', 'ufff', '\u001A' etc.

Unicode as specified above consists of 4 hexadecimal digits so its range can be from 0 to ffff (0 to 65535).

String Literals

A String is a sequence of characters. A String literal is a set of characters that is enclosed within double quotes.

When a String literal is declared, Java automatically creates an instance of the class String and initializes it with the literal value.

No comments:

Post a Comment