To check if a string is alphanumeric in Java, you can use the matches method of the String class, along with a regular expression that matches alphanumeric characters.
Here is an example of how to check if a string is alphanumeric:
r:ot refelautturi.compublic class Main {
public static void main(String[] args) {
String str = "abc123";
boolean isAlphanumeric = str.matches("^[a-zA-Z0-9]*$");
System.out.println(isAlphanumeric); // Outputs: true
}
}
In this example, the matches method is used to check if the str string contains only alphanumeric characters. The regular expression "^[a-zA-Z0-9]*$" matches any combination of lowercase and uppercase letters and digits, and the ^ and $ characters anchor the match to the start and end of the string, respectively.
If the str string contains any non-alphanumeric characters, the matches method will return false. For example:
String str = "abc123!";
boolean isAlphanumeric = str.matches("^[a-zA-Z0-9]*$");
System.out.println(isAlphanumeric); // Outputs: false
You can use a similar approach to check if a string is alphabetic (contains only letters) or numeric (contains only digits). For example, to check if a string is alphabetic:
String str = "abcdefg";
boolean isAlphabetic = str.matches("^[a-zA-Z]*$");
System.out.println(isAlphabetic); // Outputs: true
And to check if a string is numeric:
String str = "12345";
boolean isNumeric = str.matches("^[0-9]*$");
System.out.println(isNumeric); // Outputs: true