Java for students logo
Explore the English language on a new scale using AI-powered English language navigator.

Convert String to int and int to String

Abstract

Code snippet, converting String to int and int to String. Program performs error checking when converting from String to int.

Source code

IntegerStringConverter.java

import java.util.Scanner;

 

public class IntegerStringConverter {

      public static void main(String[] args) {

            Scanner in = new Scanner(System.in);

            int intVar;

            String strVar;

            // read it as string

            System.out.print("Enter an integer: ");

            strVar = in.nextLine();

            // convert to integer

            try {

                  intVar = Integer.parseInt(strVar);

                  System.out.println("strVar = \"" + strVar + "\"");

                  System.out.println("intVar = " + intVar);

            } catch (NumberFormatException e) {

                  System.out.println("Can't convert \"" + strVar + "\" to integer.");

            }

            System.out.println();

            // read it as integer

            System.out.print("Enter an integer: ");

            intVar = in.nextInt();

            strVar = Integer.toString(intVar);

            System.out.println("intVar = " + intVar);

            System.out.println("strVar = \"" + strVar + "\"");

      }

}

Download IntegerStringConverter.java

Sample runs

Enter an integer: x123

Can't convert "x123" to integer.

 

Enter an integer: 123

intVar = 123

strVar = "123"

 

Enter an integer: 777

strVar = "777"

intVar = 777

 

Enter an integer: 777

intVar = 777

strVar = "777"