How to deal with Final Strings?

Are there any advantages in creating, String as finalor can we do String as final?, I understand that since String is immutable, it makes no sense to make it final, is it right or is it a situation when you want to do String as final?

the code:

private final String a = "test";

or 

private String b = "test";
+3
source share
6 answers

Final means that the link can never change, while the immutability of String means something else, it means that when a string is created (the value is not refrence ie: "text"), it cannot be changed look at this:

String x="Strings Are ";
String s=x;

now s and x both point to the same line:

x+=" Immutable Objects!";
System.out.println("x= "+x);
System.out.println("s= "+s);

This will print:

x= Strings Are Immutable Objects
s= Strings Are

, , - , .

final, x final ,

final String x="Strings Are ";
x+=" Immutable Objects!";

java.lang.RuntimeException: Uncompilable source code - cannot assign a value to final variable x
+9

, .

( , String ... String. .)

( - ...

final String x = "test";

)

+4

final , , . , .

final String a = "test";
String b = "hello";

a = "world"; // error, a can't change reference to the String object "world"
b = "two"; // ok, b points to a different String object "two"
+4

final .

final String s = "abcd";
// later in the code
s = "efgh";  // This will not compile

, String, , . setter, append ..

+1

, " ", , " ":

  • , ( ) , ,
  • .

1, 10 , . Way 2, , , , .

0

, , String , .

private final String a = "test";

slightly more effective, perhaps clearer than

private static final String a = "test";
0
source

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


All Articles