How to Check If a String Is Numeric in Java


In this example we will show how to judge if a string is numeric through a conversion of an array of characters in NumberFormatException.

Source Code

1)

package com.beginner.examples;

public class CheckStringIsNumeric {

	public static void main(String[] args) {

		System.out.println("checkNumeric() method:");
		System.out.println("120!:" + checkNumeric("120!"));

		System.out.println("12345:" + checkNumeric("12345"));

		System.out.println("8.12:" + checkNumeric("8.12"));

		System.out.println("checkNumeric_2() method:");

		System.out.println("120!:" + checkNumeric_2("120!"));

		System.out.println("12345:" + checkNumeric_2("12345"));

		System.out.println("8.12:" + checkNumeric_2("8.12"));

	}

	public static boolean checkNumeric(String str) {

		if (str.length()  '0' && c < '9' || c == '.')) {
				return false;
			}

		}

		return true;
	}

	public static boolean checkNumeric_2(String str) {
		
		if (str.length() < 1 || str == null) {
			return false;
		}

		for (char c : str.toCharArray()) {
			// Use the isDigit() method in the Character class to determine whether it is a
			// number
			if (!Character.isDigit(c)) {
				return false;
			}

		}

		return true;
	}
}

Output:

checkNumeric() method:
120!:false
12345:true
8.12:true
checkNumeric_2() method:
120!:false
12345:true
8.12:false

2)

package com.beginner.examples;

public class CheckStringIsNumeric2 {

	public static void main(String[] args) {
		
		
		System.out.println("123:"+checkNumeric("123"));
		
		System.out.println("123?:"+checkNumeric("123?"));
		
	}
	
	public static boolean checkNumeric(String str)
	{
		
		try {
			Integer.parseInt(str);
		}
		catch (NumberFormatException e) {
		
			return false;
		}
		
		return true;
	}

}

Output:

123:true
123?:false
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments