36

Take this for example (excerpt from Java regex checker not working):

while(!checker) {
    matcher = pattern.matcher(number);
    if(matcher.find())
        checker = true;
    else
        year++;
}

Would it matter if .equals(false) was used to check for the value of the Boolean checker?

I know that there is this which is rather similar. However, obviously the question deals with primitive boolean and not the object wrapper, Boolean; thus, .equals() would not be applicable.

Also, should Boolean be dealt differently than boolean?

Community
  • 1
  • 1
ylun.ca
  • 2,504
  • 7
  • 26
  • 47
  • 3
    Why would you *want* to use `Boolean` instead of `boolean` here to start with? – Jon Skeet Mar 18 '14 at 21:59
  • Yeah, I don't get the use-case of this. Seems like a purely academic question. – asteri Mar 18 '14 at 22:19
  • @JonSkeet `this question applies for all Java boolean comparisons and not just the link`. I want to know the better practice for all `Boolean` comparisons – ylun.ca Mar 18 '14 at 22:23
  • 2
    There's no best practice for comparing `Boolean`s rather than `boolean`s, because comparing the object wrapper is already a bad practice. Haha. There's no reason to ever use it, and it only opens you up to unneeded bugs like `NullPointerException`s. – asteri Mar 18 '14 at 22:27

7 Answers7

77

Try this:

if (Boolean.TRUE.equals(yourValue)) { 
    // ...
}

As additional benefit, this comparison is null-safe.

yglodt
  • 13,807
  • 14
  • 91
  • 127
24

From your comments, it seems like you're looking for "best practices" for the use of the Boolean wrapper class. But there really aren't any best practices, because it's a bad idea to use this class to begin with. The only reason to use the object wrapper is in cases where you absolutely must (such as when using Generics, i.e., storing a boolean in a HashMap<String, Boolean> or the like). Using the object wrapper has no upsides and a lot of downsides, most notably that it opens you up to NullPointerExceptions.

Does it matter if '!' is used instead of .equals() for Boolean?

Both techniques will be susceptible to a NullPointerException, so it doesn't matter in that regard. In the first scenario, the Boolean will be unboxed into its respective boolean value and compared as normal. In the second scenario, you are invoking a method from the Boolean class, which is the following:

public boolean equals(Object obj) {
    if (obj instanceof Boolean) {
        return value == ((Boolean)obj).booleanValue();
    }
    return false;
}

Either way, the results are the same.

Would it matter if .equals(false) was used to check for the value of the Boolean checker?

Per above, no.

Secondary question: Should Boolean be dealt differently than boolean?

If you absolutely must use the Boolean class, always check for null before performing any comparisons. e.g.,

Map<String, Boolean> map = new HashMap<String, Boolean>();
//...stuff to populate the Map
Boolean value = map.get("someKey");
if(value != null && value) {
    //do stuff
}

This will work because Java short-circuits conditional evaluations. You can also use the ternary operator.

boolean easyToUseValue = value != null ? value : false;

But seriously... just use the primitive type, unless you're forced not to.

asteri
  • 11,402
  • 13
  • 60
  • 84
  • Thank you. Regarding your answer to `Would it matter if .equals(false) was used to check for the value of the Boolean checker?`. Both Sunil and Migol have said that `.equals()` hinders performance. However, I have found Steve Kuo's comment [here](http://stackoverflow.com/questions/1750435/comparing-java-enum-members-or-equals) that seems to contradict them. Who is correct? FYI Steve said `equals will most likely be inlined by the JIT, so performance isn't an issue` – ylun.ca Mar 18 '14 at 23:05
  • 1
    @ylun Both methods have different performance overheads. The first has to unbox the `Boolean` to a `boolean`, while the second has to box the `false` to a `Boolean`, then cast it from `Object` back to `Boolean` in the `.equals()` method. My guess would be that the `.equals()` method is slower, but I'd have to make an actual benchmark and test it. You can do so yourself by performing each operation a few million times and measuring the time elapsed. – asteri Mar 18 '14 at 23:13
2

As long as checker is not null, you may use !checker as posted. This is possible since Java 5, because this Boolean variable will be autoboxed to the primivite boolean value.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
2

Using direct conditions (like ==, !=, !condition) will have a slight performance improvement over the .equals(condition) as in one case you are calling the method from an object whereas direct comparisons are performed directly.

ucsunil
  • 7,378
  • 1
  • 27
  • 32
  • What do you mean by "comparisons are performed directly"? What I interpreted: There is no need to access a method in another class to perform the comparison and is therefore faster..? – ylun.ca Mar 18 '14 at 22:33
  • yes - basically because you are chaining to the super class and calling a method from it. But depending on the nature of comparison, you might want to stick with .equals() over '=='. – ucsunil Mar 18 '14 at 22:38
  • Ok, I have researched a little on what you and @Migol have said. I came across [this](http://stackoverflow.com/questions/1750435/comparing-java-enum-members-or-equals). More specifically, `Steve Kuo` said `equals will most likely be inlined by the JIT, so performance isn't an issue`. What doe he mean by this? – ylun.ca Mar 18 '14 at 22:46
  • Darn, missed the time limit for edits. Regarding my comment immediately above, Steve's comment seems to go against your statements on performance – ylun.ca Mar 18 '14 at 22:53
2

Regarding the performance of the direct operations and the method .equals(). The .equals() methods seems to be roughly 4 times slower than ==.

I ran the following tests..

For the performance of ==:

public class BooleanPerfCheck {

    public static void main(String[] args) {
        long frameStart;
        long elapsedTime;

        boolean heyderr = false;

        frameStart = System.currentTimeMillis();

        for (int i = 0; i < 999999999; i++) {
            if (heyderr == false) {
            }
        }

        elapsedTime = System.currentTimeMillis() - frameStart;
        System.out.println(elapsedTime);
    }
}

and for the performance of .equals():

public class BooleanPerfCheck {

    public static void main(String[] args) {
        long frameStart;
        long elapsedTime;

        Boolean heyderr = false;

        frameStart = System.currentTimeMillis();

        for (int i = 0; i < 999999999; i++) {
            if (heyderr.equals(false)) {
            }
        }

        elapsedTime = System.currentTimeMillis() - frameStart;
        System.out.println(elapsedTime);
    }
}

Total system time for == was 1

Total system time for .equals() varied from 3 - 5

Thus, it is safe to say that .equals() hinders performance and that == is better to use in most cases to compare Boolean.

ylun.ca
  • 2,504
  • 7
  • 26
  • 47
1

.equals(false) will be slower because you are calling a virtual method on an object rather than using faster syntax and rather unexpected by most of the programmers because code standards that are generally used don't really assume you should be doing that check via .equals(false) method.

Migol
  • 8,161
  • 8
  • 47
  • 69
  • Other than system performance, do the two ways have no difference? – ylun.ca Mar 18 '14 at 22:18
  • @ylun well, you also have coding conventions - using method is breaking them. – Migol Mar 18 '14 at 22:22
  • Is there a specific document on the conventions for comparisons? I can't seem to find them in [Oracle's Java Conventions](http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-137265.html#529) – ylun.ca Mar 18 '14 at 22:29
  • 1
    @ylun It's well known convention and well, I **never** saw anyone use `.equals(false)` in their code as standard in my 10 years of programming. Read other peoples code, look at examples in Java documentation - you won't find it. – Migol Mar 18 '14 at 22:33
0

As object?

equals

public boolean equals(Object obj)

Returns true if and only if the argument is not null and is a Boolean object that represents the same boolean value as this object.

Overrides: equals in class Object

Parameters: obj - the object to compare with.

Returns: true if the Boolean objects represent the same value; false otherwise.

boolean a = true;
boolean b = false;

System.out.println("a.equals(b):" + ((Object)a).equals( ((Object)b) ));

Output: a.equals(b):false

CamelTM
  • 1,225
  • 12
  • 17