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

偶尔善良 提交于 2019-12-03 00:57:33

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.

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

e.g.

final String s = "s";
s = "a"; // illegal

It makes sense. The final keyword prevents future assignments to the variable. The following would be an error in java:

final String x = "foo";
x = "bar" // error on this assignment

References are final, Objects are not. You can define a mutable object as final and change state of it. What final ensures is that the reference you are using cannot ever point to another object again.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!