Java Program to Convert String to int - The Coding Shala
Hey there, welcome back to another post. In this post, we are going to learn how to convert String to int in Java.
Java Program to Convert String to int
There are a few ways by using those we can convert String to int data type in Java. The most common ways are below:
- By using Integer class's parseInt() method.
- By using Integer class's valueOf() method.
Now let's see these methods with examples in Java.
Java Example to Convert String to int using parseInt() method
We can convert a String to int by using the Integer wrapper class's parseInt() method.
Java Program:
/** * https://www.thecodingshala.com/ */ public class Main { public static void main(String[] args) { String str = "100"; // using Integer.parseInt() int num1 = Integer.parseInt(str); System.out.println("Converted int, num1 is: " + num1); System.out.println("5 + str is: " + (5 + str)); System.out.println("5 + num1 is: " + (5 + num1)); } }
Output:
Converted int, num1 is: 100 5 + str is: 5100 5 + num1 is: 105
Java Example to Convert String to int using valueOf() method
We can convert a String to an int in Java by using the Integer class's valueOf() method.
Java Program:
/** * https://www.thecodingshala.com/ */ public class Main { public static void main(String[] args) { String str = "100"; // using Integer.valueOf() int num = Integer.valueOf(str); System.out.println("String str: " + str); System.out.println("1 + str = " + (1 + str)); System.out.println("Converted int, num is: " + num); System.out.println("1 + num = " + (1 + num)); String str2 = "-50"; System.out.println("String str2 is: " + str2); int num2 = Integer.valueOf(str2); System.out.println("Converted num2 is: " + num2); } }
Output:
String str: 100 1 + str = 1100 Converted int, num is: 100 1 + num = 101 String str2 is: -50 Converted num2 is: -50
Exception case while converting String to int in Java
When we convert a String to int then it must be a valid number otherwise we will get a NumberFormatException error. for example, String "1234" is a valid number in int data type but String "ab12" will not be a valid number.
Java Program:
/** * https://www.thecodingshala.com/ */ public class Main { public static void main(String[] args) { String str = "ab1234"; // Exception case int num1 = Integer.parseInt(str); System.out.println("String is: " + str); System.out.println("Converted int is: " + num1); } }
Output:
Exception in thread "main" java.lang.NumberFormatException: For input string: "ab1234" at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67) at java.base/java.lang.Integer.parseInt(Integer.java:668) at java.base/java.lang.Integer.parseInt(Integer.java:786) at Main.main(Main.java:11)
- Java Program to Convert int to long
- Java Program to Convert long to int
- Java Program to Convert int to char
- Java Program to Convert char to int
- Java Program to Convert int to String
Comments
Post a Comment