Check if a string is a number in Java
There are several ways to check whether the entered string is a number or not in Java program.
Here I have mentioned three methods to do so.
METHOD-1: We can parse String to Double or Int and check whether it throws an error or not. If it throws an error then the entered string is not numeric else if it does not throws an error then it is numeric.
Code:
public class Main { public static boolean isNumeric(String str) { if (str == null) { return false; } try { double d = Double.parseDouble(str); } catch (NumberFormatException nf) { return false; } return true; } public static void main(String[] args) { if(isNumeric("dsfd")){ System.out.print("true"); } else System.out.print("false"); } }
Output: false
METHOD-2: We can use regex (regular expressions) to check whether the entered string is number or not. As per Java regular expressions, the +
means “one or more times” and \d
means “a digit” and ‘.’ is used for int or float.
Code:
public class Main { public static boolean isNumeric(String str) { if (str == null) return false; return str.matches("-?\\d+(\\.\\d+)?"); } public static void main(String[] args) { if(isNumeric("44")){ System.out.print("true"); } else System.out.print("false"); } }
Output: true
METHOD-3: You can convert String to an array of characters and check one by one for each character that if it is a number or not by applying if condition.
Code:
public class Main { public static boolean isNumeric(String str) { if (str == null) return false; char[] arr = str.toCharArray(); if (arr.length <= 0) return false; int ind = 0; if (arr[0] == '-' && arr.length > 1) ind = 1; for (; ind < arr.length; ind++) { if (arr[ind] < '0' || arr[ind] > '9') // Character.isDigit() can go here too. return false; } return true; } public static void main(String[] args) { if(isNumeric("56")){ System.out.print("true"); } else System.out.print("false"); } }
Output: true
Leave a Reply