Boolean類的概念和使用


Boolean類的概述

(1)基本概念

  java.lang.Boolean類型內部包裝了一個boolean類型的變量作為成員變量,主要用於實現對
boolean類型的包裝並提供boolean類型到String類之間的轉換等方法。

(2)常用的常量

 

 (3)常用的方法

 

 

package com.lagou.task11;

public class BooleanTest {
    public static void main(String[] args) {
        //  1.在java5之前采用方法進行裝箱和拆箱
        //  裝箱
        //  相當於從boolean類型到Boolean類型的轉換
        Boolean bo1 = Boolean.valueOf(true);
        //  拆箱
        boolean bo2 = bo1.booleanValue();
        System.out.println("裝箱:" + bo1);
        System.out.println("拆箱:" + bo2);

        System.out.println("----------------------------------------");
        //  2.從java5開始支持自動裝箱和自動拆箱
        Boolean bo3 = true;
        boolean bo4 = bo3;
        System.out.println("自動裝箱:"+bo3);
        System.out.println("自動拆箱:"+bo4);

        System.out.println("----------------------------------------");
        //  3.實現從String類型到boolean類型的轉換
        boolean bo5 = Boolean.parseBoolean("true1");    //  false
        System.out.println(bo5);
    }
}

為什么轉換字符串的時候,不是輸入true1是false?

  因為在源碼中parseBoolean方法使用形參和字符串true對比(不區分大小寫),只要不是true一律返回false。

源碼:  
/** * Parses the string argument as a boolean. The {@code boolean} * returned represents the value {@code true} if the string argument * is not {@code null} and is equal, ignoring case, to the string * {@code "true"}. * Otherwise, a false value is returned, including for a null * argument.<p> * Example: {@code Boolean.parseBoolean("True")} returns {@code true}.<br> * Example: {@code Boolean.parseBoolean("yes")} returns {@code false}. * * @param s the {@code String} containing the boolean * representation to be parsed * @return the boolean represented by the string argument * @since 1.5 */ public static boolean parseBoolean(String s) { return "true".equalsIgnoreCase(s); }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM