When learning Java, one of the most basic yet important concepts you’ll encounter is literals. A literal in Java is a constant value that is directly used in the code. Unlike variables, literals do not change during program execution. They represent fixed values such as numbers, characters, or strings that you type directly into your program.
For example:
int age = 20; // 20 is an integer literal
char grade = 'A'; // 'A' is a character literal
String name = "John"; // "John" is a string literal
Here, 20, 'A', and "John" are all literals.
Types of Literals in Java
Java supports different types of literals based on the data they represent:
1. Integer Literals
Integer literals are whole numbers without decimal points.
They can be written in different number systems:
-
Decimal (base 10):
int x = 25; -
Octal (base 8):
int y = 025; -
Hexadecimal (base 16):
int z = 0x1A; -
Binary (base 2):
int b = 0b1010;
2. Floating-Point Literals
Used to represent decimal values.
-
Example:
double pi = 3.14159;
float rate = 6.5f;
Here, 3.14159 is a double literal, and 6.5f is a float literal (notice the f suffix).
3. Character Literals
Represent a single character inside single quotes.
-
Example:
char letter = 'A';
char digit = '7';
char symbol = '#';
Java also supports escape sequences like '\n' (new line), '\t' (tab), and '\\' (backslash).
4. String Literals
A sequence of characters enclosed in double quotes.
-
Example:
String greeting = "Hello, World!";
5. Boolean Literals
Only two possible values: true and false.
-
Example:
boolean isJavaFun = true;
boolean isCold = false;
6. Null Literal
Represents the absence of a value and can only be assigned to object references.
-
Example:
String str = null;
Example Program Using Literals
public class LiteralsExample {
public static void main(String[] args) {
int number = 100; // Integer literal
float price = 99.99f; // Floating-point literal
char grade = 'A'; // Character literal
String name = "Java"; // String literal
boolean passed = true; // Boolean literal
System.out.println("Number: " + number);
System.out.println("Price: " + price);
System.out.println("Grade: " + grade);
System.out.println("Name: " + name);
System.out.println("Passed: " + passed);
}
}
Output:
Number: 100
Price: 99.99
Grade: A
Name: Java
Passed: true
Conclusion
Literals in Java are the building blocks of your program. They provide fixed values directly in the source code, making it easier to write and understand programs. By mastering literals, you lay a strong foundation for learning more advanced Java concepts.
Comments
Post a Comment