Java – Is it good practice to use java.lang.String.intern()

javastring

The Javadoc about String.intern() doesn't give much detail. (In a nutshell: It returns a canonical representation of the string, allowing interned strings to be compared using ==)

  • When would I use this function in favor to String.equals()?
  • Are there side effects not mentioned in the Javadoc, i.e. more or less optimization by the JIT compiler?
  • Are there further uses of String.intern()?

Best Answer

This has (almost) nothing to do with string comparison. String interning is intended for saving memory if you have many strings with the same content in you application. By using String.intern() the application will only have one instance in the long run and a side effect is that you can perform fast reference equality comparison instead of ordinary string comparison (but this is usually not advisable because it is realy easy to break by forgetting to intern only a single instance).