There are two ways to convert String to Integer in Java,
- String to Integer using Integer.parseInt()
- String to Integer using Integer.valueOf()
Let’s say you have a string – strTest - that contains a numeric value.
String strTest = “100”;Try to perform some arithmetic operation like divide by 4 – This immediately shows you a compilation error.
class StrConvert{ public static void main(String []args){ String strTest = "100"; System.out.println("Using String:" + (strTest/4)); } }
Output:
/StrConvert.java:4: error: bad operand types for binary operator '/' System.out.println("Using String:" + (strTest/4));
Hence, you need to convert a String to int before you peform numeric operations on it
Example 1: Convert String to Integer using Integer.parseInt()
Syntax of parseInt method as follows:
int <IntVariableName> = Integer.parseInt(<StringVariableName>);
Pass the string variable as the argument.
This will convert the Java String to java Integer and store it into the specified integer variable.
Check the below code snippet-
This will convert the Java String to java Integer and store it into the specified integer variable.
Check the below code snippet-
class StrConvert{ public static void main(String []args){ String strTest = "100"; int iTest = Integer.parseInt(strTest); System.out.println("Actual String:"+ strTest); System.out.println("Converted to Int:" + iTest); //This will now show some arithmetic operation System.out.println("Arithmetic Operation on Int: " + (iTest/4)); } }
Output:
Actual String:100 Converted to Int:100 Arithmetic Operation on Int: 25
Example 2: Convert String to Integer using Integer.valueOf()
Integer.valueOf() Method is also used to convert String to Integer in Java.
Following is the code example shows the process of using Integer.valueOf() method:
public class StrConvert{ public static void main(String []args){ String strTest = "100"; //Convert the String to Integer using Integer.valueOf int iTest = Integer.valueOf(strTest); System.out.println("Actual String:"+ strTest); System.out.println("Converted to Int:" + iTest); //This will now show some arithmetic operation System.out.println("Arithmetic Operation on Int:" + (iTest/4)); } }
Output:
Actual String:100 Converted to Int:100 Arithmetic Operation on Int:25
NumberFormatException
NumberFormatException is thrown If you try to parse an invalid number string. For example, String ‘Guru99’ cannot be converted into Integer.
Example:
public class StrConvert{ public static void main(String []args){ String strTest = "Guru99"; int iTest = Integer.valueOf(strTest); System.out.println("Actual String:"+ strTest); System.out.println("Converted to Int:" + iTest); } }
Above example gives following exception in output:
Exception in thread "main" java.lang.NumberFormatException: For input string: "Guru99"
No comments:
Post a Comment