Default

How to convert String to Integer in Java?

How to convert String to Integer in Java?

In this post, we will answer the question of How to convert String to Integer in Java.

We can use Integer.valueOf() or the Integer.parseInt() methods to convert the string to integer. Both the methods may throw java.lang.NumberFormatException exception. We can add the conversion in the try-catch block to handle the exception.

Integer.valueOf()

We can use this method to convert the String object to an Integer object.

public static Integer valueOf(String s) throws NumberFormatException {

…

}

Integer.parseInt()

We can use this method to convert the String object to a primitive int data type.

public static int parseInt(String s, int radix)
throws NumberFormatException
{

…

}

Using Integer constructor

Integer iObj = new Integer(str);

Note that the above conversion using the Integer class constructor is deprecated since Java 9. It’s recommended to not use this constructor with Java 9 or above.

Java Program

Sample Java Program to convert Java String object to Integer object.

public class StringToInteger {

	public static void main(String args[]){

		//Create New String object
		String str = new String("79");

		//Using valueOf(String) method 
		Integer iObj = Integer.valueOf(str); 
		//Using parseInt(String) method 
		int i = Integer.parseInt(str);
		System.out.println("String converted to Integer Object: " + iObj);
		System.out.println("String converted to primitive int: " + i);
	}
}

 

Convert String to Integer

In this program, we will show the usage of both the methods discussed above.

String str = new String(“79”);

Create a String object str.

Integer iObj = Integer.valueOf(str);

Convert the String object to an Integer object.

int i = Integer.parseInt(str);

Convert the String to primitive datatype int.

—

Java Tutorials

Java Tutorial on this website:

https://www.testingdocs.com/java-tutorial/

For more information on Java, visit the official website :

https://www.oracle.com/in/java/