Check whether the String contains only digit characters in Java



Introduction

In this article, we'll explore how to check whether a given string contains only digits or a mix of digits and other characters in Java. We'll achieve this by using the String class and its matches() method.

Problem Statement

Given a string write a Java program to check whether it contains only digit characters.

Input 1

4434

Output 1

String contains only digits!

Input 2

5demo9

Output 2

String contains digits as well as other characters!

Steps to check digit characters in String

The following are the steps to check whether the String contains only digit characters in Java ?

  • First start with a string containing only digits.
  • Then we will use the matches() method to verify if the string contains only digits.
  • Ensure that the string has more than two characters.
  • If both conditions are met, we'll print a message indicating the string contains only digits

Check for digits only

Below is the Java program to check for digits and other characters ?

public class Demo {
   public static void main(String []args) {
      String str = "4434";
      if(str.matches("[0-9]+") && str.length() > 2) {
         System.out.println("String contains only digits!");
      }
   }
}

Output

String contains only digits!

Check for digits and other characters

The following are the steps to check whether the String contains both digits and non-digit characters in Java ?

  • First, start with a string that contains both digits and non-digit characters.
  • Then we will again use the matches() method to check if the string contains only digits.
  • And then verify that the string has more than two characters.
  • Depending on the conditions, we'll print whether the string contains only digits or also includes other characters.

Below is the Java program to check for digits and other characters ?

public class Demo {
   public static void main(String []args) {
      String str = "5demo9";
      System.out.println("String: "+str);
      if(str.matches("[0-9]+") && str.length() > 2) {
         System.out.println("String contains only digits!");
      } else {
         System.out.println("String contains digits as well as other characters!");
      }
   }
}

Output

String: 5demo9
String contains digits as well as other characters!
Updated on: 2024-08-27T18:49:01+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements