442

Sometimes java puzzles me.
I have a huge amount of int initializations to make.

What's the real difference?

  1. Integer.toString(i)
  2. new Integer(i).toString()
Neuron
  • 5,141
  • 5
  • 38
  • 59
marcolopes
  • 9,232
  • 14
  • 54
  • 65
  • 20
    I would just use `"" + 42`, but hey, that's me. Form #2 will result in a new integer object (for most values of i) as an intermediate. It is also more typing. –  Oct 14 '10 at 05:11
  • 16
    @pst: if the intermediate object is an issue for you, then `"" + 42` isn't any better, as it requires an intermediate `StringBuilder` which is quite a lot heavier than an `Integer`. – Joachim Sauer Oct 14 '10 at 11:18
  • 49
    "" + 42 might work, but is a bad idea. Folks like me will come look at your code and try to figure out what the heck happened to the empty string. – Mainguy Dec 27 '10 at 20:38
  • 3
    I wouldn't recommend `"" + 42` because in the case of appending strings of integers you may end up adding the values and not realizing it. – BoltzmannBrain Apr 02 '15 at 21:03
  • @alavin89, we're talking about Java here, that definitely isn't going to happen. A valid warning in the case of JS and similar languages though. – Veselin Romić Apr 05 '15 at 14:05
  • 23
    If you don't like a lot of typing, then you probably shouldn't be programming in Java. – Adam Pierce May 21 '15 at 23:16
  • 2
    I personally prefer `String.valueOf()` because it can be used for any type. – shmosel Aug 02 '16 at 19:47
  • 1
    How about using a formatted string: String.format("%d", i); – Wouter Oct 30 '16 at 22:01

11 Answers11

562

Integer.toString calls the static method in the class Integer. It does not need an instance of Integer.

If you call new Integer(i) you create an instance of type Integer, which is a full Java object encapsulating the value of your int. Then you call the toString method on it to ask it to return a string representation of itself.

If all you want is to print an int, you'd use the first one because it's lighter, faster and doesn't use extra memory (aside from the returned string).

If you want an object representing an integer value—to put it inside a collection for example—you'd use the second one, since it gives you a full-fledged object to do all sort of things that you cannot do with a bare int.

Neuron
  • 5,141
  • 5
  • 38
  • 59
Jean
  • 10,545
  • 2
  • 31
  • 31
97

new Integer(i).toString() first creates a (redundant) wrapper object around i (which itself may be a wrapper object Integer).

Integer.toString(i) is preferred because it doesn't create any unnecessary objects.

John Strickler
  • 25,151
  • 4
  • 52
  • 68
oksayt
  • 4,333
  • 1
  • 22
  • 41
47

Another option is the static String.valueOf method.

String.valueOf(i)

It feels slightly more right than Integer.toString(i) to me. When the type of i changes, for example from int to double, the code will stay correct.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
fhucho
  • 34,062
  • 40
  • 136
  • 186
14

I also highly recommend using

int integer = 42;
String string = integer + "";

Simple and effective.

frogatto
  • 28,539
  • 11
  • 83
  • 129
