简体   繁体   中英

Immutable strings and final keyword

I typically place global compile-time variables (like constants that i use such as avogadro's number or whatever) into public static final variables. However, i hadn't ever considered if this actually does anything for Strings. Is there any point in making a String final since it's already immutable?

It's a theoretical more than a practical question.

final is different from immutable. final means the handler (variable) cannot point to another object. Immutable means the object can't change its internal state.

  • static final Foo foo = new Foo(1) means you can't later have foo = new Foo(2)
  • if Foo is immutable, it means that once you create it, you can't change its fields. Eg you can't have Foo foo = new Foo(1); foo.setValue(3); Foo foo = new Foo(1); foo.setValue(3);

You're getting the reference to the string and the actual string confused. Immutable describes the actual string object and means you can't change the value of that object. Final refers to the reference to a string object and means that you can't change what string that reference is pointing to. Consider the following code: public static String str = "happy"; ... str = "sad";

This code creates two string objects, one that contains the value "happy" and one that contains the value "sad". Neither of these objects (because Strings are immutable) can be changed. str is a reference and can be made to point to either of these objects; however, were we to change the first line of code to: public static final String str = "happy"; str = "sad" would no longer be legal. Because we have changed str to be a final variable, it cannot be made to point to different objects.

final only applies to the reference. If you declare an Object final it doesn't mean that the object can't be changed, it disallows the reference to the object to be changed. It's not the same thing as immutable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM