Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with Final Strings?

Tags:

java

string

types

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";
like image 878
Rachel Avatar asked Jan 16 '11 07:01

Rachel


People also ask

Can you modify a final String?

It is not possible. Strings are immutable, which means that they cannot be changed.

What does final String do?

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).

Can we use final with String?

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.


2 Answers

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
like image 50
Feras Odeh Avatar answered Oct 04 '22 01:10

Feras Odeh


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";

)

like image 40
david van brink Avatar answered Oct 04 '22 00:10

david van brink