Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add an empty string vs toString - why is it bad?

According to the tool PMD, the following is a bad practice:

String s = "" + 123; // bad 
String t = Integer.toString(456); // ok 


This is an inefficient way to convert any type to a `String`.

Why is it a bad thing to do?

like image 368
corgrath Avatar asked Sep 02 '10 12:09

corgrath


People also ask

Which is better string valueOf or toString?

valueOf will transform a given object that is null to the String "null" , whereas . toString() will throw a NullPointerException . The compiler will use String. valueOf by default when something like String s = "" + (...); is used.

Why do you need a toString?

The toString method is used to return a string representation of an object. If any object is printed, the toString() method is internally invoked by the java compiler. Else, the user implemented or overridden toString() method is called.

What is the point of an empty string?

An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters. A null string is represented by null .


1 Answers

It is inefficient, as it involves an unneeded string concatenation, thus the creation of one or two extra String objects - although I believe the JIT can optimize it away.

To me the bigger problem is that the code is less clear. Calling toString is a standard idiom, understandable to every Java developer (hopefully :-), so you should prefer this.

like image 51
Péter Török Avatar answered Sep 28 '22 03:09

Péter Török