We can make use of regular expressions to know if a string is numeric or alphanumeric in Java.
Let's take a look at some examples.
public class Example {
public static void main(String[] args) {
String string1 = "23.00"; // Numeric
String string2 = "X01201A"; // Alphanumeric
String string3 = "AXYKZ"; // Alphabetic
System.out.println("String1 is " + (isNumeric(string1) ? "numeric" : "not numeric") + " and " +
(isAlphaNumeric(string1) ? "alphanumeric" : "not alphanumeric"));
System.out.println("String2 is " + (isNumeric(string2) ? "numeric" : "not numeric") + " and " +
(isAlphaNumeric(string2) ? "alphanumeric" : "not alphanumeric"));
System.out.println("String3 is " + (isNumeric(string3) ? "numeric" : "not numeric") + " and " +
(isAlphaNumeric(string3) ? "alphanumeric" : "not alphanumeric"));
}
public static boolean isNumeric(String str) {
return str.matches("-?\\d+(\\.\\d+)?");
}
public static boolean isAlphaNumeric(String str) {
return str.matches("[a-zA-Z0-9]+");
}
}
Output:
Facing issues? Have Questions? Post them here! I am happy to answer!
More Posts related to Java,
- Deep Dive into Java 8 Predicate Interface
- Read and Parse XML file using Java DOM Parser [Java Tutorial]
- Java 8 Predicate Functional Interface isEqual() Method Example
- Convert Multidimensional Array toString In Java
- How to read int value using Scanner Class Java
- Spring Boot AI + LLM + Java Code Example
- Write to a File using Java Stream API
- Implementing Bubble Sort Algorithm using Java Program
- How to Fix XmlBeanDefinitionStoreException in Java SpringBoot ApplicationConfig.xml
- YAML Parser using Java Jackson Library Example
- [Fix] java: integer number too large compilation error
- Convert JSON String to Java GSON Object Example
- Read a file using Java 8 Stream
- Java Spring Boot 3 Web Hello World with Gradle in IntelliJ
- Ways Compare Dates in Java Programming with Examples
- Pretty Print JSON String in Java Console Output
- Java JDBC with Join Queries Example
- How to Check For Updates on Windows 11 (Step-by-Step)
- [Fix] java.net.MalformedURLException: unknown protocol
- How to display date and time in GMT Timezone in Java
- Error: LinkageError occurred while loading main class UnsupportedClassVersionError [Eclipse Java]
- How to convert a String to Java 8 Stream of Char?
- RabbitMQ Queue Listener Java Spring Boot Code Example
- 5+ Fibonacci number Series Java Program Examples [ 0 1 1 2 3 ..]
- Handling NullPointerException with Java Predicate
More Posts:
- Android Emulator] ##KBD: Full queue, lose event Error Logs - Android
- Java: Convert Char to ASCII - Java
- What are E, K, N, S, T, U, V in Java Generics - Java
- Install and Run Cassandra on Docker Desktop - Docker
- [fix] AWS S3 make_bucket failed: An error occurred (InvalidBucketName) when calling the CreateBucket operation. - S3
- Pandas: Reading .xlsx or .xls Excel Files - Python
- Install node on Alpine Linux Docker - Docker
- Convert SQL to CSV in Notepad++ - NotepadPlusPlus