String == considered as error for interned string

  • Version 7.9.1 (build 27448)
  • Java provides an intern() method on Strings to reduce space taken by constants and frequently used Strings. Interned Strings can be compared using the == operator as this increases program speed.
  • We submitted the following code which uses interned Strings (see assert at beginning). This code works (it has been in production for eight years). But we get an error that would be applicable if the Strings were not interned. String constants are automatically interned by the compiler so using them as status values was very natural before enums were introduced into the language and easy to debug. SonarQube should not generate this error if it is obvious that the field is interned (as here with the assert) or explicitly mention that interned values are not concerned by the error (less experienced programmers may not know they exist) and mention a way of getting rid of the error (for example an assert)
  • Rewrite code using enum values rather than Strings.

hello @IanGriffiths and welcome to this forum!

You are right that interned Strings can be compared using reference equality and current implementation is not capable to take it into consideration (it’s quite complicated to make analysis understand that).

However, I don’t think it is worth to improve the rule in this way, as I consider it to be quite a corner case. The speed difference will become significant only in narrow class of applications, and one could argue that the risk of introducing hard to find bugs is not worth potential speed improvement.