Reputation: 618
I have used the below statement in my code to declare an empty string.
String temp = new String();
This has led to an issue raised by Sonarqube. So what would be the efficient way to fix this ? Is the below declaration a good way?
String temp = "";
Upvotes: 3
Views: 1058
Reputation: 3557
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.
Upvotes: 0
Reputation: 3767
Sonar is correct in that you shouldn't be using new String()
. Initializing to empty string (String temp = ""
) is better. But if you do not use the value of empty string in any case, you should not initialize the variable to anything. You should only initialize a variable to a value you intend to use.
This is perfectly, and usually, acceptable:
String temp;
Your conditional logic should cover all cases of assignment.
Upvotes: 1
Reputation: 3519
/**
* Initializes a newly created {@code String} object so that it represents
* an empty character sequence. Note that use of this constructor is
* unnecessary since Strings are immutable.
*/
public String() {
this.value = new char[0];
}
Above souce code of String class depicts that use of this constructor is unnecessary. Every time you will create new object in heap. Better is to use String pool.
Upvotes: 0