This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Though the result of last two lines are same, I would like to know which one is better in terms of performance etc.
Correct me if I'm wrong but I think that creates a StringBuilder behind the scene and appends the empty String and a.toString together.
Performance wise there is no difference between the two, what's important for the performance point of view is the implementation of the toString() method.
The cleanest way to implement is just to do .
What are the other ways I can use to convert this integer to String effectively
For any type of a (int, float, Object, Integer, etc), ""+a is equal to this in Java 6:
For all object types "append(a)" is equal to "append(String.valueOf(a))" with String.valueOf being somewhat like this: So if you do ""+a, you also call a.toString(), but with another String (""), a StringBuilder, and the final String. So yes, a.toString() is more efficient.
If you want to be safe, you can always call String.valueOf(a). This will also handle the cases where a is null, or where a is a primitive type (String.valueOf has been overloaded for these).
That's because there are two matches for null: String.valueOf(Object) and String.valueOf(char). If you pass null, the compiler finds the most specific, and that is valueOf(char). Unlike String.valueOf(Object), that one does throw an exception. The following will work fine:
Almost the same, but this time the reference type (Object) makes sure that String.valueOf(Object) is called instead of String.valueOf(char).