通常,在处理字符时,我们使用基本数据类型char。
Example
char ch = 'a'; // Unicode for uppercase Greek omega character char uniChar = '\u039A'; // an array of chars char[] charArray ={ 'a', 'b', 'c', 'd', 'e' };
然而,在开发过程中,我们遇到了需要使用对象而不是原始数据类型的情况。为了实现这一点,Java为原始数据类型char提供了包装器类字符。
Character类提供了许多有用的类(即静态)方法来操作字符。可以使用角色构造函数创建角色对象−
字符ch=新字符(“a”);
在某些情况下,Java编译器还会为您创建一个Character对象。例如,如果将基元字符传递给需要对象的方法,编译器会自动将该字符转换为字符。如果转换方向相反,则此功能称为自动装箱或取消装箱。
Example
// 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');
转义序列
前跟反斜杠(\)的字符是转义序列,对编译器有特殊意义。
换行符(\n)在系统中的本教程中经常使用。出来println()语句,以在打印字符串后前进到下一行。
下表显示了Java转义序列−
转义序列 | 描述 |
---|---|
\t | Inserts a tab in the text at this point. |
\b | Inserts a backspace in the text at this point. |
\n | Inserts a newline in the text at this point. |
\r | Inserts a carriage return in the text at this point. |
\f | Inserts a form feed in the text at this point. |
\' | Inserts a single quote character in the text at this point. |
\" | Inserts a double quote character in the text at this point. |
\\ | Inserts a backslash character in the text at this point. |
当在print语句中遇到转义序列时,编译器会相应地对其进行解释。
Example
如果要在引号中加引号,则必须在内部引号中使用转义序列“\”−
public class Test { public static void main(String args[]) { System.out.println("She said \"Hello!\" to me."); } }
这将产生以下结果−
Output
She said "Hello!" to me.
Character Methods
下面是Character类的所有子类实现的重要实例方法列表−
Sr.No. | Method & Description |
---|---|
1 | isLetter() Determines whether the specified char value is a letter. |
2 | isDigit() Determines whether the specified char value is a digit. |
3 | isWhitespace() Determines whether the specified char value is white space. |
4 | isUpperCase() Determines whether the specified char value is uppercase. |
5 | isLowerCase() Determines whether the specified char value is lowercase. |
6 | toUpperCase() Returns the uppercase form of the specified char value. |
7 | toLowerCase() Returns the lowercase form of the specified char value. |
8 | toString() Returns a String object representing the specified character value that is, a one-character string. |
有关方法的完整列表,请参考java。lang.字符API规范。