I\'m working on a project where all conversions from int
to String
are done like this:
int i = 5;
String strI = \"\" + i;
There are various ways of converting to Strings:
StringBuilder string = string.append(i).toString();
String string = String.valueOf(i);
String string = Integer.toString(i);
Personally I think that "" + i does look as the original question poster states "smelly". I have used a lot of OO languages besides Java. If that syntax was intended to be appropriate then Java would just interpret the i alone without needing the "" as desired to be converted to a string and do it since the destination type is unambiguous and only a single value would be being supplied on the right. The other seems like a 'trick" to fool the compiler, bad mojo when different versions of Javac made by other manufacturers or from other platforms are considered if the code ever needs to be ported. Heck for my money it should like many other OOL's just take a Typecast: (String) i. winks
Given my way of learning and for ease of understanding such a construct when reading others code quickly I vote for the Integer.toString(i) method. Forgetting a ns or two in how Java implements things in the background vs. String.valueOf(i) this method feels right to me and says exactly what is happening: I have and Integer and I wish it converted to a String.
A good point made a couple times is perhaps just using StringBuilder up front is a good answer to building Strings mixed of text and ints or other objects since thats what will be used in the background anyways right?
Just my two cents thrown into the already well paid kitty of the answers to the Mans question... smiles
EDIT TO MY OWN ANSWER AFTER SOME REFLECTION:
Ok, Ok, I was thinking on this some more and String.valueOf(i) is also perfectly good as well it says: I want a String that represents the value of an Integer. lol, English is by far more difficult to parse then Java! But, I leave the rest of my answer/comment... I was always taught to use the lowest level of a method/function chain if possible and still maintains readablity so if String.valueOf calls Integer.toString then Why use a whole orange if your just gonna peel it anyways, Hmmm?
To clarify my comment about StringBuilder, I build a lot of strings with combos of mostly literal text and int's and they wind up being long and ugly with calls to the above mentioned routines imbedded between the +'s, so seems to me if those become SB objects anyways and the append method has overloads it might be cleaner to just go ahead and use it... So I guess I am up to 5 cents on this one now, eh? lol...
Mostly ditto on SimonJ. I really dislike the ""+i idiom. If you say String.valueOf(i), Java converts the integer to a string and returns the result. If you say ""+i, Java creates a StringBuilder object, appends an empty string to it, converts the integer to a string, appends this to the StringBuilder, then converts the StringBuilder to a String. That's a lot of extra steps. I suppose if you do it once in a big program, it's no big deal. But if you're doing this all the time, you're making the computer do a bunch of extra work and creating all these extra objects that then have to be cleaned up. I don't want to get fanatic about micro-optimization, but I don't want to be pointlessly wasteful either.
Normal ways would be Integer.toString(i)
or String.valueOf(i)
.
The concatenation will work, but it is unconventional and could be a bad smell as it suggests the author doesn't know about the two methods above (what else might they not know?).
Java has special support for the + operator when used with strings (see the documentation) which translates the code you posted into:
StringBuilder sb = new StringBuilder();
sb.append("");
sb.append(i);
String strI = sb.toString();
at compile-time. It's slightly less efficient (sb.append()
ends up calling Integer.getChars()
, which is what Integer.toString()
would've done anyway), but it works.
To answer Grodriguez's comment: ** No, the compiler doesn't optimise out the empty string in this case - look:
simon@lucifer:~$ cat TestClass.java
public class TestClass {
public static void main(String[] args) {
int i = 5;
String strI = "" + i;
}
}
simon@lucifer:~$ javac TestClass.java && javap -c TestClass
Compiled from "TestClass.java"
public class TestClass extends java.lang.Object{
public TestClass();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_5
1: istore_1
Initialise the StringBuilder:
2: new #2; //class java/lang/StringBuilder
5: dup
6: invokespecial #3; //Method java/lang/StringBuilder."<init>":()V
Append the empty string:
9: ldc #4; //String
11: invokevirtual #5; //Method java/lang/StringBuilder.append:
(Ljava/lang/String;)Ljava/lang/StringBuilder;
Append the integer:
14: iload_1
15: invokevirtual #6; //Method java/lang/StringBuilder.append:
(I)Ljava/lang/StringBuilder;
Extract the final string:
18: invokevirtual #7; //Method java/lang/StringBuilder.toString:
()Ljava/lang/String;
21: astore_2
22: return
}
There's a proposal and ongoing work to change this behaviour, targetted for JDK 9.
The expression
"" + i
leads to string conversion of i
at runtime. The overall type of the expression is String
. i
is first converted to an Integer
object (new Integer(i)
), then String.valueOf(Object obj)
is called. So it is equivalent to
"" + String.valueOf(new Integer(i));
Obviously, this is slightly less performant than just calling String.valueOf(new Integer(i))
which will produce the very same result.
The advantage of ""+i
is that typing is easier/faster and some people might think, that it's easier to read. It is not a code smell as it does not indicate any deeper problem.
(Reference: JLS 15.8.1)
It's not a good way.
When doing conversion from int to string, this should be used:
int i = 5;
String strI = String.valueOf(i);