How to check if string is number in java?

By Preeti Jain Last updated : February 02, 2024

Java - Checking is string is numeric

To check whether a string is numeric, you can use the Double.parseDouble() method by passing the string to be checked. If parsing doe successful, the method returns true; false, otherwise. And, then you can check the condition. You can also use exception handling to handle logic if the string is not parsed.

Steps

Below are the steps to check if string is numeric in Java:

  • In the first step, we will take a string variable named str and store any value in it.
  • In the second step, We will take a boolean variable named str_numeric which stores Boolean values like true or false. Let us suppose that a given string is numeric so that initially boolean variable str_numeric is set to true.
  • In the third step we will do one thing in the try block we will convert a String variable to Double by using the parseDouble() method because initially, we are assuming that given the string is a number that's why we are converting first.
  • If it throws an error (i.e. NumberFormatException), it means the given String is not a number, and then at the same time boolean variable str_numeric is set to false. Otherwise given string is a number.

Java code to check if string is number

This code checks whether the given string is numeric is not.

public class IsStringNumeric {
  public static void main(String[] args) {
    // We have initialized a string variable with double values
    String str1 = "1248.258";
    // We have initialized a Boolean variable and 
    // initially we are assuming that string is a number 
    // so that the value is set to true        
    boolean str_numeric = true;

    try {
      // Here we are converting string to double 
      // and why we are taking double because 
      // it is a large data type in numbers and 
      // if we take integer then we can't work 
      // with double values because we can't covert 
      // double to int then, in that case, 
      // we will get an exception so that Boolean variable 
      // is set to false that means we will get wrong results. 
      Double num1 = Double.parseDouble(str1);
    }

    // Here it will raise an exception 
    // when given input string is not a number 
    // then the Boolean variable is set to false. 
    catch (NumberFormatException e) {
      str_numeric = false;
    }

    // if will execute when given string is a number
    if (str_numeric)
      System.out.println(str1 + " is a number");
    // Else will execute when given string is not a number       
    else
      System.out.println(str1 + " is not a number");
  }
}

Output

The output of the above code is:

D:\Programs>javac IsStringNumeric.java

D:\Programs>java IsStringNumeric
1248.258 is a number

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.