Java Character Class

The Character class is used to operate on individual characters.

The Character class wraps a primitive type in an objectcharvalue

Example

char ch = 'a'; //Unicode Character Representation char uniChar = '\u039A'; //Character Array char[] charArray ={ 'a', 'b', 'c', 'd', 'e' };

However, in the actual development process, we often encounter situations where we need to use objects rather than built-in data types. To solve this problem, the Java language provides a wrapper class, the Character class, for the built-in data type char.

The Character class provides a series of methods to manipulate characters. You can use the Character constructor to create a Character class object, for example:

Character ch = new Character('a');

In certain cases, the Java compiler will automatically create a Character object.

For example, when passing a char type parameter to a method that requires a Character type parameter, the compiler will automatically convert the char type parameter into a Character object. This feature is called boxing, and the reverse is called unboxing.

Example

//The primitive character 'a' is boxed into the Character object ch Character ch = 'a'; //The primitive character 'x' is boxed using the test method //The unboxed value is returned to 'c' char c = test('x');

Escape Sequences

Characters preceded by a backslash (\) represent escape characters, which have special meaning to the compiler.

The following list shows Java's escape sequences:

Escape Sequence Description
\t Insert a tab key at that point in the text
\b Insert a backspace key at that point in the text
\n Insert a newline at that point in the text
\r Insert a carriage return at that point in the text
\f Insert a form feed at that point in the text
\' Insert a single quote at that point in the text
\" Insert a double quote at that point in the text
\\ Insert a backslash at that point in the text

Example

When a print statement encounters an escape sequence, the compiler can interpret it correctly.

The following example escapes double quotes and outputs:

Test.java file code:

public class Test { public static void main(String[] args) { System.out.println("Visit\"Example!\""); } }

The compilation and execution result of the above example is as follows:

Visit "Example Tutorial!"

Character Methods

The following are the methods of the Character class:

No. Method and Description
1 isLetter()
Whether it is a letter
2 isDigit()
Whether it is a digit character
3 isWhitespace()
Whether it is a whitespace character
4 isUpperCase()
Whether it is an uppercase letter
5 isLowerCase()
Whether it is a lowercase letter
6 toUpperCase()
The uppercase form of the specified letter
7 toLowerCase()
The lowercase form of the specified letter
8 toString()
Returns the string form of the character, and the length of the string is only 1

For the complete list of methods, please refer to thejava.lang.Character APIspecification.

Other Extensions