Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.9k points)

Sometimes java puzzles me.

I have a huge amount of int initializations to make.

What's the real difference?

  • Integer.toString(i)
  • new Integer(i).toString()

1 Answer

0 votes
by (46k points)

Integer.toString calls the static approach in the class Integer. It doesn't require an occurrence of Integer.

If you call a new Integer(i) you construct an instance of type Integer, which is a complete Java object encapsulating the value of your int. Then you call the toString process on it to direct it to declare a string image of itself.

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

If you need an object expressing an integer value—to put it inside a collection for example—you'd use the second one, as it gives you a full-fledged object to do all kinds of things that you can't do with a bare int.

Related questions

0 votes
1 answer
asked Jul 26, 2019 in Java by Shubham (3.9k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Aug 6, 2019 in Java by Anvi (10.2k points)

Browse Categories

...