Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

JAVA 包裝類 Boolean 的使用:字串建構與 toString()

Boolean 類除了接受 true/false 之外,還可以直接傳入字串來建構物件,再用 toString() 把結果以字串形式輸出。本例就示範了這兩個動作。

程式碼

/**
 * Boolean 類使用字串建構,並以 toString() 輸出 true / false。
 */
public class BooleanApps {

    Boolean b1 = new Boolean("true");
    String str1 = b1.toString();

    Boolean b2 = new Boolean("OK");
    String str2 = b2.toString();

    public BooleanApps() {
        System.out.println(str1);
        System.out.println(str2);
    }

    public static void main(String[] args) {
        new BooleanApps();
    }
}

值得注意的行為

  • 字串建構子只認得「true」(忽略大小寫)為真,其他任何字串一律視為假。因此 new Boolean("OK") 得到的是 false,str2 印出的就是 false,這點常讓人誤判。
  • toString() 只會輸出 true 或 false 這兩個字面值,不會保留原本的輸入字串。
  • 靜態的 Boolean.parseBoolean(String) 與 Boolean.valueOf(String) 更適合用於解析設定值;在自動裝箱機制下,也可以直接寫 boolean flag = Boolean.TRUE;。
Copyright © Linux教程網 All Rights Reserved