views:

189

answers:

4

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

Thanks.

+11  A: 

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

Jean
+5  A: 

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 new objects.

oksayt
+3  A: 
  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.

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

Dhiraj
Which one is better in terms of performance?
marcolopes
A: 

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
I pasted this code in IntelliJ IDEA and got a warning: "`new Integer(10).toString() can be simplified to Integer.toString(10)`"
oksayt