Write Java program to Convert String to Integer


This Java program prompts the user to input a number as a string and converts it to an integer using two different methods: Integer.valueOf().intValue() and Integer.parseInt().

The Scanner class is used to read input from the user, and the String class is used to store the input as a string. The program then uses two methods provided by the Integer class to convert the string to an integer value: intValue() and parseInt().

The intValue() method converts an Integer object to an int value, while parseInt() method returns an int value parsed from a string.

The program prints both the string value and the integer value of the input using both methods.

Source Code

import java.util.Scanner;
public class StringToInteger
{
	public static void main(String args[])
	{
		Scanner input = new Scanner(System.in);
		String str;
		System.out.print("Enter the Number : ");
		str = input.next();
		System.out.println("String Value : " + str);
 
		int int_val = 0;
 
		//intValue() Method 1
		int_val = Integer.valueOf(str).intValue();
		System.out.println("Integer Value Using intValue() Method : " + int_val);
 
		//parseInt() Method 2
		int_val = Integer.parseInt(str);
		System.out.println("Integer Value Using parseInt() Method : " + int_val);
	}
}

Output

Enter the Number : 10912
String Value : 10912
Integer Value Using intValue() Method : 10912
Integer Value Using parseInt() Method : 10912