What are Literals in Java?

They are used to represent the constant value. Literals are source code representation of a fixed value or the sequence of characters which represents the constant value that is to be stored in a variable.

There are five types of literals in Java.

  • Integer Literals
  • Boolean Literals
  • Character Literals
  • String Literals
  • Floating Point Literals

Now let us see more details about these literals.

Integer Literal :-

The integer literal can be used to create int value. They can be used to initialize the group data types like byte, short, int and long.

The number without decimal is the integer literals. The java compiler treats all the integer literals as int by default. We can assign different values to integer literal. They are:

  • Decimal Literals – The decimal literal is not prefixed with ‘0’ or ‘0b’ or ‘0x’.
    For example:  int d = 10;
  • Binary Literals – The binary literal is prefixed with ‘0b’.
    For example: int x =  0b1010;  //the value in decimal is 10
  • Hexadecimal Literals – The hexadecimal literal is prefixed with ‘0x’.
    For example: int a = 0x17; //the value in decimal is 23
  • Octal Literals – The octal literals are prefixed with ‘0’.
    For example: int y = 023; //the value in decimal is 19
  • Long Literals – The long literals are suffixed with ‘l’ or ‘L’.
    For example: long b = 34562780l; // the value in decimal is 34562780
    long b = 23456791L; // the value in decimal is 23456791

Boolean Literal :-

The Boolean literal is used to represent the two values i.e. either true or false. We can assign the true or false value to the variable. These values are case sensitive.
For example:

boolean flag1 = true;
boolean flag2 = false;

Character Literal :-

The character literal is a 16 bit Unicode character where it is enclosed in single quotes. It use primitive data type char.

Some of the examples to represent character literal are:

Escape sequence Meaning
\\ Backslash
\a Alert
\b Backspace
\’ Single quotation mark
\’’ Double quotation mark
\n New line
\t Tab
\r Carriage return
\f Formfeed
\d Octal
\xd Hexadecimal
\ud Unicode character

String Literal : –

The string literal are the sequence of characters which are enclosed in double quotes. The string literal should occur in single line.
For example:

String str = “good morning”;
String str1 = “hello world”;

Floating Point Literal : –

The floating point literal can be used to represent the decimal values with a fractional component. These literals are double data type. These literals contain the fractional parts and if the floating point literal is suffixed with letter f or F then it is float type.
These literals include the float and double data types. In floating point literals double is the default data type. To represent the float literal f is suffixed and to represent the double literal d is suffixed.
For example:

float x = 2.7f;
double x = 54.888d;