0
0
JavaHow-ToBeginner · 2 min read

Java How to Convert String to Boolean - Simple Guide

In Java, convert a string to boolean using Boolean.parseBoolean(yourString), which returns true if the string equals "true" ignoring case, otherwise false.
📋

Examples

Input"true"
Outputtrue
Input"False"
Outputfalse
Input"hello"
Outputfalse
🧠

How to Think About It

To convert a string to a boolean, check if the string exactly matches "true" ignoring case. If yes, return true; otherwise, return false. This approach treats any other string as false.
📐

Algorithm

1
Get the input string.
2
Compare the string to "true" ignoring case.
3
If it matches, return true.
4
Otherwise, return false.
💻

Code

java
public class StringToBoolean {
    public static void main(String[] args) {
        String input = "True";
        boolean result = Boolean.parseBoolean(input);
        System.out.println(result);
    }
}
Output
true
🔍

Dry Run

Let's trace converting the string "True" to boolean.

1

Input string

input = "True"

2

Parse string to boolean

Boolean.parseBoolean("True") returns true

3

Print result

Output: true

Input StringBoolean.parseBoolean Result
Truetrue
💡

Why This Works

Step 1: Parsing logic

The Boolean.parseBoolean() method checks if the input string equals "true" ignoring case.

Step 2: Return value

If the string matches "true", it returns true; otherwise, it returns false.

🔄

Alternative Approaches

Using Boolean.valueOf()
java
public class StringToBoolean {
    public static void main(String[] args) {
        String input = "true";
        Boolean result = Boolean.valueOf(input);
        System.out.println(result);
    }
}
Returns a Boolean object instead of primitive boolean; useful if you need an object.
Manual comparison
java
public class StringToBoolean {
    public static void main(String[] args) {
        String input = "true";
        boolean result = "true".equalsIgnoreCase(input);
        System.out.println(result);
    }
}
Manually compares string ignoring case; same result but more explicit.

Complexity: O(n) time, O(1) space

Time Complexity

The method compares the input string to "true" ignoring case, which takes O(n) time where n is the string length.

Space Complexity

No extra space is used besides a few variables, so space complexity is O(1).

Which Approach is Fastest?

Boolean.parseBoolean() and manual comparison have similar performance; Boolean.valueOf() adds object creation overhead.

ApproachTimeSpaceBest For
Boolean.parseBoolean()O(n)O(1)Simple primitive boolean conversion
Boolean.valueOf()O(n)O(1)When Boolean object needed
Manual equalsIgnoreCaseO(n)O(1)Explicit control over comparison
💡
Use Boolean.parseBoolean() for a simple and safe string to boolean conversion.
⚠️
Assuming any non-"true" string returns true; actually, only "true" (case-insensitive) returns true.