Write a program to convert a string to an integer in Java


This program takes a string input from the user and converts it to an integer using the parseInt method of the Integer class in Java. The converted integer value is then printed as output.

Here's how the program works:

  • First, the program creates a Scanner object to read input from the user.
  • Then, the program prompts the user to enter a number as a string and reads it using the nextLine method of the Scanner class.
  • The program then calls the parseInt method of the Integer class to convert the string input to an integer value.
  • The converted integer value is then stored in the variable res.
  • Finally, the program prints the converted integer value as output using the println method of the System.out object.

Note that if the string input is not a valid integer value, the parseInt method will throw a NumberFormatException at runtime.

Source Code

import java.util.Scanner;
class Convert_StringtoInt
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		System.out.println("Enter the number(string): ");
        String str1 = input.nextLine();
		int res = Integer.parseInt(str1);
        System.out.println("The integer value is : "+res);
	}	
}

Output

Enter the number(string):
45
The integer value is : 45