devxlogo

Integer-to-string Conversions

Integer-to-string Conversions

Question:
I want to convert an integer into a string. Is there anything in Java similar to the itoa() function in C?

Answer:
To convert a number (or in fact, any Java object) into a string isvery easy. Just concatenate it with the empty string.

     int n = 5;     String s = n + "";

You can also call the toString() function that is defined for allobjects, but that is a pain for numbers. A number isn’t an object, soyou first have to make the number an object.

     Integer i = new Integer(n);     String s = i.toString();

You can do it all in one statement:

     String s = new Integer(n).toString();

Clearly the first method, of concatenating with “”, seems moreattractive.

devx-admin

Share the Post: