Convert Int to String

JavaJavaBeginner
Practice Now

Introduction

In Java, there are several ways to convert an int data type to a String data type. In this step-by-step lab, we will go through three different methods to convert an int to a String in Java.

Create a Java file

Firstly, create a new Java file named IntToString.java. This can be done using the following command in the terminal:

touch IntToString.java

Convert int to String using valueOf() method

The valueOf() method can be used to convert an int to a String. The valueOf() method belongs to the String class and returns a String representation of the specified int. Here's an example code block in IntToString.java that shows how to use this method:

public class IntToString {
    public static void main(String[] args) {
        int num = 42;

        // using valueOf() method to convert int to String
        String str = String.valueOf(num);

        System.out.println(str);
    }
}

To run the code, use the following command in the terminal:

javac IntToString.java && java IntToString

The output will be 42.

Convert int to String using toString() method

Another way to convert an int to a String is to use the toString() method of the Integer class. The toString() method returns a String containing the int value represented by the Integer object. Here's an example code block in IntToString.java that shows how to use this method:

public class IntToString {
    public static void main(String[] args) {
        int num = 42;

        // using toString() method to convert int to String
        String str = Integer.toString(num);

        System.out.println(str);
    }
}

To run the code, use the following command in the terminal:

javac IntToString.java && java IntToString

The output will be 42.

Convert int to String using string concatenation

A simple way to convert an int to a String is to concatenate it with an empty String. When an int is concatenated with a String, the int is automatically converted to a String. Here's an example code block in IntToString.java that shows how to use this method:

public class IntToString {
    public static void main(String[] args) {
        int num = 42;

        // using string concatenation to convert int to String
        String str = "" + num;

        System.out.println(str);
    }
}

To run the code, use the following command in the terminal:

javac IntToString.java && java IntToString

The output will be 42.

Summary

In this lab, we have discussed three methods to convert an int to a String in Java. These methods are the valueOf() method of the String class, the toString() method of the Integer class, and string concatenation. Each method has its own unique implementation, and the choice of which method to use will depend on the specific use case.

Other Java Tutorials you may like