Advertisement
Advertisement


Java int to String - Integer.toString(i) vs new Integer(i).toString()


Question

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()
2018/05/06
1
429
5/6/2018 2:41:18 PM

Accepted Answer

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.

2018/05/06
550
5/6/2018 2:41:32 PM

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.

2014/07/18

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.

2015/09/07

  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.

2020/06/20

I also highly recommend using

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

Simple and effective.

2017/11/05

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

2017/11/05

Source: https://stackoverflow.com/questions/3930210
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]