Java literals : Using literals in java


Java literals are the elements that are used in an invariant manner in a program. A literal signifies a fixed value and is represented directly in the code without requiring computation.

Example:
int num1=90;
float num2=35.7F;
char ch=’s’;

Literals are also called constants. Literals can be numbers, characters or string. A literal is used whenever a value of its type is allowed.

Types of java literals:
  1. Integer literal
  2. Floating point literal
  3. Boolean literal
  4. Character literal
  5. Null literal
  6. String literal

Integer Literal
An int value is represented using an integer literal. It is a 32-bit integer value in java. Integers are most commonly used type in any program. Any whole number value is an integer literal.

Integer literals can be expressed as,
  1. Decimal value expressed in base 10. Decimal numbers appear as ordinary number in a program (example: int x=173;)
  2. Octal value expressed in base 8. Octal numbers appears with a leading 0 (example: int x=0173;).
  3. Hexadecimal value expressed in base 16. Hexadecimal numbers appears with a leading 0x or 0X in a program (example: int x=0x7B; or int x=0X7B)

Floating point literal
Floating point literals represent decimal numbers with a fractional part like “234.98”.

Floating point literals can be expressed as,
  1. A number with decimal point.
  2. Exponent is indicated by an “E” or “e” followed by a decimal number. The number can be negative or positive.
  3. Numbers with suffix “D”, “d”, “F” or “f”.

A float literal is represented by “F” or “f” appended to the value and a double literal is represented by “D” or “d” appended to the value.

Boolean literal
Boolean literals are simple and have only two possible values i.e. “true” or “false”. A Boolean value does not convert into any decimal representation. A “true” Boolean literal is not equal to 1 on java and a “false” Boolean literal is not equal to 0. Only variables declared as boolean can hold boolean values.


Character literal
Character literals are enclosed in single quotes. We can enter any of the visible ASCII character directly in the single quotes. Single characters that cannot be directly entered are hyphen (-) and backslash (\).

Null literal
When we create an object, a certain amount of memory space is allocated for that object. The starting address of this memory is stored in an object, that is, a reference value. However, sometimes it is not desirable for the reference variable to refer that object. In such a case, a null value is assigned to the reference variable.
Example: obj=null;

String literal
A string literal can be defined as a sequence of characters enclosed in double quotes. The characters can be printable or non-printable. However, escape sequence is used to represent backslash, double quotes and non-printable characters.

No comments:

Post a Comment