In this tutorial, you will learn how to convert an Integer to a String. There are two main approaches that you can leverage to achieve this. The first approach is to use the toString() method of Integer and the latter is to use the valueOf() method of String.

Using the toString() method

The toString() method of the Integer class expects a single parameter of type int. Once you specify the Integer, the method returns a String representation of the value. Let’s look at an example.

package com.javawhizz;

public class Main {
    public static void main(String[] args) {
        int age = 35;

        String ageToString = Integer.toString(age);

        System.out.println(ageToString);
    }
}

The age variable declares an Integer to convert to a String using the toString() method. To convert the Integer, pass the variable as the argument of the toString() method.

As a result, the method returns a String representation of the age in base 10. Note that when working with other wrapper classes, you can use the same approach.

For example, you can call Long.toString() method to convert a long value to a String.

Output

35

Using the valueOf() method

The valueOf() method of the String class also expects a single parameter of type int. The String returned by this method is the same as the one in the previous example. Let’s look at an example.

package com.javawhizz;
public class Main {
    public static void main(String[] args) {
        Integer age = 35;

        String valueOfAgeAsString = String.valueOf(age);

        System.out.println(valueOfAgeAsString);
    }
}

As you can see from the code, you only need to pass the age variable as the argument of the toString() method. With this in place, the method will return a String representation of the age value.

Output

35

Conclusion

In this tutorial, you have learned how to convert an Integer to a String in Java. The approaches covered in this tutorial include using toString() and valueOf() methods.

There are other approaches provided on the internet that are out of this scope. For example, using String concatenation is not the same as converting an Integer to a String.

As a result, use only the approaches covered in this tutorial.


0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *