How to check if a string contains only digits in java

We know Integer.parseInt(number) will throw NumberFormatException if we are passing any non digit charactors, using this here is one simple example which is checking the given string contains only digit or not.

Example

package com.pretech;
public class NumberCheck {
	
	public static void main(String[] args) {
		System.out.println(isNumber("121221"));
		System.out.println(isNumber("pretech123"));
	}
	  private static boolean isNumber(final String number) {
	        boolean bisNumber = false;
	        if (number == null) {
	            bisNumber = false;
	        }
	        try {
	            Integer.parseInt(number);
	            bisNumber = true;
	        } catch (NumberFormatException ne) {
	            bisNumber = false;
	        }
	        return bisNumber;
	    }
}

Output



true
false

No comments:

Post a Comment

12 classic String-based Java interview questions with simple explanations and code.

  1️⃣ Check if a String is a Palindrome Problem Given a string, check if it reads the same forward and backward. Example: "madam...

Featured Posts