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.
java valueof* @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"));
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。