StringUtils isAsciiPrintable () example in Java

In this post, we will see org.apache.commons.lang3.StringUtils isAsciiPrintable () example in Java. The isAsciiPrintable () method is used to check given character is an alphabet or not. It returns true if the given character is alphabet else returns false.

import org.apache.commons.lang3.StringUtils;

public class StringUtilsExample {
    public static void main(String[] args) {
        String str1 = "Hello, world!";
        String str2 = "Hello,\nworld!";
        
        boolean isAsciiPrintable1 = StringUtils.isAsciiPrintable(str1);
        boolean isAsciiPrintable2 = StringUtils.isAsciiPrintable(str2);
        
        System.out.println(str1 + " isAsciiPrintable? " + isAsciiPrintable1);
        System.out.println(str2 + " isAsciiPrintable? " + isAsciiPrintable2);
    }
}

The output of above example is

Hello, world! isAsciiPrintable? true
Hello, world! isAsciiPrintable? false

As expected, str1 is determined to be printable, while str2 is not, due to the presence of the newline character.

In the above example, we import the StringUtils class from the Apache Commons Lang library, which provides a number of useful methods for working with strings.

We then define two strings, str1 and str2. str1 contains only printable ASCII characters, while str2 contains a newline character (\n) which is not printable.

We then use the StringUtils.isAsciiPrintable() method to determine whether each string contains only printable ASCII characters. We store the result in the isAsciiPrintable1 and isAsciiPrintable2 boolean variables, respectively.

How to check if ASCII is printable or not in Java?

We can use StringUtils isAsciiPrintable() method.

Note – We need to add the below dependency in pom.xml to use org.apache.commons.lang3.StringUtils isAsciiPrintable () method. We can download apache-commons maven dependency from here.

pom.xml changes

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.10</version>
</dependency>

Another example of StringUtils isAsciiPrintable () in Java

package com.javatute;

import org.apache.commons.lang3.StringUtils;

public class StringUtilsIsAsciiPrintable {
    public static void main(String[] args) {
        System.out.println(StringUtils.isAsciiPrintable(null));//false
        System.out.println(StringUtils.isAsciiPrintable("@"));//true
        System.out.println(StringUtils.isAsciiPrintable("21"));//true
        System.out.println(StringUtils.isAsciiPrintable("jbl"));//true
        System.out.println(StringUtils.isAsciiPrintable(" "));//true
        System.out.println(StringUtils.isAsciiPrintable("java"));//true

    }
}

Output is

false
true
true
true
true
true

That’s all about StringUtils isAsciiPrintable() example in Java.

See docs.

Related post.