In Java, you can convert a String to a boolean using the Boolean.parseBoolean(String) method or by using Boolean.valueOf(String). Here’s how you can do it:
1. Boolean.parseBoolean(String):
String str = "true";
boolean boolValue = Boolean.parseBoolean(str);
System.out.println(boolValue); // Output: true
str = "True";
boolValue = Boolean.parseBoolean(str);
System.out.println(boolValue); // Output: true
str = "false";
boolValue = Boolean.parseBoolean(str);
System.out.println(boolValue); // Output: false
str = "anything else";
boolValue = Boolean.parseBoolean(str);
System.out.println(boolValue); // Output: false
Explanation: The parseBoolean method will return true if the string is “true” (ignoring case), and false for any other value, including null.
Important Points:
1. ignore case sensitive, so “TRUE”, “true” will be true and “False”, “FALSE” will be false.
2. if the string is anything other than “true”, including null or empty strings will be false.
2. Using Boolean.valueOf(String)
The valueOf method also returns a Boolean object. If the string is “true” (ignoring case), it returns Boolean.TRUE; otherwise, it returns Boolean.FALSE.
String str = "true";
boolean boolValue = Boolean.valueOf(str);
System.out.println(boolValue); // Output: true
str = "false";
boolValue = Boolean.valueOf(str);
System.out.println(boolValue); // Output: false
str = "anything else";
boolValue = Boolean.valueOf(str);
System.out.println(boolValue); // Output: false
Note: –
- If you’re working with primitive boolean, use Boolean.parseBoolean().
- If you need a Boolean object, use Boolean.valueOf().
3. Using equalsIgnoreCase() method
If you want to manually parse the string and handle cases differently, you can check the string directly with equals() to decide how to convert it.
String str = "true";
boolean boolValue = str != null && str.equalsIgnoreCase("true");
System.out.println(boolValue); // Output: true
str = "FALSE";
boolValue = str != null && str.equalsIgnoreCase("true");
System.out.println(boolValue); // Output: false
Explanation:
This method checks if the string equals “true”, ignoring case. It returns true only if the string matches “true”, otherwise, it returns false.
4. Using Objects.equals() method
In some cases, using Objects.equals() might be useful if you want to handle null safely, especially in cases where you expect the string to be nullable:
import java.util.Objects;
String str = "true";
boolean boolValue = Objects.equals(str, "true");
System.out.println(boolValue); // Output: true
str = "FALSE";
boolValue = Objects.equals(str, "true");
System.out.println(boolValue); // Output: false
Explanation: Objects.equals() is a null-safe method to check if the string matches “true”. If str is null, it will return false without throwing a NullPointerException.