w3resource

Java String Exercises: Check if a given string contains only digits

Java String: Exercise-101 with Solution

Write a Java program to test if a given string contains only digits. Return true or false.

Sample Solution-1:

Java Code:

public class Main {
    
    public static void main(String[] args) {
       String digit_string1 = "131231231231231231231231231212312312";
        String digit_string2 = "13123123123Z1231231231231231212312312";
        System.out.println("First string:");
       System.out.println(digit_string1);
       boolean result1 = test_only_digits(digit_string1);
        System.out.println(result1);
        System.out.println("\nSecond string:");
       System.out.println(digit_string2);
        boolean result2 = test_only_digits(digit_string2);
        System.out.println(result2);                                
 }
     public static boolean test_only_digits(String digit_string) {
       for (int i = 0; i < digit_string.length(); i++) {
           if (!Character.isDigit(digit_string.charAt(i))) {
               return false;
           }
       }
       return true;
   }
}

Sample Output:

First string:
131231231231231231231231231212312312
true

Second string:
13123123123Z1231231231231231212312312
false

Pictorial Presentation:

Java String Exercises: Test if a given string contains only digits
Java String Exercises: Test if a given string contains only digits

Flowchart:

Flowchart: Java String Exercises - Test if a given string contains only digits

Sample Solution-2:

Main.java Code:

//MIT License: https://bit.ly/35gZLa3
import java.util.concurrent.TimeUnit;

public class Main {

    private static final String ONLY_DIGITS = "45566336754493420932877387482372374982374823"
            + "749823283974232237238472392309230923849023848234580383485342234287943943094"
            + "234745374657346578465783467843653748654376837463847654382382938793287492326";
    
    private static final String NOT_ONLY_DIGITS = "45566336754493420932877387482372374982374823"
            + "749823283974232237238472392309230923849023848234580383485342234287943943094"
            + "234745374657346578465783467843653748654376837463847654382382938793287492326A";
    
    public static void main(String[] args) {

        System.out.println("Input text with only digits: \n" + ONLY_DIGITS + "\n");
        System.out.println("Input text with other characters: \n" + NOT_ONLY_DIGITS + "\n");
                
        System.out.println("Character.isDigit() solution:");
        long startTimeV1 = System.nanoTime();
        
        boolean onlyDigitsV11 = Strings.containsOnlyDigitsV1(ONLY_DIGITS);
        boolean onlyDigitsV12 = Strings.containsOnlyDigitsV1(NOT_ONLY_DIGITS);
        
        displayExecutionTime(System.nanoTime() - startTimeV1);
        System.out.println("Contains only digits: " + onlyDigitsV11);
        System.out.println("Contains only digits: " + onlyDigitsV12);
        
        System.out.println();        
        System.out.println("String.matches() solution:");
        long startTimeV2 = System.nanoTime();
        
        boolean onlyDigitsV21 = Strings.containsOnlyDigitsV2(ONLY_DIGITS);
        boolean onlyDigitsV22 = Strings.containsOnlyDigitsV2(NOT_ONLY_DIGITS);
        
        displayExecutionTime(System.nanoTime() - startTimeV2);
        System.out.println("Contains only digits: " + onlyDigitsV21);
        System.out.println("Contains only digits: " + onlyDigitsV22);
        
        System.out.println();                
        System.out.println("Java 8, functional-style solution:");
        long startTimeV3 = System.nanoTime();
        
        boolean onlyDigitsV31 = Strings.containsOnlyDigitsV3(ONLY_DIGITS);
        boolean onlyDigitsV32 = Strings.containsOnlyDigitsV3(NOT_ONLY_DIGITS);
        
        displayExecutionTime(System.nanoTime() - startTimeV3);
        System.out.println("Contains only digits: " + onlyDigitsV31);
        System.out.println("Contains only digits: " + onlyDigitsV32);        
    }
    
    private static void displayExecutionTime(long time) {
        System.out.println("Execution time: " + time + " ns" + " ("
                + TimeUnit.MILLISECONDS.convert(time, TimeUnit.NANOSECONDS) + " ms)");
    }
    
}

Strings.java Code:

//MIT License: https://bit.ly/35gZLa3
public final class Strings {

    private Strings() {
        throw new AssertionError("Cannot be instantiated");
    }

    // Note: For Unicode supplementary characters use codePointAt() instead of charAt()
    //       and codePoints() instead of chars()
    
    public static boolean containsOnlyDigitsV1(String str) {

        if (str == null || str.isEmpty()) {
            // or throw IllegalArgumentException
            return false;
        }
        
        for (int i = 0; i < str.length(); i++) {
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }
        
        return true;
    }

    public static boolean containsOnlyDigitsV2(String str) {

        if (str == null || str.isEmpty()) {
            // or throw IllegalArgumentException
            return false;
        }

        return str.matches("[0-9]+");
    }

    public static boolean containsOnlyDigitsV3(String str) {

        if (str == null || str.isEmpty()) {
            // or throw IllegalArgumentException
            return false;
        }

        return !str.chars()
                .anyMatch(n -> !Character.isDigit(n));
    }
}

Sample Output:

Input text with only digits: 
45566336754493420932877387482372374982374823749823283974232237238472392309230923849023848234580383485342234287943943094234745374657346578465783467843653748654376837463847654382382938793287492326

Input text with other characters: 
45566336754493420932877387482372374982374823749823283974232237238472392309230923849023848234580383485342234287943943094234745374657346578465783467843653748654376837463847654382382938793287492326A

Character.isDigit() solution:
Execution time: 1279465 ns (1 ms)
Contains only digits: true
Contains only digits: false

String.matches() solution:
Execution time: 2059497 ns (2 ms)
Contains only digits: true
Contains only digits: false

Java 8, functional-style solution:
Execution time: 114091339 ns (114 ms)
Contains only digits: true
Contains only digits: false

Flowchart:

Flowchart: Java String Exercises - Test if a given string contains only digits
Flowchart: Java String Exercises - Test if a given string contains only digits

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to check if a given string contains another string. Return true or false.
Next: Write a Java program to convert a given String to int, long, float and double.

What is the difficulty level of this exercise?



Java: Tips of the Day

Count the number of occurrences of a char in a String:

int count = StringUtils.countMatches("a.b.c.d", ".");

Ref: https://bit.ly/2OTy6sG