Java Data Type How to - Check if a String is a numeric type








Question

We would like to know how to check if a String is a numeric type.

Answer

//w  ww . j  a va 2 s  .  co  m
public class Main {
  public static void main(String[] args) {
    boolean flag = true;
    String str = "123";

    for (int i = 0; i < str.length(); i++) {
      if (str.charAt(i) > 48 && str.charAt(i) < 58) {
        flag = false;
        break;
      }
    }
    if (flag == true) {
      System.out.println("String is a valid String..");
    } else {
      System.out.println("String contains number");
    }
  }
}