Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if String value is Boolean type in Java?

I did a little search on this but couldn't find anything useful.

The point being that if String value is either "true" or "false" the return value should be true. In every other value it should be false.

I tried these:

String value = "false"; System.out.println("test1: " + Boolean.parseBoolean(value)); System.out.println("test2: " + Boolean.valueOf(value)); System.out.println("test3: " + Boolean.getBoolean(value)); 

All functions returned false :(

like image 546
Ragnar Avatar asked Nov 19 '09 12:11

Ragnar


People also ask

Can you use == for boolean in Java?

Java boolean operators are denoted by |, ||, &, &&, <, >, <=, >=, ^, != , ==. These logical boolean operators help in specifying the condition that will have the two return values – “true” or “false”.

Is a boolean a string?

A string is a type of variable that represents a series of characters (i.e. text.) A boolean is a type of variable that represents one of two possible values, either true of false.

How do you compare boolean and string?

Using the Strict Equality Operator (===) In this method, we will use the strict equality operator to compare strings to Boolean. The strict equality always returns false when we compare string and boolean values as it also checks for the data type of both operands.


2 Answers

  • parseBoolean(String) returns true if the String is (case-insensitive) "true", otherwise false
  • valueOf(String) ditto, returns the canonical Boolean Objects
  • getBoolean(String) is a red herring; it fetches the System property of the given name and compares that to "true"

There exists no method to test whether a String encodes a Boolean; for all practical effects, any non-"true"-String is "false".

like image 177
mfx Avatar answered Sep 28 '22 07:09

mfx


return "true".equals(value) || "false".equals(value); 
like image 32
Bombe Avatar answered Sep 28 '22 09:09

Bombe