當前位置:首頁 » Java教學 » Java Character類

Java Character類

Java Character類使用代碼實例 - 通常情況下,我們使用字符時,有時需要使用原始數據類型的字符。

通常情況下,我們使用字符時,有時需要使用原始數據類型的字符。

例子:

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方法:

下麵是列表中的重要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類中學習如何聲明和有效地使用字符串以及一些重要的方法。