Yes, Sonar is correct. Using new String()
is pretty much never a good idea.
The reason for this is, that the JVM caches Strings, so that you don't need to create a new object on the heap every time (this is why sometimes wrongly comparing strings with ==
works - They are both referring to the same cached instance on the heap).
Constructing a String yourself will circumvent that built-in cache and can lead to performance problems down the line. If all you need is an empty String just assign it:
String temp = "";
Or, if you just want to declare a String since you want to assign it later, just don't assign anything to it!
String temp;
if(condition()) {
temp = "hello!";
} else {
temp = "bye!";
}
If you plan on concatenating to your empty String in a loop though read this question about the attached performance issues and how to handle them.