Java constants for common ASCII characters

224 views Asked by At

Is there a library, in Java, i.e. Apache Commons or similar, where various ASCII character constants are defined to be reused? Or, perhaps somewhere in Java itself?

For example, I'm looking for something like public final static String ASCII_SUB_CHAR = "\u001a"; and similarly for other ASCII control characters, already defined somewhere for reuse.

Rationale is that it's quite unobvious how, and why, for example SUB corresponds to 26 and how that then becomes "\u001a". There are also ranges to those characters (control vs printable, etc.) so they can be arranged based on a need. Sounded like a good candidate to be expressed in some structure akin to Enums, hence the question.

Thank you in advance.

2

There are 2 answers

0
WJS On

Check out KeyEvent. It has something similar to what you want and are used for interpreting keyboard input. But they are declared as ints and they aren't consistently (or intuitively) named. Imo, you would be better off constructing your own and putting them in a library declared as code points.

0
Adrian8115 On

Java itself provides a way to represent ASCII characters as constants using escape sequences like '\u001a' for the ASCII SUB character (hexadecimal value 1A). However, Java doesn't provide a predefined library for constants representing all ASCII characters. You would need to define these constants yourself in your code.

If you want to make your code more readable and maintainable, you can define these constants in a utility class or an interface, like this:

public interface ASCIIConstants {
    char SUB = '\u001a';
    char SOH = '\u0001';
    // Define other ASCII constants here...
}

Then, you can use these constants in your code without having to remember the Unicode escape sequences:

char subChar = ASCIIConstants.SUB;
char sohChar = ASCIIConstants.SOH;

If you need a wide range of ASCII constants, you can generate them programmatically or create a text file with the values and write a script to generate the Java code for the constants. This way, you can ensure accuracy and reduce the chances of errors when defining these constants manually.