Convert Integer to String in Java

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to use the toString() method of the Java Integer class to convert an integer value to a string in Java programming. This method is extremely useful when you need to display the integer value as a string.

Set up a Java file

Create a new Java file named IntToString.java in your ~/project directory using the following command:

touch ~/project/IntToString.java

Import the required package

In the created file, import the java.lang package by adding the following line of code to the beginning of your Java code:

import java.lang.*;

Declare an integer value

Assign a value to an integer variable a :

int a = 100;

Convert the integer value to a string

Use the toString() method to convert the integer value to its equivalent string representation:

String str = Integer.toString(a);

Test the code

To test the code, you can print the value of the string str to the console using the System.out.println() method as shown below:

System.out.println("Converted string: " + str);

Compile and run the code

Save the file and in the terminal, navigate to the ~/project directory where your Java file is located. Use the following command to compile the Java code:

javac IntToString.java

Once the IntToString.class file is generated, run the code using the following command:

java IntToString

Enter integer value at runtime

As an example, you could ask the user to enter an integer value at runtime using the Scanner class.

import java.util.Scanner;
public class IntToString {
   public static void main(String args[]) {
      Scanner in = new Scanner(System.in);
      System.out.print("Enter an integer value: ");
      int num = in.nextInt();
      String str = Integer.toString(num);
      System.out.println("The string representation of the integer is: " + str);
   }
}

Note: This example uses the Scanner.nextInt() method to read an integer value from the user at runtime.

Compile and run the updated code

Save the file and in the terminal, navigate to the ~/project directory where your Java file is located. Use the following command to compile the updated Java code:

javac IntToString.java

Once the IntToString.class file is generated, run the code using the following command:

java IntToString

Summary

In this lab, you learned how to use the toString() method of the Java Integer class to convert an integer value to its equivalent string representation. You also learned about the Scanner class to read input from the user at runtime and how to compile and run a Java code using the command line. Now you can use this method effectively in your programs to display integer values as strings.

Other Java Tutorials you may like