I program in Java, often there is a task to translate int / float / double to String. Often I do like this

""+number 

Just because it's more convenient for me, but for some reason it seems to me that you shouldn't write like that.

I know what you can do for example

 String.valueOf(number) Integer.toString(number) // для int 

Which way would be more correct to use one of the methods, or can I write ""+number , and is it really important in this case?

    3 answers 3

    The methods of String.valueOf and Integer.toString(int number) identical in efficiency, since the first method internally calls the second.

    About number+"" and Integer.toString(int number) somewhat more complicated. Creating a string through +"" , as a rule, is expanded by the compiler in StringBuilder , with a further call to the append method. According to my performance test , the Integer.toString method Integer.toString slightly faster, by 10-20 percent.

    What happens inside the Integer.toString method?

    If you look at its implementation, you will see that an array of char is being allocated there, which is filled with numbers using bit shifts. In the StringBuilder.append(int number) method, similar actions occur. But, as it seems to me, due to the creation of the StringBuilder object this method turns out to be slower.

      The main difference between these methods is that if number == null , then:

      • String.valueOf(number) return the string null ;
      • when Integer.toString(number) a NullPointerException will be thrown .
      • Thanks for the answer, but I would like to hear something about ""+number - Amir Shabanov
      • It is ugly, at least. Do not do this. - post_zeew
       `String.valueOf()` 

      can be applied to both int, double, and float - if there is a need to change the data type of a variable, you will not need to edit the code with the conversion.

      If you look at the implementation for the int method String.valueOf(int i) , then the method calls Integer.toString(i) respectively.

      The last option is the most expensive and it is better to avoid such bikes.

      • the last one is ""+number ? - Amir Shabanov
      • yes, in this case, it simply creates a StringBuilder, adds an empty string and a number, as a result converts it to a String. - rom16rus