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";
It is not possible. Strings are immutable, which means that they cannot be changed.
In Java, we know that String objects are immutable means we can't change anything to the existing String objects. final means that you can't change the object's reference to point to another reference or another object, but you can still mutate its state (using setter methods e.g).
They are immutable but their references can be changed. To overcome this we can use "Final String s1 = "Final String" " the final keyword won't allow any assignment to s1 except at the time of First Declaration, making it truly immutable.
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
It means that that variable can never even point to a different string.
(And yes, a String object is immutable... but a variable could point to a different instance of String. Unless it's final.)
(edit -- in your example, you didnt name your variable...
final String x = "test";
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With