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); }

 

posted @ 2020-10-14 22:39  IJLog  阅读(1424)  评论(0编辑  收藏  举报