Searching...
Wednesday, 23 October 2013

How to check if a string contains only digits in java

11:10

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

0 comments: