Java字符數據類型

Character類的一種對象包裝一個char值的包裝類。Character類包含isLetter()isDigit()方法來檢查字符是否爲字母或數字。

toUpperCase()toLowerCase()方法將字符轉換爲大寫和小寫。該類提供了一個構造函數和一個工廠valueOf()方法來從char類型值創建對象。charValue()方法返回對象包裝的char類型值。

示例

以下代碼顯示瞭如何創建Character對象以及如何使用它的一些方法:

public class Main {
  public static void main(String[] args) {
    // Using the constructor
    Character c1 = new Character('A');

    // Using the factory method - preferred
    Character c2 = Character.valueOf('2');
    Character c3 = Character.valueOf('-');

    // Getting the wrapped char values
    char cc1 = c1.charValue();
    char cc2 = c2.charValue();
    char cc3 = c3.charValue();

    System.out.println("c1 = " + c1);
    System.out.println("c2 = " + c2);
    System.out.println("c3 = " + c3);

    // Using some Character class methods on c1
    System.out.println("isLowerCase c1    = " + Character.isLowerCase(cc1));
    System.out.println("isDigit c1    = " + Character.isDigit(cc1));
    System.out.println("isLetter c1    = " + Character.isLetter(cc1));
    System.out.println("Lowercase of  c1    = " + Character.toLowerCase(cc1));

    // Using some Character class methods on c2
    System.out.println("isLowerCase c2    = " + Character.isLowerCase(cc2));
    System.out.println("isDigit c2    = " + Character.isDigit(cc2));
    System.out.println("isLetter c2    = " + Character.isLetter(cc2));
    System.out.println("Lowercase of  c2    = " + Character.toLowerCase(cc2));

    System.out.println("Uppercase of  c3    = " + Character.toUpperCase(cc3));

  }
}

上面的代碼生成以下結果。

c1 = A
c2 = 2
c3 = -
isLowerCase c1    = false
isDigit c1    = false
isLetter c1    = true
Lowercase of  c1    = a
isLowerCase c2    = false
isDigit c2    = true
isLetter c2    = false
Lowercase of  c2    = 2
Uppercase of  c3    = -