May 10, 2021 Java
When using characters, we typically use built-in data type char.
char ch = 'a';
// Unicode for uppercase Greek omega character
char uniChar = '\u039A';
// 字符数组
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 character class for the built-in data type char.
The Character class provides a series of ways to manipulate characters. You can use Character's construction methods to create a Character class object, for example:
Character ch = new Character('a');
In some cases, the Java compiler automatically creates a Character object.
For example, when you pass an argument of a char type to a Character type parameter that is required, the compiler automatically converts the char type parameter to a Character object. T his feature is called boxing, which in turn is called unboxing.
// Here following primitive char 'a'
// is boxed into the Character object ch
Character ch = 'a';
// Here primitive 'x' is boxed for method test,
// return is unboxed to char 'c'
char c = test('x');
Characters with backslashes in front of them represent escape characters, which have a special meaning for the compiler.
The following list shows the escape sequence for Java:
Escape sequence | Describe |
---|---|
\t | Insert a tab key there |
\b | Insert a back key there |
\n | Line up there in the text |
\r | Insert a carriage return at this place in the text |
\f | Insert a page break there |
\' | Insert single quotes there |
\" | Insert double quotes there |
\\ | Insert a backslash there |
When a print statement encounters an escape sequence, the compiler interprets it correctly.
public class Test {
public static void main(String args[]) {
System.out.println("She said \"Hello!\" to me.");
}
}
The above examples compile and run as follows:
She said "Hello!" to me.
Here's how the Character class is:
Serial number | Method and description |
---|---|
1 |
isLetter()
Whether it is a letter |
2 |
isDigit()
Whether it is a numeric character |
3 |
isWhitespace()
Whether it's a space |
4 |
isUpperCase()
Whether it's capital letters or not |
5 |
isLowerCase()
Whether it's a lowercase letter |
6 |
toUpperCase()
Specifies the capital form of the letter |
7 |
toLowerCase()
Specify the lowercase form of the letter |
8 |
toString()
Returns the string form of the character, which is only 1 in length |
public class Java {
public static void main(String[] args) {
Character ch = new Character('X');
System.out.println(Character.isUpperCase(ch));
//Character.isUpperCase(ch) 用于判断括号里的字母是否为大写
System.out.println(Character.isLowerCase(ch));
//Character.isLowerCase(ch) 用于判断括号里的字母是否为小写
System.out.println(Character.isDigit(ch));
//Character.isDigit(ch) 用于判断括号里的内容是否为数字
}
}
The results are:
true
false
false
For a complete list of methods, refer to the java.lang.Character API specification.