Convert Integer to String (Java)

From LiteratePrograms

(Redirected from Convert Integer to String)
Jump to: navigation, search

There are a number of different ways to convert a integer number into a String-object.

In Java you can convert any primitive-type into a String-object, by appending an empty String ("") to the beginning or the end of the variable (of a primitive type).

<<built-in convert>>=
public static String convertSimple(int i) {
    return "" + i;
}

To use the static-toString Method of the Integer-class can make the code more (sometimes also less) readable.

<<integer convert>>=
public static String convertInteger(int i) {
    return Integer.toString(i);
}

Technically you can also use the Formatter (like C's "sprintf"), although it is kind of overkill.

<<format convert>>=
public static String convertFormat(int i) {
    return String.format("%d", i);
}

Testing the methods

<<test main>>=
public static void main(String[] args) {
    for (int i = 0; i <= 46; i++) {
        System.out.println(convertInteger(i) + " <=> " + convertSimple(i) + " <=> " + convertFormat(i));
    }
}

The class

<<ConvertInt2Str.java>>=
public class ConvertInt2Str {
        built-in convert
        integer convert
        format convert
        test main
}
Download code
Views