DonX
DonX

Reputation: 16369

String conversions in Java

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.

Upvotes: 6

Views: 333

Answers (4)

rustyshelf
rustyshelf

Reputation: 45101

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 ;)

Upvotes: 2

John Gardner
John Gardner

Reputation: 25126

I'd assume that this:

aMethod(""+100);

turns into this by the compiler:

aMethod(new StringBuilder("").append(String.valueOf(100)).toString());

So the option of calling the String.valueOf directly is probably the better choice. You could always compile them and compare the bytecode to see for sure.

Upvotes: 0

patros
patros

Reputation: 7819

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.

Upvotes: 1

Fabian Steeg
Fabian Steeg

Reputation: 45724

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

Upvotes: 4

Related Questions