Java Check Character is ASCII using Apache Commons Lang
Tags: Apache Commons Apache Commons Lang CharUtils char Character ASCII
In this Java tutorial we learn how to check if a character is an ASCII character using the CharUtils class of Apache Commons Lang library.
How to add Apache Commons Lang 3 library to your Java project
To use the Apache Commons Lang 3 library in the Gradle build project, add the following dependency into the build.gradle file.
implementation 'org.apache.commons:commons-lang3:3.12.0'
To use the Apache Commons Lang 3 library in the Maven build project, add the following dependency into the pom.xml file.
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
To have more information about the Apache Commons Lang 3 library you can visit the library home page at commons.apache.org/proper/commons-lang/
How to check a character is an ASCII character in Java
The Apache Commons Lang library provides the method CharUtils.isAscii() to check whether a given character is an ASCII character or not. You can learn how to use the CharUtils.isAscii() method via the following example code.
CheckIsAsciiChar.java
import org.apache.commons.lang3.CharUtils;
public class CheckIsAsciiChar {
public static void main(String... args) {
boolean result1 = CharUtils.isAscii('a');
boolean result2 = CharUtils.isAscii('A');
boolean result3 = CharUtils.isAscii('7');
boolean result4 = CharUtils.isAscii('-');
boolean result5 = CharUtils.isAscii('\n');
System.out.println("Character 'a' is ASCII result: " + result1);
System.out.println("Character 'A' is ASCII result: " + result2);
System.out.println("Character '7' is ASCII result: " + result3);
System.out.println("Character '-' is ASCII result: " + result4);
System.out.println("Character '\\n' is ASCII result: " + result5);
}
}
Character 'a' is ASCII result: true
Character 'A' is ASCII result: true
Character '7' is ASCII result: true
Character '-' is ASCII result: true
Character '\n' is ASCII result: true
Happy Coding 😊