Java 字符串转换为Boolean值

可以通过Boolean.valueof来实现字符串到boolean值的转换:
只有字符串为true 且忽略大小写比如:True/TRue/TRUE等返回布尔值true,其他都返回false。

Boolean b1 = Boolean.valueOf("true");
System.out.println(b1);// true
Boolean hh = Boolean.valueOf("hh");
System.out.println(hh);// false
Boolean aFalse = Boolean.valueOf("false");
System.out.println(aFalse);//false
Boolean aTrue = Boolean.valueOf("True");
System.out.println(aTrue);//true
Boolean aBoolean = Boolean.valueOf(null);
System.out.println(aBoolean);// false

我们可以看一下源码:
发现它其实是判断是否可以转换为Boolean类型,是的话,就返回true,否则返回false。


    /**
     * Returns a {@code Boolean} with a value represented by the
     * specified string.  The {@code Boolean} returned represents a
     * true value if the string argument is not {@code null}
     * and is equal, ignoring case, to the string {@code "true"}.
     *
     * @param   s   a string.
     * @return  the {@code Boolean} value represented by the string.
     */
    public static Boolean valueOf(String s) {
        return parseBoolean(s) ? TRUE : FALSE;
    }

接着,我们查看parseBoolean()的源码。
我们发现只要传入的字符串不为null且忽略大小写与字符串值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"}. <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 ((s != null) && s.equalsIgnoreCase("true"));
    }
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值