Introduction
In Java, literals are fixed values that are directly written in the code, such as numbers, characters, or strings. Constants are variables whose values cannot be changed once assigned. Understanding literals and constants is important because they help in writing clear, maintainable, and error-free code. This tutorial explains how to use literals and constants in Java.
Code: Literals and Constants Example
public class LiteralsConstantsExample {
// Constant declaration using final keyword
public static final double PI = 3.14159;
public static void main(String[] args) {
// Integer literal
int age = 25;
// Floating-point literal
float height = 5.9f;
// Character literal
char grade = 'A';
// String literal
String name = "John";
// Boolean literal
boolean isJavaFun = true;
// Printing literals and constant
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Height: " + height);
System.out.println("Grade: " + grade);
System.out.println("Is Java fun? " + isJavaFun);
System.out.println("Value of PI: " + PI);
}
}
Explanation of Each Code Part
1. Class Declaration
public class LiteralsConstantsExample {
- Defines a Java class named
LiteralsConstantsExample. publicmeans it can be accessed from anywhere.- Curly braces
{}define the scope of the class.
2. Constant Declaration
public static final double PI = 3.14159;
final: Makes the variable a constant; its value cannot be changed.static: Belongs to the class, not an object.double: Data type for decimal numbers.PIis a constant holding the value of π.
3. Main Method
public static void main(String[] args) {
- Entry point of the program.
- JVM executes all code inside this method.
String[] argsallows passing command-line arguments.
4. Integer Literal
int age = 25;
25is an integer literal.intspecifies the data type.- Stores whole numbers.
5. Floating-point Literal
float height = 5.9f;
5.9fis a floating-point literal.- The
fdenotes a float type. - Used to store decimal numbers.
6. Character Literal
char grade = 'A';
'A'is a character literal.- Stored in a
charvariable. - Must be enclosed in single quotes.
7. String Literal
String name = "John";
"John"is a string literal.- Stored in a
Stringvariable. - Must be enclosed in double quotes.
8. Boolean Literal
boolean isJavaFun = true;
trueis a boolean literal.- Boolean values can be
trueorfalse.
9. Printing Values
System.out.println("Name: " + name);
- Displays literals and constants on the console.
+operator concatenates strings with variables.
Conclusion
In Java:
- Literals are fixed values written directly in the code.
- Constants are variables declared with
finalthat cannot be changed. - Using literals and constants improves code readability, prevents accidental changes, and makes programs easier to maintain.