Saturday 12 November 2022

Check whether string contain only digits or not in Java

Write a function that takes a string as input and return true, if the string contain only digits, else false.

 

Signature

public static boolean hasOnlyDigits(final String str)

Find the below working application.


StringDigitsCheck.java

package com.sample.app.strings;

import java.util.regex.Pattern;

public class StringDigitsCheck {

	private static final Pattern ONLY_DIGITS_PATTERN = Pattern.compile("\\d+");

	/**
	 * 
	 * @param str
	 * 
	 * @return true, if the string contain only digits, else false.
	 */
	public static boolean hasOnlyDigits(final String str) {

		if (str == null || str.isEmpty()) {
			return false;
		}

		return ONLY_DIGITS_PATTERN.matcher(str).matches();
	}

	public static void main(String[] args) {
		String str1 = null;
		String str2 = "Hello";
		String str3 = "122324";
		String str4 = "32453\n";

		System.out.println("is str1 contain only digits : " + hasOnlyDigits(str1));
		System.out.println("is str2 contain only digits : " + hasOnlyDigits(str2));
		System.out.println("is str3 contain only digits : " + hasOnlyDigits(str3));
		System.out.println("is str4 contain only digits : " + hasOnlyDigits(str4));
	}

}

Output

is str1 contain only digits : false
is str2 contain only digits : false
is str3 contain only digits : true
is str4 contain only digits : false


 

Previous                                                 Next                                                 Home

No comments:

Post a Comment