Java Literals

In this tutorial you will learn about the Java Literals and its application with practical example.

Java Literals

Literals are used to express certain fixed value within the source code of the program. They are used to represented a value directly in the code without any computation. Literals can be assigned to any primitive type variable.

Example:-

Here,

boolean:- is data type.

flg:- – is variable

false:- is literal.

In Java, literals can be used to represent value of an integer, floating-point number, or string type. Here are some of valid literals examples –

In Java, literals can be of following types –

Integer Literals

Integer literal are used to represent a decimal, binary, or hexadecimal value. Integer literals are used to initialize variables of integer data types byte, short, int and long.Integer literal that ends with l or L is of type long. In Java, a binary literals starts with 0b, and hexadecimal literals starts with 0x and rest every integer literal is a decimal literals.

Example:-

Floating-point Literals

A floating-point literal is used to represent value for a float and double variable or constants. A decimal floating-point literals is composed of a sequence of decimal digits followed by either a decimal fraction, a decimal exponent, or both. If a floating-point literal ends with f or F, it’s of type float. Otherwise, it’s of type double. A double type can optionally end with D or d. They can also be expressed in scientific notation using E or e.
Example1:-

String & Character literals

String literals are represented as a sequence of characters surrounded by double quotes and a character literal is represented as a single character surrounded by single quotes. Java also allows use of escape sequences in string and character literals. For example, \b (backspace), \t (tab), \n (line feed), \f (form feed), \r (carriage return), \” (double quote), \’ (single quote), and \\ (backslash).

Recommended:-  Java Introduction

Example:-

Here, ‘A’ is a character literal and “W3Adda Java Tutorial” is a string literal.

Boolean Literals

Boolean literals are used to represent true and false value.

Example:-

Here, true is a boolean literal which is assigned to the variable flg.

In this tutorial we have learn about the Java Literals and its application with practical example. I hope you will like this tutorial.