Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert String object to Boolean Object?

How to convert String object to Boolean object?

like image 205
Suresh Avatar asked Oct 08 '09 16:10

Suresh


People also ask

Can you convert a string to a boolean in java?

There are two ways to convert a String to a boolean in Java, first, by using Boolean. parseBoolean() method, and second, by using Boolean. valueOf() method. The parseBoolean() method returns an equivalent boolean value of a given String, for example, if you pass "true" it will return the primitive boolean value true.

What converts the boolean Object into string Object?

To convert Boolean to String in Java, use the toString() method.

How do you convert string 1 or 0 to boolean in java?

To convert String to boolean in Java, you can use Boolean. parseBoolean(string). But if you want to convert String to Boolean object then use the method Boolean. valueOf(string) method.

Can string be used in boolean?

We can convert String to boolean in java using Boolean. parseBoolean(string) method. To convert String into Boolean object, we can use Boolean. valueOf(string) method which returns instance of Boolean class.


1 Answers

Try (depending on what result type you want):

Boolean boolean1 = Boolean.valueOf("true"); boolean boolean2 = Boolean.parseBoolean("true"); 

Advantage:

  • Boolean: this does not create new instances of Boolean, so performance is better (and less garbage-collection). It reuses the two instances of either Boolean.TRUE or Boolean.FALSE.
  • boolean: no instance is needed, you use the primitive type.

The official documentation is in the Javadoc.


UPDATED:

Autoboxing could also be used, but it has a performance cost.
I suggest to use it only when you would have to cast yourself, not when the cast is avoidable.

like image 79
KLE Avatar answered Sep 23 '22 21:09

KLE