Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does it make sense to define a final String in Java? [duplicate]

Tags:

java

string

final

Possible Duplicate:
String and Final

From http://docs.oracle.com/javase/6/docs/api/java/lang/String.html I can read that:

Strings are constant; their values cannot be changed after they are created.  

Does this mean that a final String does not really make sense in Java, in the sense that the final attribute is somehow redundant?

like image 627
Campa Avatar asked Apr 19 '12 17:04

Campa


People also ask

How do you define a final string in Java?

The string is immutable means that we cannot change the object itself, but we can change the reference to the object. The string is made final to not allow others to extend it and destroy its immutability.

Can we declare string as final?

The String is immutable in Java because of the security, synchronization and concurrency, caching, and class loading. The reason of making string final is to destroy the immutability and to not allow others to extend it. The String objects are cached in the String pool, and it makes the String immutable.

Can we use final with string in Java?

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

What will make difference if we add final in string?

If a variable is marked as final then the value of that variable cannot be changed i.e final keyword when used with a variable makes it a constant. And if you try to change the value of that variable during the course of your program the compiler will give you an error.


2 Answers

The String object is immutable but what it is is actually a reference to a String object which could be changed.

For example:

String someString = "Lala"; 

You can reassign the value held by this variable (to make it reference a different string):

someString = "asdf"; 

However, with this:

final String someString = "Lala"; 

Then the above reassignment would not be possible and would result in a compile-time error.

like image 113
Mike Kwan Avatar answered Sep 18 '22 23:09

Mike Kwan


final refers to the variable, not the object, so yes, it make sense.

e.g.

final String s = "s"; s = "a"; // illegal 
like image 34
MByD Avatar answered Sep 18 '22 23:09

MByD