2

I have been using String.valueOf(Char c) method to convert a character into a string.

When checking Character class methods I came across Character.toString(char c) method.

In the Character.toString(char c) implementation,I see that it inturn calling the String.valueOf(Char c) .

So what is the use of this method Character.toString(char c) as we already have String.valueOf(Char c) ?

And if we use Character.toString(char c) will there be any difference in the performance?

gowtham
  • 977
  • 7
  • 15
  • 6
    They're two things that do the same thing. Don't waste much time about this, use whatever you want. – Maroun Jan 08 '14 at 12:19
  • 1
    definitelly not a duplicate. But in the same line of thinking that @ᴍarounᴍaroun has. You look like you are micro optimizing. Just trust the jvm will do it's job for this type of things. – David Hofmann Jan 08 '14 at 12:45
  • @ᴍarounᴍaroun, ya I know that they do the same thing, just asked out of curiosity why we have two methods and about the performance. – gowtham Jan 08 '14 at 18:13
  • FYI, character arrays behave differently under `String.valueOf()` when compared with `char[].toString()`. Only `String.valueOf(char[])` gives what we need. – Srini Sep 24 '15 at 21:01

1 Answers1

5

So what is the use of this method Character.toString(char c) as we already have String.valueOf(Char c) ?

It's just the same. You can view this just as a convenience method.

And if we use Character.toString(char c) will there be any difference in the performance? When you code gets JITted it will inline the method calls so the performance will be the same.

However depending on how you are dealing with strings, you might get better performance if you use StringBuilder instead of creating strings and concatenating them with the + sign

David Hofmann
  • 5,683
  • 12
  • 50
  • 78