The Character class is used to operate on a single character.
The Character class wraps the value of a primitive type char in an object
Examples
char ch = ' a ' ;
// Unicode character representation
char uniChar = ' \u 039A ' ;
// array of characters
char [ ] charArray = { ' a ' , ' b ' , ' c ' , ' d ' , ' e ' } ;
However, in the actual development process, we often encounter the need to use the object, rather than the built-in data type. To solve this problem, the Java language provides a wrapper class Character for the built-in data type char.
The Character class provides a series of methods for manipulating characters. You can use the Character constructor to create a Character object, for example:
Character ch = new Character ( ' a ' ) ;
In some cases, the Java compiler automatically creates a Character object.
For example, when you pass a parameter of char type to a method that requires a Character type parameter, the compiler automatically converts the char type parameter to a Character object. This feature is called packing, which in turn is called unboxing.
Examples
//The original character 'a' is boxed into the Character object ch
Character ch = ' a ' ;
// original character 'x' boxed with test method
// Return unboxing values to 'c'
char c = test ( ' x ' ) ;
Escape sequence
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 here in the text |
\b | Insert a back key here in the text |
\n | Wrap this place in the text |
\r | Insert a carriage return here |
\f | Insert a page break here in the text |
\' | Insert single quotes there |
\" | Insert double quotes in the text |
\\ | Insert a backslash there |
Examples
When the 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 the Test {
public static void main ( String args [ ] ) {
System.out.println( " Visit \" Rookies Tutorial! \ " " ) ;
}
}
The above example compiled and run results are as follows:
Visit "Rookies Tutorial!"
Character method
Here is the method of the Character class:
No. | Method and description |
---|---|
1 | IsLetter() is a letter |
2 | IsDigit() is a numeric character |
3 | isWhitespace() is a space |
4 | IsUpperCase() is an uppercase letter |
5 | IsLowerCase() is a lowercase letter |
6 | toUpperCase() Specifies the capitalization of letters |
7 | toLowerCase () Specifies the lowercase of the letter |
8 | toString () returns the character string, the length of the string is only 1 |
For a complete list of methods, please refer to the java.lang.Character API specification.
Comments
Post a Comment