Final vs Immutability in Java


The "final" keyword in Java may be employed to define a constant value as well as prevent a variable, method, or class from being changed or overridden. On the other side, immutability describes an object's characteristic of keeping a constant state across the course of its existence. The values of an object don't change after it is formed.

Variables, methods, and classes are constrained by the "final" keyword, but immutability goes a step farther by guaranteeing that the object's whole state is preserved.

Let us learn the key differences between final vs immutability in this article.

Final in Java

The final keyword in Java has several characteristics:

  • Final variables: Their initial values cannot be modified after initialization. They are frequently employed to declare unchangeable or unchanging values.

  • Final Methods: They cannot be modified by subclasses, guaranteeing that they behave consistently. They help maintain the effectiveness of significant procedures.

  • Final classes: They are unable to be extended by other classes, guaranteeing that their implementation is unaltered. Final classes are frequently used to build security or utility classes.

  • Initialization: To ensure that final variables have a known value, they must be given a value either during declaration or in the constructor.

  • Performance: The usage of final enables the compiler to optimise code more successfully, potentially resulting in improved performance.

  • Security: Final improves the security of Java programms by preventing unauthorised alteration of sensitive data or behaviour.

Immutability in Java

In Java, an immutable class is one where the object's content cannot be changed once it is created. To create an immutable class, follow these requirements:

  • Declare the class as final to prevent inheritance.

  • Declare the class's data members as private to restrict direct access.

  • Declare the data members as final to prevent modification after object creation.

  • Use a parameterized constructor to initialize all fields with deep copies, preventing modification through object references.

  • Return copies (deep copies) of objects in getter methods instead of the actual object reference to maintain immutability.

By adhering to these characteristics, you can create your own immutable classes in Java, similar to the built-in immutable classes like Integer, Boolean, Byte, Short, and String.

Differences between final and immutability

When it comes to Java programming, understanding the distinctions between "final" and "immutable" is crucial.

  • Final: Preserving Object References and Allowing State Mutation

    Let's start with "final." When an object or variable is marked as final in Java, it signifies that after a value has been given to it, the reference cannot be changed to point to another object or variable. It's important to remember that despite the reference being fixed, using the relevant setter methods still allows you to change the object's state. Therefore, even though the reference itself cannot be altered, you can still use the methods that are accessible to alter the object's internal properties or attributes. In other words, final ensures the stability of the object reference while permitting alterations to its internal state.

  • Immutable: Immutable Values and Reference Flexibility

    Now let's turn our attention to "immutable." In Java, immutability refers to objects whose actual values cannot be changed after creation. However, unlike final, you can modify the reference itself and assign it to another object or variable. This means that although the object's value remains constant, you can change its reference to point to a different instance.

  • Application and Scope: Final and Immutability

    The modifier "final" applies to variables rather than objects in Java. It emphasizes the restriction on changing the reference or variable while allowing modifications to the object's state. On the other hand, immutability applies to objects, indicating that their values cannot be altered once created. It's essential to understand the distinction between these two concepts to ensure the desired behavior of your Java programs.

  • Implications: Object Address and State Mutability

    When we declare an object or variable as final, we are enforcing the permanence of its address. In other words, the reference remains fixed, preventing any changes to where it points. In contrast, immutability highlights the inability to modify the state of an object once it is created. This means that the object's internal values cannot be changed, preserving its integrity and consistency throughout the program's execution.

StringerBuffer()

The code demonstrates the difference between the "final" keyword and immutability in Java. The "final" keyword makes a variable constant and prevents reassignment, while immutability means the object itself cannot be modified.

Algorithm

  • Step 1: Declare a variable "sb" as a final StringBuffer object with the initial value "Hello".

  • Step 2: Append "TP" to the StringBuffer object referenced by "sb" using the append() method.

  • Step 3: Print the updated value of "sb", which will be "HelloTP".

  • Step 4: Attempt to reassign a new StringBuffer object to the variable "sb", which results in a compile−time error.

  • Step 5: Print the value of "sb", but this line will not be executed due to the error in the previous step.

Example

// Java program to illustrate difference between final and immutability
 
public class Tutorialspoint {
    public static void main(String[] args)
    {
        final StringBuffer sb = new StringBuffer("Hello");
 
        //  We can make changes even though reference variable sb is final

        sb.append("TP");
 
        System.out.println(sb);
 
        // Compile time error will appear here. This is because the final variable cannot be reassigned

        sb = new StringBuffer("Hello World");
 
        System.out.println(sb);
    }
}

Output

Tutorialspoint.java:16: error: cannot assign a value to final variable sb
        sb = new StringBuffer("Hello World");
        ^
1 error

Conclusion

To summarize, "final" and immutability have distinct characteristics in Java. The "final" keyword restricts the reassignment of object references but allows modifications to the object's state.

In contrast, immutability prevents changes to an object's values but allows the reference to be reassigned. Understanding the application and scope of "final" and immutability is important for designing reliable Java programs. When an object or variable is declared as final, its address remains fixed, while immutability ensures that an object's internal values cannot be modified. The example code demonstrates the difference, where "final" prevents reassignment, leading to a compile-time error.

Updated on: 11-Jul-2023

585 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements