How to convert Java String to int

In Java, a String can be converted into an int value by using the Integer.pareseInt() method and by using the Integer.valueOf() method.

For example, when we receive user input in the form of a String and it is required that it needs to be converted into an integer before performing any mathematical operation. This can be done via parseInt() method.

Conversion by using Integer.parseInt() Method

The parseInt() method is a part of the Integer class. It is a static method and used to convert the string into an integer. Here, a string value is converted into the int value.

Example 1:

public class StudyTonight
{  
	public static void main(String args[])
	{  
		String s = "454"; //String Declaration 
		System.out.println("String value "+s);  
		int i = Integer.parseInt(s);
		System.out.println("Integer value "+i);  
	}
} 


String value 454
Integer value 454

Conversion by using Integer.valueOf() Method

The valueOf() method is a part of the Integer class. This method is used to convert a String to an integer. See the example below.

Example 2:

The valueOf() method returns an exception if the provided string does not contain valid numeric digits.

public class StudyTonight
{  
	public static void main(String args[])
	{    
		try
		{
			String s1 = "500"; //String declaration 
			Integer i1 = Integer.valueOf(s1);  // Integer.valueOf() method converts a String into Integer
			System.out.println(i1);  

			String s2 = "mohit"; //NumberFormatException
			Integer i2 = Integer.valueOf(s2);
			System.out.println(i2);        
		}
		catch(Exception e)
		{
			System.out.println("Invalid input");
		}
	}
}


500
Invalid input

Example 3:

The conversion can also be done manually as shown in the example:

class StudyTonight
{
	public static int strToInt(String str)
	{
		int i = 0;
		int num = 0;
		boolean isNeg = false;

		// Check for negative sign; if it's there, set the isNeg flag
		if (str.charAt(0) == '-') 
		{
			isNeg = true;
			i = 1;
		}

		// Process each character of the string;
		while( i < str.length())
		{
			num *= 10;
			num += str.charAt(i++) - '0'; // Minus the ASCII code of '0' to get the value of the charAt(i++).
		}

		if (isNeg)
			num = -num;
		return num;
	}
	public static void main(String[] args)
	{
		String s = "45734";
		int i = strToInt(s);
		System.out.println("Int value is : "+i);
	}
}


Int value is: 45734