196

I am wondering why the method String.valueOf(int i) exists ? I am using this method to convert int into String and just discovered the Integer.toString(int i) method.

After looking the implementation of these methods I saw that the first one is calling the second one. As a consequence all my calls to String.valueOf(int i) involve one more call than directly calling Integer.toString(int i)

Ola Ström
  • 4,136
  • 5
  • 22
  • 41
Manuel Selva
  • 18,554
  • 22
  • 89
  • 134
  • 3
    Just for reference purposes: http://stackoverflow.com/questions/3335685/integer-tostring – Bobby Jul 26 '10 at 14:25
  • Largely so that the compiler can just generate `String.valueOf()` calls when concatenating primitive types to Strings, instead of having to know about all the `toString()` methods. – user207421 May 09 '23 at 04:43

12 Answers12

183

In String type we have several method valueOf

static String   valueOf(boolean b) 
static String   valueOf(char c) 
static String   valueOf(char[] data) 
static String   valueOf(char[] data, int offset, int count) 
static String   valueOf(double d) 
static String   valueOf(float f) 
static String   valueOf(int i) 
static String   valueOf(long l) 
static String   valueOf(Object obj) 

As we can see those method are capable to resolve all kind of numbers

every implementation of specific method like you have presented: So for integers we have

Integer.toString(int i)

for double

Double.toString(double d)

and so on

In my opinion this is not some historical thing, but it is more useful for a developer to use the method valueOf from the String class than from the proper type, as it leads to fewer changes for us to make when we want to change the type that we are operating on.

Sample 1:

public String doStuff(int num) {

  // Do something with num...

  return String.valueOf(num);

 }

Sample2:

public String doStuff(int num) {
  
 // Do something with num...
 
 return Integer.toString(num);

 }

As we see in sample 2 we have to do two changes, in contrary to sample one.

In my conclusion, using the valueOf method from String class is more flexible and that's why it is available there.

Charlie Armstrong
  • 2,332
  • 3
  • 13
  • 25
  • 19
    And don't forget `Integer.toString(int i, int radix)` that will convert to strings of bases other than 10. – Stephen P Oct 01 '10 at 21:36
  • @Vash Could you please also explain about using empty string to convert int into String compare to String.valueOf? e.g) "" + int i = "i" ? Which is best ? – Kanagavelu Sugumar Sep 24 '13 at 05:31
  • 1
    To format int as string you should not use the "" + i. There do not exists big over head but generally because this is not elegant. Instead of using `String.valueOf(int)`, you can use `String.format("%d",i);` to read more please visit this web site http://docs.oracle.com/javase/6/docs/api/java/util/Formatter.html – Damian Leszczyński - Vash Sep 24 '13 at 07:38
  • I wish autoboxing was cleverer and just added the conversion on compilation or something. – Rob Grant Oct 14 '13 at 12:38
  • 1
    @RobertGrant The autoboxing is not the case here. But to answer your concerns, it is clever as you can do this `int i = new Integer("1");` and vice versa. – Damian Leszczyński - Vash Oct 15 '13 at 14:50
  • It's a trade off - you're limited by the arguments that String.valueOf takes - e.g. what if you switch to using an AtomicDouble or something like that – naumcho Jun 17 '14 at 14:09
  • @naumcho, Nothing to be exact. Because `AtomicDouble` is derived from `Object` class. Then for an instance of it, the method `String#valueOf(Object)` will be used. And in case of `null` will result with "null" and if not then will invoke `ad.toString()`. – Damian Leszczyński - Vash Jun 17 '14 at 14:18
  • As `""+i` is the shortest method I think it is very ellegant. Especially as it also deals with (null) objects. The compiler does optimize it very good in all cases. – eckes May 01 '15 at 17:50
  • Why this answer isn't on top? It's the best and makes most sense. – zubergu May 22 '15 at 13:16
59

One huge difference is that if you invoke toString() in a null object you'll get a NullPointerException whereas, using String.valueOf() you may not check for null.

Aniruddha
  • 308
  • 2
  • 11
