0 votes
1 view
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 (46.1k 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)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...