Java - Convert integer to string

JavaStringNumbersInt

Java Problem Overview


Given a number:

int number = 1234;

Which would be the "best" way to convert this to a string:

String stringNumber = "1234";

I have tried searching (googling) for an answer but no many seemed "trustworthy".

Java Solutions


Solution 1 - Java

There are multiple ways:

  • String.valueOf(number) (my preference)
  • "" + number (I don't know how the compiler handles it, perhaps it is as efficient as the above)
  • Integer.toString(number)

Solution 2 - Java

Integer class has static method toString() - you can use it:

int i = 1234;
String str = Integer.toString(i);

> Returns a String object representing the specified integer. The argument is converted to signed decimal representation and returned as a string, exactly as if the argument and radix 10 were given as arguments to the toString(int, int) method.

Solution 3 - Java

Always use either String.valueOf(number) or Integer.toString(number).

Using "" + number is an overhead and does the following:

StringBuilder sb = new StringBuilder();
sb.append("");
sb.append(number);
return sb.toString();

Solution 4 - Java

This will do. Pretty trustworthy. : )

    ""+number;

Just to clarify, this works and acceptable to use unless you are looking for micro optimization.

Solution 5 - Java

The way I know how to convert an integer into a string is by using the following code:

Integer.toString(int);

and

String.valueOf(int);

If you had an integer i, and a string s, then the following would apply:

int i;
String s = Integer.toString(i); or
String s = String.valueOf(i);

If you wanted to convert a string "s" into an integer "i", then the following would work:

i = Integer.valueOf(s).intValue();

Solution 6 - Java

This is the method which i used to convert the integer to string.Correct me if i did wrong.

/**
 * @param a
 * @return
 */
private String convertToString(int a) {

	int c;
	char m;
	StringBuilder ans = new StringBuilder();
	// convert the String to int
	while (a > 0) {
		c = a % 10;
		a = a / 10;
		m = (char) ('0' + c);
		ans.append(m);
	}
	return ans.reverse().toString();
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTrufaView Question on Stackoverflow
Solution 1 - JavaBozhoView Answer on Stackoverflow
Solution 2 - JavalukastymoView Answer on Stackoverflow
Solution 3 - JavaAllThatICodeView Answer on Stackoverflow
Solution 4 - JavaNishantView Answer on Stackoverflow
Solution 5 - JavadanjonilaView Answer on Stackoverflow
Solution 6 - JavaJeganView Answer on Stackoverflow