Is final String s = "Hello World" same as String s = "Hello World"?

class, final, java, string

Solution

When you use `final` on the variable, it means that it cannot be re-assigned. Consider the following example:

public class FinalExample {
    private final String a = "Hello World!"; // cannot be reassigned
    private String b = "Goodbye World!"; // can be reassigned

    public FinalExample() {
        a = b; // ILLEGAL: this field cannot be re-assigned
        b = a; 
    }

    public static void main(String[] args) {
        new FinalExample();
    }
}

If you try to run it, you will get an error on `a=b`:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    The final field FinalExample.a cannot be assigned

    at FinalExample.<init>(FinalExample.java:7)
    at FinalExample.main(FinalExample.java:12)

Now, I think you were wondering whether it matters to have a `final` or not in front of the `String` data type specifically. Although you may have heard that `String` is immutable, you can still re-assign something like `String s = "Hello World!";` to another string value. This distinction is due to the fact that you are actually re-assigning the reference of `String s` to a new string. Therefore, the following is valid:

String s = "Hello World";
s = "Goodbye World!";
System.out.println(s);

Output: Goodbye World!

But you can use the `final` declaration to prevent this change:

final String s = "Hello World";
s = "Goodbye World!";
System.out.println(s);

Output: 
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    The final local variable s cannot be assigned. It must be blank and not using a compound assignment

The `final` declaration is great to use if you want to ensure that no one can change your `String` reference. You can use `final` for other data types as well to prevent the reference from being changed.

Problem

If a class is defined as `final` and we declare an instance of the final class... Would it make any difference? or is `final` in such cases would be redundant? ``` final String s = "Hello World" ``` same as ``` String s = "Hello World" ```

Original source