Java Tutorial: Literals in Java

In Java programming, a literal means a string that consists of a fixed or set value in the source code. Java literals are the way that provide you to set certain values throughout the course of your programs. A literal is text that may have its content copied to a variable or is used as a constant expression.

Here are the different types of literals in Java:Here are the different types of literals in Java:

Integer Literals

Floating-Point Literals

Character Literals

String Literals

Boolean Literals

Null Literals

I will now briefly describe each type of literal and provide an example for a better understanding.

1. Integer Literals

An integer literal is used where there is need to represent an integer figure from 0 to a positive whole number. They can be expressed in different number systems:They can be expressed in different number systems:

Decimal (Base 10): This particular form is by far the most widespread, it involved simple whole numbers from 0 through 9.

Octal (Base 8): Uses digits 0-7 and a leading 0.

Hexadecimal (Base 16): Uses digits 0-9 and letters A-F, and a leading 0x or 0X.

Binary (Base 2): Uses digits 0-1 and a leading 0b or 0B (available from Java 7 onwards).

2. Floating-Point Literals

Floating-point literals represent decimal numbers and can be expressed in either standard decimal notation or scientific notation:

  • Decimal Notation:


Scientific Notation
:


Floating-point literals default to double precision. To specify a float literal, append an f or F:

3. Character Literals

Character literals represent single characters and are enclosed in single quotes:


Character literals can also represent Unicode characters using escape sequences:

4. String Literals

String literals represent a sequence of characters enclosed in double quotes:

5. Boolean Literals

Boolean literals represent the values true and false:

6. Null Literals

The null literal represents a null reference:

Examples

Here are some examples demonstrating the use of different types of literals in Java:


This code explains how to work and publish different types of literals in Java. Copy and paste the following to your java environment and see the output and how all these literals are interpreted and used:

Post a Comment

Previous Post Next Post