A Costa
  • 799
  • 5
  • 10
  • 51
    The question is about [`Integer.toString(int i)`](http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#toString%28int%29), a `static` method. There are no `null` objects possible. – Petr Janeček Jun 27 '12 at 12:40
  • 18
    `Integer i = null;` `i.toString(); // Null pointer exception!!` `String.valueOf(i); // No exception ` – Manish Singh Oct 16 '12 at 06:25
  • 13
    @Manis Kumar: Your example will not fire the `String.valueOf(int i)` method but `String.valueOf(Object obj)`. Anyhow, the question is about primitive `int` values, where there's no possibility of `null`. – hleinone Nov 01 '12 at 11:47
  • 1
    @manish_s it was pretty clear from the example that nobody is talking about the Object type Integer. We're only talking about primitives. – Daniel Ochoa Mar 01 '16 at 14:14
  • 4
    @manish_s: The OP didn't say `Integer.toString()` but `Integer.toString(int i)`. That is a static method (http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#toString(int)). – LarsH Dec 07 '16 at 03:03
50

Just two different ways of doing the same thing. It may be a historical reason (can't remember if one came before the other).

mipadi
  • 398,885
  • 90
  • 523
  • 479
13

The String class provides valueOf methods for all primitive types and Object type so I assume they are convenience methods that can all be accessed through the one class.

NB Profiling results

Average intToString = 5368ms, Average stringValueOf = 5689ms (for 100,000,000 operations)

public class StringIntTest {


    public static long intToString () {
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 100000000; i++) {
            String j = Integer.toString(i);
        }
        long finishTime = System.currentTimeMillis();

        return finishTime - startTime;
    }

    public static long stringValueOf () {

        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 100000000; i++) {
            String j = String.valueOf(i);
        }
        long finishTime = System.currentTimeMillis();

        return finishTime - startTime;
    }

    public static void main(String[] args) {
        long intToStringElapsed = 0;
        long stringValueOfElapsed = 0;
        for (int i = 0; i < 10; i++) {
            intToStringElapsed += intToString();
            stringValueOfElapsed+= stringValueOf();
        }
        System.out.println("Average intToString = "+ (intToStringElapsed /10));
        System.out.println("Average stringValueOf = " +(stringValueOfElapsed / 10));
    }
}
Kingo
  • 440
  • 2
  • 9
  • 7
    Your profiling should really have a "warm-up" period, otherwise the results can be skewed by the JIT tinkering with things. That said, a 300ms difference over 10^8 operations is so small as to be completely negligible. – Cameron Skinner Dec 10 '10 at 03:57
  • 1
    @Kingo I don't think your test case is correct. Because you are assigning the value to `String j` but never use. The underlying compiler may have optimized this. It is better to pass j object in different method and do some dummy operation. – Rakesh Jun 24 '13 at 06:16
  • 1
    You really should not write home grown micro benchmarks this way. If you use [JMH](http://openjdk.java.net/projects/code-tools/jmh/). It will take care of warmup, time measurement, multiple independend tries (forks Java!) and makes the code small, it looks like (incl. results for different methods and values - runtime 7 minutes): https://gist.github.com/ecki/399136f4fd59c1d110c1 (spoiler: ""+n won). – eckes May 01 '15 at 18:13
  • 6
    Thanks buddy, but my answer was 5 years ago! JMH was only released in 2013 :P – Kingo Aug 11 '15 at 00:29
11

From the Java sources:

/**
 * Returns the string representation of the {@code int} argument.
 * <p>
 * The representation is exactly the one returned by the
 * {@code Integer.toString} method of one argument.
 *
 * @param   i   an {@code int}.
 * @return  a string representation of the {@code int} argument.
 * @see     java.lang.Integer#toString(int, int)
 */
public static String valueOf(int i) {
    return Integer.toString(i);
}

So they give exactly the same result and one in fact calls the other. String.valueOf is more flexible if you might change the type later.

Davio
  • 4,609
  • 2
  • 31
  • 58
9

If you look at the source code for the String class, it actually calls Integer.toString() when you call valueOf().

That being said, Integer.toString() might be a tad faster if the method calls aren't optimized at compile time (which they probably are).

agabrys
  • 8,728
  • 3
  • 35
  • 73
tskuzzy
  • 35,812
  • 14
  • 73
  • 140
3

To answer the OPs question, it's simply a helper wrapper to have the other call, and comes down to style choice and that is it. I think there's a lot of misinformation here and the best thing a Java developer can do is look at the implementation for each method, it's one or two clicks away in any IDE. You will clearly see that String.valueOf(int) is simply calling Integer.toString(int) for you.

Therefore, there is absolutely zero difference, in that they both create a char buffer, walk through the digits in the number, then copy that into a new String and return it (therefore each are creating one String object). Only difference is one extra call, which the compiler eliminates to a single call anyway.

So it matters not which you call, other than maybe code-consistency. As to the comments about nulls, it takes a primitive, therefore it can not be null! You will get a compile-time error if you don't initialize the int being passed. So there is no difference in how it handles nulls as they're non-existent in this case.

Matthias Wiehl
  • 1,799
  • 16
  • 22
Steve J
  • 31
  • 1
3

The implementation of String.valueOf() that you see is the simplest way to meet the contract specified in the API: "The representation is exactly the one returned by the Integer.toString() method of one argument."

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
2

You shouldn't worry about this extra call costing you efficiency problems. If there's any cost, it'll be minimal, and should be negligible in the bigger picture of things.

Perhaps the reason why both exist is to offer readability. In the context of many types being converted to String, then various calls to String.valueOf(SomeType) may be more readable than various SomeType.toString calls.

polygenelubricants
  • 376,812
  • 128
  • 561
  • 623
  • 1
    Actually, such one-line calls get inlined pretty quickly. – Tassos Bassoukos Jul 26 '10 at 14:29
  • Even in a loop calling 1 000 000 time String.valueof() ?? – Manuel Selva Jul 26 '10 at 14:29
  • @Manuel: did you profile it? Have you identified that herein lies your performance problem? Are you sure you're not prematurely optimizing? @Tassos: yes, that is also very likely, but either way I wouldn't worry about it unless profiling says that there's a problem with this particular call. – polygenelubricants Jul 26 '10 at 14:30
  • Actually, Manuel, I'd expect a loop going 1000000 times to get inlined more often than just going once or twice. Even so, it's going to be a small portion of the time no matter how many times it loops. – corsiKa Jul 26 '10 at 14:32
  • No but I am sure there is no bottle neck here in my app. I am just asking this because I can't see any readability concern here and thus I think I have to use the more optimum code even if the gain is 0. Don't you agree ? – Manuel Selva Jul 26 '10 at 14:33
1

my openion is valueof() always called tostring() for representaion and so for rpresentaion of primtive type valueof is generalized.and java by default does not support Data type but it define its work with objaect and class its made all thing in cllas and made object .here Integer.toString(int i) create a limit that conversion for only integer.

1

There have no differences between Integer.toString(5) and String.valueOf(5);

because String.valueOf returns:

public static String valueOf(int i) {
    return Integer.toString(i);
}
public static String valueOf(float f) {
    return Float.toString(f);
}

etc..

Ahamadullah Saikat
  • 4,437
  • 42
  • 39
0

Using the method, String.valueOf() you do not have to worry about the data(whether it is int,long,char,char[],boolean,Object), you can just call :

  • static String valueOf()

using the only syntax String.valueOf() can whatever you pass as a parameter is converted to String and returned..

Otherwise, if you use Integer.toString(),Float.toString() etc.(i.e. SomeType.toString()) then you will have to check the datatype of parameter that you want to convert into string. So, its better to use String.valueOf() for such convertions.

If you are having an array of object class that contains different values like Integer,Char,Float etc. then by using String.valueOf() method you can convert the elements of such array into String form easily. On contrary, if you want to use SomeType.toString() then at first you will need to know about there their datatype classes(maybe by using "instanceOf" operator) and then only you can proceed for a typecast.

String.valueOf() method when called matches the parameter that is passed(whether its Integer,Char,Float etc.) and by using method overloading calls that "valueOf()" method whose parameter gets matched, and then inside that method their is a direct call to corresponding "toString()" method..

So, we can see how the overhead of checking datatype and then calling corresponding "toString()" method is removed.Only we need is to call String.valueOf() method, not caring about what we want to convert to String.

Conclusion: String.valueOf() method has its importance just at cost of one more call.

Amit Bhandari
  • 541
  • 6
  • 8