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