×

java.lang.NumberFormatException for Input String

java.lang.NumberFormatException for Input String

The exception java.lang.NumberFormatException for input string occurs when we try to convert a string into a number format.

For example, if someone converts the string “Tutorial & Example” into a number, the java.langNumberFormatException is raised, as it is not possible to convert the given string into a number.

The NumberFormatException is the child of the IllegalArgumentnException class. The exception also implements the Serializable interface. Note that itis an unchecked exception.

Constructors of the NumberFormatException

ConstructorDescription
NumberFormatException()Constructs an object of the NumberFormatException class with no specific message.
NumberFormatException(String s)Constructs an object of the NumberFormatException class with the specific message mentioned in the string s.

The following shows when the NumberFormatException is raised.

FileName: NumberFormatExecptionExample.java

 public class NumberFormatExceptionExample
{ 
// main method
public static void main(String argvs[])
{
// Input string
String str1 = "Tutorial & Example";
// converting the input string into an integer
int i = Integer.parseInt(str1); // here the exception is raised.
// control never reaches here
System.out.println(i);
}
} 

Output:

Common Cause for the NumberFormatException  

We have already seen in the above example that when there is irrational string format. There can be various ways that makes the input string inappropriate for the conversion into numbers. Some of the ways are discussed below.

  • When the input string is empty. For example, int i = Integer.parseInt(“”);
  • When the input string is null. For example, int i = Integer.parseInt(null);
  • When the input string contains leading blank spaces. For example, int i = Integer.parseInt(“  143”);
  • When the input string contains trailing blank spaces. For example, int i = Integer.parseInt(“133  ”);
  • When the input string contains alphabets as well as numbers. For example, int i = Integer.parseInt(“abc23”);
  • When the input string contains numbers only, but the number overflows. For example, int i = Integer.parseInt(“14455455423456”); In this example, the input string such a huge number that an integer cannot hold.
  • When the input string contains number only, but the number underflows. For example, int i = Integer.parseInt(“-14455455423456”); In this example, the input string such a small number that an integer cannot hold.
  • When there is a mismatch between the method used for parsing and the input number.

For example, int i = Integer.parseInt(“14.455”); In this example, the input string is of type float or double. However, the parse method used here is of type int. Hence, the exception is raised.

Avoiding the NumberFormatException 

We have seen the various scenarios where the exception NumberFormatException is raised. Therefore, one needs to handle the exception as it is common to put inappropriate string for parsing. The following program shows how to handle the NumberFormatException.

NumberFormatExceptionExample1.java

 public class NumberFormatExceptionExample1
{ 
// main method
public static void main(String argvs[])
{
// Input string
String str1 = "Tutorial & Example";
try
{
// converting the input string into an integer
int i = Integer.parseInt(str1); // here the exception is raised.
System.out.println(i);
}
catch(NumberFormatException ex)
{
System.out.println("The input string is inappropriate. Hence, the conversion is not possible.");   
}
}
} 

Output:

The input string is inappropriate. Hence, the conversion is not possible.


Explanation: The line of code at which there is a chance of occurrence of NumberFormatException should be enclosed within a try-catch block. Thus, when the exception is raised, it can be handled in the catch block.


Related Topics

Local Minima in Java

An Array Finding a local minimum in an array a[0. m-1] of different integers is the job. A[i] is considered a local minimum if it is smaller than two of its...

4 minutes read.

Java LinkedHashSet

LinkedHashSet in Java with Example Java LinkedHashSet extends HashSet and Implements the Set interface. It doesn’t contain only duplicate values like HashSet. It also permits the null elements. It maintains the order...

5 minutes read.

Missing Number in an Arithmetic Progression in Java

Given an array that shows the elements of an orderly arithmetic progression. Find the missing number to complete the succession of elements. Example:  Input: a [ ] = {2 , 4 , 6...

3 minutes read.

Java Boolean equals() method

The equals() method of Java Boolean class returns a Boolean value true if the specified argument is not null and is same as this object, else it returns false. Syntax public boolean...

2 minutes read.

Transaction Management in java

Definition: A database application is an application that is running against a relational database and executes one or more transactions. A transaction is an executing program that contains some database operations,...

4 minutes read.

Thread Safety and How to Achieve it in Java

Before diving into the topic, let’s just recap the concept of Multithreading provided by Java where we can create and execute multiple threads of the same object. When these multiple...

5 minutes read.

Print Matrix Diagonally in Java

The aim is to print the elements of a matrix of size n*n in some kind of a diagonal pattern. Input : mat[3][3] = {{1, 2, 3},                      {4, 5, 6},                      {7,...

3 minutes read.

Web Crawler in Java

In this article, you will be acknowledged with what a web crawler in java is and what are its functions. You will also be able to understand where to implement...

4 minutes read.

Java Math atan() Method

The atan() method of Math class computes the trigonometric Arc Tangent (inverse of tangent ) of an angle. The value returned is between -pi/2 to pi/2. Syntax: public static double atan(double a) Parameters: The...

2 minutes read.

How to uninstall the Java in Ubuntu

We need java on our computers in our daily lives because there are lots of different applications that are developed using the java environment, so we have to install java...

4 minutes read.

Radix Sort in Java

Radix Sort in Java Radix sort in Java uses the digits of the numbers given in the sorted array to sort the numbers. The radix sort uses the place value of...

5 minutes read.

Mutable and Immutable in Java

Java is a programming language in which everything is treated as an object. Its procedures and functions are centred around objects because it is an object-oriented programming language. Mutable and...

6 minutes read.

Java String replace() method

Java String replace() method returns new String by replacing old characters with new characters or old CharSequence to new CharSequence. Syntax: public String replace(char oldChar, char newChar) public String replace(CharSequence target, CharSequence replacement) Parameters: oldChar...

2 minutes read.

Special Operators in Java

An operator in Java is a special symbol. It is used to perform operations on two or more variables.  We all know basic operations in Java. There are 8 types...

5 minutes read.

Java String Inbuilt functions

There are different types of inbuilt functions available in the Java String class, all of them are listed below. Char chat At (int index)It outputs the character indicated by the index....

5 minutes read.

Java Default Keyword

The Default keyword in java programming language is used as access modifier.If any of the variable or the constructor or the methods or the classes are not assigned with the...

3 minutes read.

Tilt operator in Java | Tilde operator in Java Example

The symbol designates it as a unary operator (pronounced as the tilde). It gives back the bit's complement or inverse. Every 0 turns into a 1, and every 1 back...

3 minutes read.

Enum Java Interview Questions

1. What exactly is Java? Java is a portable, high-level, object-oriented, robust, secure, platform-independent, multi-threaded, high-performance programming language. Developed in June 1991 by James Gosling, also known as Platform. 2. Enum is...

3 minutes read.

How to Convert char to int in Java

How to Convert char to int in Java When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to...

3 minutes read.

Why main method is static in Java

The method serves as the entry point for Java programmes or simply the point from which the programme begins to run. As a result, it is one of the most...

4 minutes read.