Wednesday, August 21, 2019

Java - String to Int Conversion Examples

1. Overview


In this tutorial, We'll learn to convert String to integer in java.

We will be showing the example programs using the following methods and possible exceptions that occur at runtime.

Integer.parseInt()
Integer.valueOf()

For Example, We have a string "456" and want it to convert int type.



2. Convert String to Integer using Integer.parseInt()


Writing a java program using Integer.parseInt(String s) method. parseInt() is a static method in Integer class. So, this method is accessed directly with the class name.

In the below example taking string "12345" which has only numbers and trying to convert it into integer type.

package com.java.w3schools.blog.string;

public class StringToIntparseIntExample {
    
    public static void main(String[] args) {
       
       // Way 1
       String string = "12345";
       int intValue = Integer.parseInt(string);
       System.out.println("converted int Value : " + intValue);
    }

}

Output:

converted int Value : 12345


The above program converted successfully from string to int. No errors are thrown at the time of execution. This example is using Integer.parseInt() method.

3. Convert String to Integer using Integer.valueOf()


We'll see now another way to convert String to Integer. Integer is a wrapper class and it has utility method valueOf(String s).

// Way 2
String str = "789";
int value = Integer.valueOf(str);
System.out.println("converted string value to int using Integer valueOf method : " + value);

valueOf() method is a static method and directly can be invoked with the class name.

Output:

converted string value to int using Integer valueOf method : 789

4. Exception 


when using these two approaches in converting string to int, there might be chances to pass the wrong input these methods. Passing string with alphabetic may cause some unexpected problems. This will throw runtime NumberFormatException. Eg. Taking the string "java8" and this has alphabets that cause the problem in conversion. so this method does not know how to parse such type of input. So, It will throw NumberFormatException.


// NumberFormatException
String invalid = "java8example";
int invalidInt = Integer.parseInt(invalid);

Runtime Exception:

Once we run this program it will fail at runtime with the following reason. "java8example" string does not have the appropriate format.

Exception in thread "main" java.lang.NumberFormatException: For input string: "java8example"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:658)
at java.base/java.lang.Integer.parseInt(Integer.java:776)
at com.java.w3schools.blog.string.StringToIntparseIntExample.main(StringToIntparseIntExample.java:19)


5. Handling NumberFormatException


If we not handling NumberFormatException in try/catch block then we definitely end up in stopping the application. To avoid application halt, We should keep our code in the try block to handle error scenarios.

// Handling NumberFormatException
int number;
String strValue = "java8example";
try {

     number = Integer.parseInt(strValue);
} catch (NumberFormatException e) {
 number = -1;
}

if (number != -1) {
 System.out.println("String is parsed to a Number");
} else {
 System.out.println("Invalid input " + strValue + " is given");
}

In the above program, Parsing logic is placed in a try block and in the catch, block setting the number to -1. -1 indicates that parsing is failed and it will process the next steps without any fail.

Output:

Invalid input java8example is given

Printed from else block because input has alphabets. The solution is to keep the parsing logic inside a try block and if an exception occurs setting the value to default.

6. Conclusion


In this article, We've seen the ways to convert String to Integer. For invalid input, we will get runtime exception NumberFormatException. For best practices, we must keep the parsing logic inside try/catch block and set the value to default value if fails.


GitHub 
Integer.parseInt() Ref
Integer.valueOf() Ref




No comments:

Post a Comment