w3resource

Java: Check if a given string contains only digits

Java String: Exercise-101 with Solution

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

Visual Presentation:

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

Sample Solution-1:

Java Code:

// Define a class named Main
public class Main {
    
    // The main method, entry point of the program
    public static void main(String[] args) {
        // Define two digit strings
        String digit_string1 = "131231231231231231231231231212312312";
        String digit_string2 = "13123123123Z1231231231231231212312312";

        // Display the first string
        System.out.println("First string:");
        System.out.println(digit_string1);
        // Check if the first string contains only digits
        boolean result1 = test_only_digits(digit_string1);
        System.out.println(result1);

        // Display the second string
        System.out.println("\nSecond string:");
        System.out.println(digit_string2);
        // Check if the second string contains only digits
        boolean result2 = test_only_digits(digit_string2);
        System.out.println(result2);
    }

    // Method to check if a string contains only digits
    public static boolean test_only_digits(String digit_string) {
        // Iterate through each character of the string
        for (int i = 0; i < digit_string.length(); i++) {
            // Check if the character is not a digit
            if (!Character.isDigit(digit_string.charAt(i))) {
                return false;
            }
        }
        // If all characters are digits, return true
        return true;
    }
}

Sample Output:

First string:
131231231231231231231231231212312312
true

Second string:
13123123123Z1231231231231231212312312
false

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?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/java-exercises/string/java-string-exercise-101.php