Convert String to int
Converting a String to an int or Integer is a very common operation in Java. There are a few simple ways to do this conversion. The frequently used method is Integer.parseInt() .Integer.parseInt() method
Integer.parseInt() Parses the string argument as a signed decimal integer and throws a NumberFormatException if the string can’t be converted to an int type.
String strNum="999";
int numStr = Integer.parseInt(strNum);
The value of numStr would be 999.
If the first character is a minus(-) sign it will return a minus value.
String strNum="-999";
int numStr = Integer.parseInt(strNum);
The value of numStr would be -999.
If the given String is not valid, conversion will throws a NumberFormatException .
String strNum="asdf";
int numStr = Integer.parseInt(strNum);
The above code will throws a NumberFormatException.
Example
class TestClass{
public static void main (String[] args){
String strNum="999";
int numStr = Integer.parseInt(strNum);
System.out.println("Output is " + numStr);
String strNum1="-999";
int numStr1 = Integer.parseInt(strNum1);
System.out.println("Output is " + numStr1);
}
}
Output
Value is 999
Value is -999
Integer.valueOf()
Java Integer.valueOf() returns an Integer instance representing the specified int value.
class TestClass{
public static void main (String[] args){
String strNum="999";
Integer numStr = Integer.valueOf(strNum);
System.out.println("Value is " + numStr);
}
}
Output
Value is 999
Integer's Constructor
You can convert a string to an integer value using Integer's Constructor.
class TestClass{
public static void main (String[] args){
String strNum="999";
Integer numStr = new Integer(strNum);
System.out.println("Value is " + numStr);
}
}
Output
Value is 999
Difference between parseInt() and valueOf()
Integer.valueOf() returns an Integer object, while Integer.parseInt() returns an int primitive.
Related Topics
- How to Get the Length of a String
- Java String charAt() Method
- String indexOf() method
- Java String replace()
- Java String contains()
- String Comparison in Java
- Java String substring()
- Java String concat() Method
- Java String split() method
- Java StringBuilder Class
- StringTokenizer in Java
- How to convert int to String in Java?