• 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); }
  • 相关阅读:
    PAT(A) 1095. Cars on Campus (30)
    PAT(A) 1080. Graduate Admission (30)
    PAT(A) 1083. List Grades (25)
    Linux 使用create_ap开热点后无法连接wifi问题的解决
    汽车加油行驶问题(最短路)
    孤岛营救问题(最短路 状态压缩)  网络流24题
    软件补丁问题(状态压缩 最短路)
    餐巾计划问题(费用流)
    分配问题(二部图的最佳匹配 KM) 线性规划与网络流24题
    数字梯形问题(费用流)
  • 原文地址:https://www.cnblogs.com/xujiaqi/p/13817862.html
Copyright © 2020-2023  润新知