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

If a class is defined as final, and we declare an instance of the last class ... Doesn't matter? or finalin such cases will be redundant?

final String s = "Hello World" 

same as

String s = "Hello World"
+4
source share
3 answers

When you use finalfor a variable, it means that it cannot be reassigned. 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 start it, you will receive an error message 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)

, , , final String. , , , String , - String s = "Hello World!"; . , String s . , :

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

Output: Goodbye World!

final, :

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

final , , String. final , .

+6

final , final.

final String s = "Hello World";
s = "Goodbye";  // illegal

String s2 = "Hello World";
s2 = "Goodbye";  // legal
+5

, :

final String s = "123";
s = "234"; // doesn't work!

final class A {
}

class B extends A { // does not work!
}

immutable (, String). . ( , .)

+4

Source: https://habr.com/ru/post/1543133/


All Articles