Skip to main content

Java Fundamentals

Java Literals

Literals

In programming, we can use some fixed values/constants in our code. These fixed values are called Literals. These values are not variables or expressions but are constants that retain their fixed value throughout the program. 

Types of Literals

In Java, some common types of literals are:

  • Integers (int) - Integers are whole numbers that do not contain any decimal points. They can be positive or negative numbers such as 5, -11, 0, or 12. In Java, the term 'int' refers to this type of integer literal.
int x = 101;
  • Floating-point numbers (double) - Floating-point numbers are numbers that contain decimal points. They can also be positive or negative, and they include values such as 2.5, 6.76, 0.0, or -9.45. In Java, the term 'double' is used to refer to this type of literal. 
double a = 101.12
  • Char literals - Character literals are used to represent single characters, letters, or symbols in the program. They are often used when dealing with individual characters rather than strings of characters. In Java, the keyword 'char' is used to refer to this type of literal. 
char ch = 'a';
  • String (text): A string is a sequence of characters that is enclosed within double quotation marks. Strings are used to represent text and can include any combination of letters, numbers, symbols, and spaces. "Hello" and "Learnyard Java Course" are both examples of String literals in Java.
String s = "Hello";
  • Boolean literal: A boolean literal can be either true or false, indicating whether a condition is satisfied or not. These literals are essential for controlling the flow of the program and making logical decisions based on specific conditions.
boolean b = true;

Quiz: