Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String conversions in Java

Tags:

java

string

I have a method which takes String argument. In some cases I want to pass int value to that method. For invoking that method I want to convert int into String. For that I am doing the following:

    aMethod(""+100);

One more option is:

    aMethod(String.valueOf(100));

Both are correct. I don't know which is appropriate? Which gives better performance?

Mostly this is happen in GWT. In GWT for setting size of panels and widgets I want to do this.

like image 549
DonX Avatar asked Jan 21 '09 02:01

DonX


3 Answers

Using + on strings creates multiple string instances, so using valueOf is probably a bit more performant.

like image 80
Fabian Steeg Avatar answered Nov 13 '22 03:11

Fabian Steeg


Since you're mostly using it in GWT, I'd go with the ""+ method, since it's the neatest looking, and it's going to end up converted to javascript anyway, where there is no such thing as a StringBuilder.

Please don't hurt me Skeet Fanboys ;)

like image 43
rustyshelf Avatar answered Nov 13 '22 03:11

rustyshelf


Normally you'd use Integer.toString(int) or String.valueOf(int). They both return the same thing, and probably have identical implementations. Integer.toString(int) is a little easier to read at a glance though, IMO.

like image 44
patros Avatar answered Nov 13 '22 02:11

patros