如何处理Final Strings?

Rac*_*hel 6 java string types

是否有制作String as final或者我们可以制作的优势String as final?我的理解是,由于字符串是不可变的,没有必要使它成为最终的,这是正确的还是他们想要制作的情况String as Final

码:

private final String a = "test";

or 

private String b = "test";
Run Code Online (Sandbox Code Playgroud)

Fer*_*deh 11

final意味着引用永远不会改变.String不变性意味着不同的东西; 它意味着当String创建a(值,而不是引用,即:"text")时,它不能被更改.

例如:

String x = "Strings Are ";
String s = x;
Run Code Online (Sandbox Code Playgroud)

现在s和x都引用相同的String.然而:

x += " Immutable Objects!";
System.out.println("x = " + x);
System.out.println("s = " + s);
Run Code Online (Sandbox Code Playgroud)

这将打印:

x = Strings Are Immutable Objects
s = Strings Are
Run Code Online (Sandbox Code Playgroud)

这证明任何String创建都无法更改,并且当发生任何更改时,String会创建一个新的.

现在,因为final,如果我们将x声明为final并尝试更改其值,我们将得到一个异常:

final String x = "Strings Are ";
x += " Immutable Objects!";
Run Code Online (Sandbox Code Playgroud)

这是一个例外:

java.lang.RuntimeException: Uncompilable source code - cannot assign a value to final variable x
Run Code Online (Sandbox Code Playgroud)