How to solve the Java String instantiation problem reported by Sonarqube

I used the below statement in my code to declare an empty string.

String temp = new String();

      

This led to the issue raised by Sonarqube. So what would be an efficient way to fix this? Is the following declaration a good way?

String temp = "";

      

+3


source to share


4 answers


Sonar is correct in that you shouldn't use new String()

. Empty string initialization ( String temp = ""

) is better. But if you don't use the empty string value anyway, you shouldn't initialize this variable with anything. You only have to initialize the variable to the value you intend to use.

This is fine and generally acceptable:



String temp;

      

Your conditional logic should cover all assignment cases.

+1


source


/**
     * 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];
    }

      



The suce code for the String class shows that this constructor is not required . Every time you create a new object on the heap. Better to use String pool.

0


source


The second example is correct.

Using

String temp = "";

      

0


source


Yes, the sonar is correct. Using new String()

is pretty much never a good idea.

The reason for this is that the JVM caches strings, so you don't have to create a new object on the heap every time (which is why it is sometimes a mistake to compare strings with ==

works - they both refer to the same cached instance on the heap).

Building a String will bypass this inline cache on its own and can lead to performance issues down the line. If you only want an empty string, just assign it:

String temp = "";

      

Or, if you just want to declare a string as you want to assign it later, just don't assign anything to it!

String temp;
if(condition()) {
    temp = "hello!";
} else {
    temp = "bye!";
}

      

If you are planning on concatenating your empty string in a loop, read this question about related performance issues and how to handle them.

0


source







All Articles