Convert String to int in Java

Convert String to int in Java Example describes about Converting a String to int using Java.

The Integer class will wraps the value of the primitive type int in an object. An Integer is an Object that contains a single int field. Integer values are immutable. If you want to change the value of a Integer variable, you need to create a new Integer object and discard the old one.

When you need to convert String to int in Java, we can use Integer.parseInt(String s) method of the Integer class, It will convert the string to primitive int.

If you need an Integer object in lieu of primitive int, you can use Integer.valueOf(String s). It will convert the string to Integer Object

In the following case If String is not Integer type, it will throws a NumberFormatException, so you should catch this exception

Convert String to int in Java

public class ConvertStringToIntExample {
 
public static void main(String[] args) {
   
try {
     
String str = "10";
     
// returns a primitive int
     
System.out.println(Integer.parseInt(str));
     
// returns an Integer object
     
System.out.println(Integer.valueOf(str));
   
} catch (NumberFormatException nfe) {
     
System.out.println("NumberFormatException: " + nfe.getMessage());
   
}
  }
}
Output
10
10










1 Responses to "Convert String to int in Java"
  1. kavya 2018-04-09 00:36:18.0

Your email address will not be published. Required fields are marked *