Difference between literal and constant in Java

1. Introduction

In Java, a literal is a syntactic element that represents a fixed value in the source code. For example, when you write int i = 1;, 1 is a literal. A constant is a variable whose value cannot be changed once assigned, typically declared with the final keyword.

2. Key Points

1. Literals are directly written in the code and their values are 'literal' - a number, text, or other information that represents a constant value.

2. Constants are defined as variables in code and marked as unchangeable with the final keyword.

3. A literal can be used to initialize a constant.

4. Constants are typically static, meaning they are shared across all instances of a class.

3. Differences

Literal Constant
Fixed value placed directly in the code. Variable whose value cannot change once assigned.
Does not have a name; it’s just a value. Has a name and is referenced in code using that name.
Its value is known at compile-time and does not change. Defined as final, but the initial value can be set dynamically during runtime (e.g., final static values set in static blocks).

4. Example

public class LiteralAndConstantExample {
    // This is a constant
    private static final int MAX_USERS = 10; // 10 is a literal used to initialize the constant

    public static void main(String[] args) {
        // Using the literal directly in the code
        System.out.println("Maximum number of users: " + 10);

        // Using the constant in the code
        System.out.println("Defined constant for max users: " + MAX_USERS);
    }
}

Output:

Maximum number of users: 10
Defined constant for max users: 10

Explanation:

1. The number 10 is used as a literal to represent itself in the code.

2. MAX_USERS is defined as a constant using the final keyword and is initialized with the literal 10.

3. When we print these values, both the direct literal and the constant represent the same value in the output.

5. When to use?

- Use a literal when you need to represent a fixed, unchanging value directly in your code.

- Use a constant when you have a value that you want to define once and use throughout your code, giving it a meaningful name and the ability to ensure it does not get modified.

Comments