0

I have to read a String from a field and then convert it to a Boolean.
I've tried this:

ObjectInputStream nm;
nm = new ObjectInputStream(new FileInputStream("buscamines.txt"));
String s = nm.readLine();
Boolean bool = Boolean.valueOf(s);

But it's not working, when I print the string s, it is correct but the Boolean value is always false.

Is there any other way to convert a String to Boolean?

1
  • 1
    You wrote in your question: when I print the String s, it is correct Perhaps s contains leading (or trailing) spaces? Perhaps it contains non-printing characters? I presume that the value of s is true. I suggest you print the length of s and see whether it is 4. Commented Jun 6, 2020 at 18:01

1 Answer 1

3

According to Java's Boolean documentation:

public static Boolean valueOf(String s)
Returns a Boolean with a value represented by the specified string. The Boolean returned represents a true value if the string argument is not null and is equal, ignoring case, to the string "true".

So, it means that:

System.out.print(Boolean.valueOf("true")); // -> true
System.out.print(Boolean.valueOf("TRUE")); // -> true
System.out.print(Boolean.valueOf("tRuE")); // -> true
System.out.print(Boolean.valueOf("false")); // -> false
System.out.print(Boolean.valueOf("anything else")); // -> false
System.out.print(Boolean.valueOf("TRUE ")); // -> false
Sign up to request clarification or add additional context in comments.

2 Comments

What Boolean value is obtained for the string "TRUE " (i.e. with a trailing space) ?
@Abra System.out.print(Boolean.valueOf("TRUE ")); will return false.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.