Number Format Exceptions of parseInt() Method
Exceptions caused by parseInt() Method mentioned below:
Java
// Java Program to Demonstrate Working of parseInt() Method // Where NumberFormatException is Thrown // Main class public class GFG { // Main driver method public static void main(String args[]) { // NumberFormatException String invalidArguments = "" ; // invalidArguments Error empty string // passed int emptyString = Integer.parseInt(invalidArguments); // The Converted Intger is out of bound // Too large to be called Integer int outOfRangeOfInteger = Integer.parseInt( "w3wiki" , 29 ); // Domain Number System int domainOfNumberSystem = Integer.parseInt( "geeks" , 28 ); // Print commands on console System.out.println(emptyString); System.out.println(outOfRangeOfInteger); System.out.println(domainOfNumberSystem); } } |
Output
Similarly, we can convert the string to any other primitive data type:
- parseLong(): parses the string to Long
- parseDouble(): parses the string to double If we want to convert the string to an integer without using parseInt(), we can use valueOf() method. It also has two variants similar to parseInt()
- Difference between parseInt() and valueOf(): parseInt() parses the string and returns the primitive integer type. However, valueOf() returns an Integer Object.
Note: valueOf() uses parseInt() internally to convert to integer.
String to int in Java
In Java, while operating upon strings, there are times when we need to convert a number represented as a string into an integer type. We usually do this because we can operate with a wide flexible set of operations over strings. The method generally used to convert String to Integer in Java is parseInt() of the String class.
In this article, we will see how to convert a String to int in Java.