Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

string

int

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()
like image 801
marcolopes Avatar asked Oct 14 '10 05:10

marcolopes


People also ask

What is the use of integer toString () in Java?

toString() is an inbuilt method in Java which is used to return the String object representing this Integer's value. Parameters: The method does not accept any parameters. Return Value:The method returns the string object of the particular Integer value.

What is the difference between toString and string?

Both these methods are used to convert a string. But yes, there is a difference between them and the main difference is that Convert. Tostring() function handles the NULL while the . ToString() method does not and it throws a NULL reference exception.

What is difference between toString and string valueOf () in Java?

String. valueOf will transform a given object that is null to the String "null" , whereas . toString() will throw a NullPointerException . The compiler will use String.

What is the difference between string valueOf and integer toString?

You will clearly see that String. valueOf(int) is simply calling Integer. toString(int) for you. Therefore, there is absolutely zero difference, in that they both create a char buffer, walk through the digits in the number, then copy that into a new String and return it (therefore each are creating one String object).


1 Answers

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.

like image 82
Jean Avatar answered Sep 19 '22 14:09

Jean