Java – Check if a string contains integer only

The following static function helps you to check if a string contains number.

public static boolean checkIfNumber(String in) {
  try {
    Integer.parseInt(in);
  } catch (NumberFormatException ex) {
    return false;
  }
  return true;
}


 

Try it out.

public class CheckIfNumber {
  public static void main(String[] args) {
    System.out.println(checkIfNumber("123"));
    System.out.println(checkIfNumber("Eureka"));
    System.out.println(checkIfNumber("Eureka 123"));
  }
	
  public static boolean checkIfNumber(String in) {
    try {
      Integer.parseInt(in);
    } catch (NumberFormatException ex) {
      return false;
    }
	  
    return true;
  }
}

 

The console output.

true
false
false

 

Reference: Validate if string is a number

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.