Tuesday, September 18, 2018

3 Ways to convert String to Boolean in Java? Examples

You can convert a String object to Boolean object or boolean primitive by using the Boolean.valueOf() and Boolean.parseBoolean() method. The steps are similar rot converting to String to other data types e.g. String to Integer and String to Long. You can use valueOf() method to convert String to Boolean object and parseBoolean() method to convert given String to boolean primitive value. Internally, valueOf() also uses parseBoolean() for parsing String but on top of that it also provides caching e.g. it can return Boolean.TRUE and Boolean.FALSE cached value for "true" and "false" string.  In fact, the Boolean.TRUE is returned only when String is equal to true ignoring case e.g. "True", "true", "TRUE" will evaluate into boolean true, hence Boolean.TRUE will be returned. For string like "Yes", Boolean.FALSE will be returned. We'll discuss the rules of String to boolean conversion in next section.



1. Rules of String to Boolean Conversion in Java

The parsing logic is encapsulated in parseBoolean() method which is also leveraged or used by valueOf(). According to this logic, the parseBoolean() method return true if given String is not null and equal to true ignoring case and false otherwise. For example, "true", "True", and "TRUE" all will return Boolean.TRUE value but "Yes" will return Boolean.FALSE. Similarly, "false", "False", or "FALSE" will also return Boolean.FALSE

Here are some examples:

Boolean.parseBoolean("True") returns true.
Boolean.parseBoolean("TRUE") returns true.
Boolean.parseBoolean("true") returns true.
Boolean.parseBoolean("yes") returns false.
Boolean.parseBoolean("y") returns false.
Boolean.parseBoolean("no") returns false.
Boolean.parseBoolean("false") returns false.
Boolean.parseBoolean("False") returns false.
Boolean.parseBoolean("FALSE") returns false.

If you want to know more about how to convert one data type to other in Java,  The Complete Java Masterclass is a good resource to learn it in depth.




2. Boolean.parseBoolean() Example

The parseBoolean() method is similar to parseInt() method and it returns a primitive boolean value after parsing given String. It returns a boolean value, true or false based upon the rules given above. It compares String by ignoring case and only return true if String matches true after ignoring cases.

Boolean.parseBoolean("True") returns true.
Boolean.parseBoolean("TRUE") returns true.
Boolean.parseBoolean("true") returns true.
Boolean.parseBoolean("yes") returns false.

You should use this method if you need a primitive boolean value.



3. Boolean.valueOf() Example

This method should be used to convert a String object to a Boolean object in Java. It leverages the parsing logic of parseooleBan() method but it also uses the Flyweight design pattern to cache frequently used value and returns them.

Since boolean can either be true or false, it just uses two Boolean instances, Boolean.TRUE and Boolean.FALSE, for all String to Boolean conversion, which drastically reduces the number of objects and causes less overhead for Garbage collector.

Here are some examples of converting String to Boolean using the valueOf() method:

Boolean.valueOf("True") returns Boolean.TRUE.
Boolean.valueOf("TRUE") returns Boolean.TRUE.
Boolean.valueOf("true") returns Boolean.TRUE.
Boolean.valueOf("yes") returns Boolean.FALSE.
Boolean.valueOf("y") returns Boolean.FALSE.
Boolean.valueOf("no") returns Boolean.FALSE.
Boolean.valueOf("false") returns Boolean.FALSE.
Boolean.valueOf("False") returns Boolean.FALSE.
Boolean.valueOf("FALSE") returns Boolean.FALSE.

You should use this method if you need a Boolean object from String rather than boolean primitive value.  If you want to know more about primitive data types in Java then Java Fundamentals: The Java Language a good place to start with.

String to Boolean in Java



4. Java Program to convert String to Boolean

Here is your complete Java program, which you can copy and paste in your Eclipse IDE and run. This program accepts a user input as String and tries to convert it to a boolean. If successful, it prints that value into the console, otherwise, it throws an error.

package tool;

import java.util.Scanner;

/**
 * 
 * A simple Java Program to convert String to Boolean or boolean data type.
 */
public class Hello {

  public static void main(String[] args) {

    System.out.println("Please enter a boolean String e.g. true or false");

    Scanner sc = new Scanner(System.in);

    String input = sc.next();

    boolean b = Boolean.valueOf(input);

    System.out.println("converted boolean value from String using valueOf: "
        + b);

    boolean value = Boolean.parseBoolean(input);

    System.out
        .println("converted boolean value from String using parseBoolean: "
            + value);

    sc.close();

    // you can also use constructor but that is not encouraged by Effective Java

    Boolean bool = new Boolean(input);
    System.out
        .println("converted boolean value from String using constructor: "
            + bool);

  }

}

Output
Please enter a boolean String e.g. true or false
true
converted boolean value from String using valueOf: true
converted boolean value from String using parseBoolean: true
converted boolean value from String using constructor: true


Here is the summary of all three methods to convert String to Boolean in Java:

3 Ways to convert String to Boolean in Java? Examples


5. Important points

5.1 Even though you can also use the constructor of java.lang.Boolean class to convert String to a Boolean object, it's not encouraged by Effective Java of Joshua Bloch, which advice prefer static factory methods like valueOf() to take advantage of caching they offer.

5.2. The parsing rules i.e. how the string is actually converted into a boolean value is written in parseBoolean() method.

5.3 Both valueOf() and parseBoolean() method belongs to java.lang.Boolean class.

5.4. The valueOf() method return either the Boolean.TRUE or  Boolean.FALSE object, which is shared by all boolean values converted.


That's all about how to convert String to Boolean or boolean in Java. As I said, you can use either Boolean.valueOf(), a static factory method or the parseBoolean() method for this conversion. The rule of thumb is to prefer valueOf() if you need Boolean object and parseBoolean() if you need a boolean primitive value.


Further Learning

Thanks for reading this article so far. If you like this tutorial then please share with your friends and colleagues. If you have any questions or feedback then please drop a note. 

No comments :

Post a Comment