×

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

How to Split String by Comma in Java

strsplit() technique permits you to break a string given the explicit Java string delimiter. The Java string split property is frequently a space or a comma(,) that you want to...

7 minutes read.

Powerful Number in Java

We will define a powerful number in this article and write Java programs to determine whether a given number is a powerful number or not. Java coding interviews and academic...

6 minutes read.

Java Math cos() Method

The cos() method of Math class returns the trigonometric cosine of the specified angle. Syntax: public static double cos(double a) Parameters: The parameter ‘a’ represents an angle measured in radians. Return Value: The cos() method returns...

1 minute read.

Difference between String, StringBuffer and StringBuilder in java

What is a string in Java? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Java SHA256

Definition: In cryptography, SHA is a hash function that takes 20 bytes of input and produces an approximate 40-digit hexadecimal integer as the hash result. Class for Message Digest: Java's MessageDigest Class,...

2 minutes read.

Java Math.multiplyExact() method in Java

Java has an inbuilt math function called Math.multiplyExact() that returns the sum of the parameters. If the result exceeds an integer, an exception is thrown. There is no need to...

2 minutes read.

Block Swap Algorithm for array rotation in Java

An array and r, the rotation factor by which the array must be rotated, are both provided to us. We must then return the rotated array. A well-known and popular method is...

4 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.

Java Append Data to File

When writing data to a file using the classes within the java.io package, its file will often be overwritten, meaning that any existing data will be removed and new data...

4 minutes read.

Java LinkedList vs ArrayList

LinkedList In LinkedList, each element is a distinct entity containing an information portion and an address component, and the elements are not kept in consecutive locations. Pointers & addresses are used...

3 minutes read.

Java Write File

In this post, we'll examine various Java programming methods for writing into files. Since this class is character-oriented due to how it is used in file handling in Java, it...

4 minutes read.

Java Finally Keyword

The final block in Java is used to run essential code, such as connection closure, among other things. Whether an exception is resolved or not, the Java finally block has...

3 minutes read.

Comparetoignorecase in Java

In Java, the function compareToIgnoreCase ( ) is part of the String class, which is part of the java.lang package. It is used to compare any two strings while disregarding...

4 minutes read.

Difference between next() and nextline() in Java

One of the simplest methods for receiving input of the basic data types, also including int, double, and strings, in Java, is to use the Scanner class, which is part...

3 minutes read.

XOR of Array Elements Except Itself in Java

A lot of the biggest IT organisations, including The Google, Amazon, TCS, and The Accenture, etc., question about this issue in their interview processes. By addressing the issue, one hopes to assess...

5 minutes read.

How to Update Java

As we all know that java can be installed in all operating systems like windows, Linux, macOS. We are available with the java 17 and java 18 versions in the...

3 minutes read.

Resultset in java

Resultset: A result set is an interface that is present in the package java.sql and the resultset is used to store the data that are returned from the database table after...

5 minutes read.

Prime Number Program in Java

Prime Number Program in Java using for loop A natural number which is greater than 1 and has only two factors the number itself and 1 is called prime number. In...

2 minutes read.

Java Integer max() method

The max() method of Integer class returns the greater of two int values. It returns the same result as by calling Math.max. Syntax public static int max(int a, int b) Parameters The parameters ‘a’...

2 minutes read.

Java inheritance with Example

Java inheritance Java inheritance is a mechanism in which a child object acquires all the properties and behaviors of a parent object. It helps in reusing the code and establishes...

7 minutes read.