How do I convert primitive boolean type into Boolean object?

The following code snippet demonstrate how to use the Boolean.valueOf() method to convert primitive boolean value or a string into Boolean object. This method will return the corresponding Boolean object of the given primitive boolean value.

When a string value is passed to this method it will return Boolean.TRUE when the string is not null, and the value is equal, ignoring case, to the string "true". Otherwise, it will return Boolean.FALSE object.

package org.kodejava.lang;

public class BooleanValueOfExample {
    public static void main(String[] args) {
        boolean b = true;
        Boolean bool = Boolean.valueOf(b);
        System.out.println("bool = " + bool);

        // Here we test the conversion, which is likely unnecessary. But
        // here is shown the boolean true is equals to Boolean.TRUE static
        // variable and of course you can guest the boolean false value is
        // equals to Boolean.FALSE
        if (bool.equals(Boolean.TRUE)) {
            System.out.println("bool = " + bool);
        }

        // On the line below we convert a string to Boolean, it returns
        // true if and only if the string is equals to "true" otherwise it
        // returns false
        String s = "false";
        Boolean bools = Boolean.valueOf(s);
        System.out.println("bools = " + bools);

        String f = "abc";
        Boolean abc = Boolean.valueOf(f);
        System.out.println("abc = " + abc);
    }
}

The code snippet will print the following output:

bool = true
bool = true
boolS = false
abc = false
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.