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:

  1. parseLong(): parses the string to Long
  2. 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()
  3. 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.

Similar Reads

Program to Convert Java String to int

Let us take an example straight away to get used to the working parseInt() method :...

parseInt() Method in Java

...

Cases of parseInt() Method

There are two variants of this method:...

Number Format Exceptions of parseInt() Method

Let’s take a random code snippet further understand the illustrations better....

Another Approach for Converting a String to Integer

Exceptions caused by parseInt() Method mentioned below:...