通常情况下,我们使用字符时,有时需要使用原始数据类型的字符。
char ch = 'a'; // Unicode for uppercase Greek omega character char uniChar = '\u039A'; // an array of chars char[] charArray ={ 'a', 'b', 'c', 'd', 'e' };
然而在开发中,我们遇到的情况,我们需要使用的对象,而不是原始数据类型。为了实现这个Java提供包装CLASSE字符为基本数据类型char。
Character类提供了一些有用的类(即静态)方法操作字符。可以创建一个字符的字符构造的对象:
Character ch = new Character('a');
Java编译器会创建一个Character对象,在某些情况下。例如,如果传递一个对象的方法,预计到原始字符,编译器会自动转换成字符一个字符。此功能称为自动装箱,拆箱,如果转换“的另一种方式。
// 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');
A character preceded by a backslash (\) is an escape sequence and has special meaning to the compiler.
The newline character (\n) has been used frequently in this tutorial in System.out.println() statements to advance to the next line after the string is printed.
Following table shows the Java escape sequences:
Escape Sequence | Description |
---|---|
\t | Insert a tab in the text at this point. |
\b | Insert a backspace in the text at this point. |
\n | Insert a newline in the text at this point. |
\r | Insert a carriage return in the text at this point. |
\f | Insert a form feed in the text at this point. |
\' | Insert a single quote character in the text at this point. |
\" | Insert a double quote character in the text at this point. |
\\ | Insert a backslash character in the text at this point. |
When an escape sequence is encountered in a print statement, the compiler interprets it accordingly.
如果要加上引号,引号内的,则必须使用转义序列\“,内部引号:
public class Test{ public static void main(String args[]){ System.out.println("She said \"Hello!\" to me."); } }
这将产生以下结果:
She said "Hello!" to me.
下面是列表中的重要Character类的所有子类的实例方法实施:
SN | Methods with 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 valuethat is, a one-character string. |
方法的完整列表,请参阅的java.lang.Character API规范。
在下一节中,我们将通过在Java中的String类。将在String类中学习如何声明和有效地使用字符串以及一些重要的方法。