Java布爾包裝類

布爾(Boolean)類的對象包裝一個布爾值。Boolean.TRUEBoolean.FALSE是布爾類型的兩個常量,用於表示布爾值truefalse值。

可以使用構造函數或valueOf()工廠方法創建一個布爾(Boolean)對象。當解析字符串時,該類將處理「true」,忽略所有字符的大小結果均爲true,任何其他字符串爲false

示例

下面的代碼顯示瞭如何使用Boolean類。

public class Main {
    public static void main(String[] args) {
        // Using constructors
        Boolean b1True = new Boolean(true);
        Boolean b2True = new Boolean("true");
        Boolean b3True = new Boolean("tRuE");
        Boolean b4False = new Boolean("false");
        Boolean b5False = new Boolean("how  is this"); // false
        // Using the factory methods
        Boolean b6True = Boolean.valueOf(true);
        Boolean b7True = Boolean.valueOf("true");
        Boolean b8True = Boolean.valueOf("tRuE");
        Boolean b9False = Boolean.valueOf("false");
        Boolean b10False = Boolean.valueOf("how is this"); // false

        // Getting a boolean value from a Boolean object
        boolean bbTrue = b8True.booleanValue();

        boolean bTrue = Boolean.parseBoolean("true");
        boolean bFalse = Boolean.parseBoolean("This string evaluates to false");

        Boolean bcTrue = Boolean.TRUE;
        Boolean bcFalse = Boolean.FALSE;

        System.out.println("bcTrue = " + bcTrue);
        System.out.println("bcFalse = " + bcFalse);
    }
}

執行上面的代碼,得到如下結果 -

bcTrue = true
bcFalse = false