Daisy Holton
  • 533
  • 3
  • 17
  • 39
    this is definitely bad form, because it both relies on a fairly subtle part of the Java language and is less efficient than Integer.toString(i). See [this SO post](http://stackoverflow.com/questions/4105331/how-to-convert-from-int-to-string) – rickcnagy Nov 21 '13 at 15:39
  • This could be inefficient. I suggest using some conventional choices like Integer.toString or String.valueOf. Check here http://javadevnotes.com/java-integer-to-string-examples – JavaDev Feb 15 '15 at 14:15
  • It's generally a bad idea to do things in such an unintuitive manner. More obvious choices like `Integer.toString()` might use some extra keystrokes, but are much clearer, which is crucial when you want to maintain the code. – Calvin Li Mar 03 '15 at 09:05
  • Wouldn't this automatically call integer variable's `toString()` method? – Ankit Deshpande Oct 06 '15 at 09:15
14
  1. new Integer(i).toString();

    This statement creates the object of the Integer and then call its methods toString(i) to return the String representation of Integer's value.

  2. Integer.toString(i);

    It returns the String object representing the specific int (integer), but here toString(int) is a static method.

Summary is in first case it returns the objects string representation, where as in second case it returns the string representation of integer.

Community
  • 1
  • 1
Dhiraj
  • 350
  • 1
  • 3
12

Although I like fhucho's recommendation of

String.valueOf(i)

The irony is that this method actually calls

Integer.toString(i)

Thus, use String.valueOf(i) if you like how it reads and you don't need radix, but also knowing that it is less efficient than Integer.toString(i).

frogatto
  • 28,539
  • 11
  • 83
  • 129
Nathan Waite
  • 121
  • 1
  • 3
4

In terms of performance measurement, if you are considering the time performance then the Integer.toString(i); is expensive if you are calling less than 100 million times. Else if it is more than 100 million calls then the new Integer(10).toString() will perform better.

Below is the code through u can try to measure the performance,

public static void main(String args[]) {
            int MAX_ITERATION = 10000000;
        long starttime = System.currentTimeMillis();
        for (int i = 0; i < MAX_ITERATION; ++i) {
            String s = Integer.toString(10);
        }
        long endtime = System.currentTimeMillis();
        System.out.println("diff1: " + (endtime-starttime));

        starttime = System.currentTimeMillis();
        for (int i = 0; i < MAX_ITERATION; ++i) {
            String s1 = new Integer(10).toString();
        }
        endtime = System.currentTimeMillis();
        System.out.println("diff2: " + (endtime-starttime));
    }

In terms of memory, the

new Integer(i).toString();

will take more memory as it will create the object each time, so memory fragmentation will happen.

Dhiraj
  • 350
  • 1
  • 3
  • 2
    I pasted this code in IntelliJ IDEA and got a warning: "`new Integer(10).toString() can be simplified to Integer.toString(10)`" – oksayt Oct 15 '10 at 05:34
  • 1
    This code works for me. I get about 420 milliseconds for Integer.toString(10) and 525 milliseconds for new Integer(10).toString() – Jake Stevens-Haas Dec 12 '10 at 20:46
  • 1
    See http://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java ... – Petr Tuma Aug 21 '13 at 11:17
  • Would of helped to warmup first, otherwise the results aren't valid! – sixones Sep 21 '16 at 12:54
  • 1
    If you say one is expensive in one case, and the other is better in the other case, that means the the other is better/inexpensive in all situation. – Sgene9 Aug 30 '17 at 18:34
2

Better:

Integer.valueOf(i).toString()
ryu
  • 312
  • 3
  • 6
  • 1
    I think this is better, because as @Dhiraj pointed out that in terms of memory, the "new Integer(i).toString();" will take more memory because it creates a new object instead of just getting the Integer value and converting that to a string. – Patricia Sep 10 '14 at 18:21
  • 4
    @Lucy Integer.valueOf(i) returns a new Integer, so there's no difference – inigoD Feb 27 '15 at 12:26
  • You're not providing an answer to the question at all. The question is what is the difference between blah and blah, not what is a better replacement for blah. – ahitt6345 Dec 25 '16 at 21:16
2

Simple way is just concatenate "" with integer:

int i = 100;

String s = "" + i;

now s will have 100 as string value.

Neuron
  • 5,141
  • 5
  • 38
  • 59
Shiv Buyya
  • 3,770
  • 2
  • 30
  • 25
1

Here Integer.toString calls the static method in the class Integer. It does not require the object to call.

If you call new Integer(i) you first create an instance of type Integer, which is a full Java object encapsulating the value of your int i. Then you call the toString method on it to ask it to return a string representation of itself.

Shailej Shimpi
  • 145
  • 2
  • 3
0

1.Integer.toString(i)

Integer i = new Integer(8);
    // returns a string representation of the specified integer with radix 8
 String retval = i.toString(516, 8);
System.out.println("Value = " + retval);

2.new Integer(i).toString()

 int i = 506;

String str = new Integer(i).toString();
System.out.println(str + " : " + new Integer(i).toString().getClass());////506 : class java.lang.String
Py-Coder
  • 2,024
  • 1
  • 22
  • 28