Convert string value to boolean
In this chapter you will learn:
Convert string to boolean
The following methods do the conversion from string to boolean value.
static boolean parseBoolean(String s)
parses the string argument as a boolean.static Boolean valueOf(boolean b)
returns a Boolean instance representing the specified boolean value.static Boolean valueOf(String s)
returns a Boolean with a value represented by the specified string.
public class Main {
/*j ava 2 s. c o m*/
public static void main(String[] args) {
System.out.println(Boolean.parseBoolean("true"));
System.out.println(Boolean.valueOf("true"));
}
}
The output:
Converts a String to a Boolean
'true'
, 'on'
or 'yes'
(case insensitive) will return true
.
'false'
, 'off'
or 'no'
(case insensitive) will return false
.
Otherwise, null
is returned.
public class Main {
public static void main(String[] argv) {
/* j a va 2s.c om*/
System.out.println(toBooleanObject(null));
System.out.println(toBooleanObject("true"));
System.out.println(toBooleanObject("false"));
System.out.println(toBooleanObject("on"));
System.out.println(toBooleanObject("ON"));
System.out.println(toBooleanObject("off"));
System.out.println(toBooleanObject("oFf"));
System.out.println(toBooleanObject("blue"));
}
public static Boolean toBooleanObject(String str) {
if ("true".equalsIgnoreCase(str)) {
return Boolean.TRUE;
} else if ("false".equalsIgnoreCase(str)) {
return Boolean.FALSE;
} else if ("on".equalsIgnoreCase(str)) {
return Boolean.TRUE;
} else if ("off".equalsIgnoreCase(str)) {
return Boolean.FALSE;
} else if ("yes".equalsIgnoreCase(str)) {
return Boolean.TRUE;
} else if ("no".equalsIgnoreCase(str)) {
return Boolean.FALSE;
}
return null;
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » Primitive Data Types