Issue
Is there any advantage of making String as final
or can we make String as final
?, my understanding is that as String is immutable, there is no point of making it final, is this correct or they are situation where one would want to make String as Final
?
Code:
private final String a = "test";
or
private String b = "test";
Solution
final
means that the reference can never change. String
immutability means something different; it means when a String
is created (value, not reference, i.e: "text"), it can't be changed.
For example:
String x = "Strings Are ";
String s = x;
Now s and x both reference the same String
. However:
x += " Immutable Objects!";
System.out.println("x = " + x);
System.out.println("s = " + s);
This will print:
x = Strings Are Immutable Objects
s = Strings Are
This proves that any String
created cannot be changed, and when any change does happen, a new String
gets created.
Now, for final
, if we declare x as final
and try to change its value, we'll get an exception:
final String x = "Strings Are ";
x += " Immutable Objects!";
Here is the exception:
java.lang.RuntimeException: Uncompilable source code - cannot assign a value to final variable x
Answered By - Feras Odeh
Answer Checked By - Clifford M. (JavaFixing Volunteer)