This article explains how to find strings containing only numbers in an array efficiently using Java. When preparing for Java interviews, logical problem-solving skills play a crucial role.
Problem statement:
Write a Java program that identifies strings in an array that consist only of numeric characters (digits 0-9).
Approach to Solve the Problem
We will break the solution into three simple steps:
- Use Java’s built-in
matches()
method with a regular expression\d+
. This ensures that the string contains only digits. - Loop through each word in the array and check if it is numeric using the above method.
- Store valid numeric strings in a list and print the final result.
Java program to check if a string contains only digits
This Java program identifies strings in an array that consist only of numeric characters (digits).
package com.javacodepoint.stringarray;
import java.util.ArrayList;
import java.util.List;
public class NumericStrings {
// Method to check if a string contains only numeric characters
public static boolean isNumeric(String str) {
return str.matches("\\d+"); // Regular expression to check if the string contains only digits
}
// Method to identify numeric strings in an array
public static List<String> findNumericStrings(String[] words) {
List<String> numericStrings = new ArrayList<>();
for (String word : words) {
if (isNumeric(word)) {
numericStrings.add(word);
}
}
return numericStrings;
}
public static void main(String[] args) {
// Example array of strings
String[] words = { "123", "hello", "4567", "world", "8901", "java123" };
// Find and print numeric strings
List<String> numericStrings = findNumericStrings(words);
System.out.println("Numeric strings: " + numericStrings);
}
}
OUTPUT:
Numeric strings: [123, 4567, 8901]
Conclusion
This approach efficiently filters numeric strings from an array using regex. Understanding such logical problems will strengthen your Java skills for coding interviews.
You can learn the Top 20 string array programs for interview preparation (Click here).