最终String s ="Hello World"与String s ="Hello World"相同吗?

Aro*_*ora 4 java string final class

如果一个类被定义为final并且我们声明了最终类的实例......它会有什么不同吗?或者final在这种情况下是多余的?

final String s = "Hello World" 
Run Code Online (Sandbox Code Playgroud)

与...一样

String s = "Hello World"
Run Code Online (Sandbox Code Playgroud)

Dav*_*Yee 6

final变量上使用时,意味着无法重新分配变量.请考虑以下示例:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您尝试运行它,您将收到以下错误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)
Run Code Online (Sandbox Code Playgroud)

现在,我想你是在想具体是否finalString数据类型前面是否重要.虽然您可能听说过这String是不可变的,但您仍然可以重新分配类似于String s = "Hello World!";另一个字符串值的内容.这种区别是由于您实际上正在重新分配String s新字符串的引用.因此,以下内容有效:

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

Output: Goodbye World!
Run Code Online (Sandbox Code Playgroud)

但您可以使用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
Run Code Online (Sandbox Code Playgroud)

final声明是伟大的,如果你想确保没有人可以改变你使用String的参考.您也可以使用final其他数据类型来防止引用被更改.


ajb*_*ajb 5

final变量与类是否相关无关final.

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

String s2 = "Hello World";
s2 = "Goodbye";  // legal
Run Code Online (Sandbox Code Playgroud)