java

String to int conversion using Java

We will be using Integer.parseInt() method to convert a String value to an Integer value using Java. We will be explaining more methods to convert a string to int in this post.

String mystr = "100";
int intVal = Integer.parseInt(mystr);
      
System.out.println(intVal);

In the above code example, we have defined a String variable 'mystr' and want to convert it to integer type values using Java. We are using Integer.parseInt() function to do that.

Integer.parseInt(MyString)

If the string value is not valid then the program will throw an error. You can handle it using the below code.

try {
    String mystr = "abc";
    int val = Integer.parseInt(mystr);
}
catch (NumberFormatException e) {
    System.out.println("Not a valid value");
}

Output

Not a valid value

Method 2: Use Integer.valueOf() function to convert a String to Integer value

We can also use the Java method Integer.valueOf() to convert the given String value to Integer type value. The function takes the string as a parameter and returns the numeric value. Below is the code example for that.

String mystr = "10";
int val = Integer.valueOf(mystr);
        
System.out.println(val);

Output

10
Was this helpful?