To convert a string into boolean
we can use the Boolean.parseBoolean(String)
method. If we pass a non null
value that equals to true
, ignoring case, this method will return true
value. Given other values it will return a false
boolean value.
package org.kodejava.lang;
public class BooleanParseExample {
public static void main(String[] args) {
// Parsing string "true" will result boolean true
boolean boolA = Boolean.parseBoolean("true");
System.out.println("boolA = " + boolA);
// Parsing string "TRUE" also result boolean true, as the
// parsing method is case insensitive
boolean boolB = Boolean.parseBoolean("TRUE");
System.out.println("boolB = " + boolB);
// The operation below will return false, as Yes is not
// a valid string value for boolean expression
boolean boolC = Boolean.parseBoolean("Yes");
System.out.println("boolC = " + boolC);
// Parsing a number is also not a valid expression so the
// parsing method return false
boolean boolD = Boolean.parseBoolean("1");
System.out.println("boolD = " + boolD);
}
}
The code snippet above will print the following output:
boolA = true
boolB = true
boolC = false
boolD = false
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024