In Java, converting a String to a boolean is a common operation, especially when dealing with user inputs, configuration files, or API responses. Java provides straightforward methods to achieve this conversion efficiently. This article explores different java convert string to boolean.
1. Using Boolean.parseBoolean()
Example:
java
Copy
Edit
public class StringToBooleanExample {
public static void main(String[] args) {
String str1 = "true";
String str2 = "False";
String str3 = "hello";
boolean bool1 = Boolean.parseBoolean(str1);
boolean bool2 = Boolean.parseBoolean(str2);
boolean bool3 = Boolean.parseBoolean(str3);
System.out.println(bool1); // true
System.out.println(bool2); // false
System.out.println(bool3); // false
}
}
Explanation:
"true" (case-insensitive) converts to true.
Any other string (including "False", "hello", or an empty string) converts to false.
2. Using Boolean.valueOf()
Boolean.valueOf() works similarly to Boolean.parseBoolean(), but it returns a Boolean object instead of a primitive boolean.
Example:
java
Copy
Edit
public class StringToBooleanExample2 {
public static void main(String[] args) {
String str = "True";
Boolean boolObj = Boolean.valueOf(str);
System.out.println(boolObj); // true
}
}
This method is useful when working with Boolean objects instead of primitive boolean values.
3. Using Custom Logic (Manual Check)
For stricter control over string values, you can manually check if the string equals "true", ignoring case.
Example:
java
Copy
Edit
public class StringToBooleanManual {
public static void main(String[] args) {
String input = "YES";
boolean result = input.equalsIgnoreCase("true") || input.equalsIgnoreCase("yes");
System.out.println(result); // true
}
}
Here, we extend the logic to accept "yes" as true, which is useful in cases where additional keywords should be considered.
4. Handling Null and Empty Strings
Since Boolean.parseBoolean(null) returns false, it’s essential to handle null and empty strings explicitly when necessary.
Example:
java
Copy
Edit
public class StringToBooleanNullCheck {
public static boolean convertToBoolean(String str) {
if (str == null || str.trim().isEmpty()) {
return false;
}
return Boolean.parseBoolean(str);
}
public static void main(String[] args) {
System.out.println(convertToBoolean(null)); // false
System.out.println(convertToBoolean("")); // false
System.out.println(convertToBoolean("true")); // true
}
}
Conclusion
Java provides built-in methods like Boolean.parseBoolean() and Boolean.valueOf() to convert a String to a boolean. However, for better control, a custom approach can be used, especially when dealing with variations like "yes", "no", or null values. Always ensure proper handling of edge cases to avoid unintended results.