Back in college one of my profs. taught us to just do x + \"\"
as a quick conversion from basic types to strings.
I don\'t remember which class it was in I
In Java, for primitive types (int
, double
, etc.) you cannot write .toString()
because the types aren't objects. This means that your options are either to write something like
x + "";
or to use
Integer.toString(x);
In C++, you cannot use x + ""
to do this sort of conversion, since this will be treated as pointer arithmetic and will give you a bad pointer. Using something like boost::lexical_cast
is the preferred way to do the conversion.
And... I know nothing about C#, so I won't comment on it. :-)
Well, as a side note, it depends on what x is. If x is a primitive in Java, you have to call .toString()
using one of its wrappers, like
Integer.toString(x)
I would say using toString() is generally better, because x + "", in at least Java, is saying you want to append the two Strings together.
Like in this example:
public static void main(String[] args)
{
int x = 3;
String s = x + "";
}
That ends up, in bytecode, as :
public static void main(java.lang.String[]);
Code:
0: iconst_3
1: istore_1
2: new #2; //class java/lang/StringBuilder
5: dup
6: invokespecial #3; //Method java/lang/StringBuilder."<init>":()V
9: iload_1
10: invokevirtual #4; //Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
13: ldc #5; //String
15: invokevirtual #6; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
18: invokevirtual #7; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
21: astore_2
22: return
So it has to create a StringBuilder to append "" and the String value of x together. While the efficiency lost isn't that much, it isn't too much to just use the toString function.
Compare with using toString:
public static void main(String[] args)
{
int x = 3;
String s = Integer.toString(x);
}
Which ends up as:
public static void main(java.lang.String[]);
Code:
0: iconst_3
1: istore_1
2: iload_1
3: invokestatic #2; //Method java/lang/Integer.toString:(I)Ljava/lang/String;
6: astore_2
7: return
And although it might just be my opinion, using .toString reflects what you actually want -- you want the String value of x, while using x + "" is kind of a hack and says -- I want the String value of x concatenated with "".
Side Note: I can't speak on the intermediate bytecode C# would emit, but I imagine something similar to this. Plus, with C#, you can just call .ToString() on your value types just as easily as reference types, so I think my advice would apply the same.