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.example.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
Wayan Saryada
Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. If these posts help, you can support me, buy me a cup of coffee or tea. Thank you 🥳
Latest posts by Wayan Saryada (see all)
- How do I set the time of java.util.Date instance to 00:00:00? - October 24, 2019
- How to Install Consolas Font in Mac OS X? - March 29, 2019
- How do I clear the current command line in terminal? - February 14, 2019