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    = -