37

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?

4
  • 3
    Why would you want to use Boolean instead of boolean here to start with? Commented Mar 18, 2014 at 21:59
  • Yeah, I don't get the use-case of this. Seems like a purely academic question. Commented Mar 18, 2014 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 Commented Mar 18, 2014 at 22:23
  • 2
    There's no best practice for comparing Booleans rather than booleans, 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 NullPointerExceptions. Commented Mar 18, 2014 at 22:27

7 Answers 7

82

Try this:

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

As additional benefit, this comparison is null-safe.

Sign up to request clarification or add additional context in comments.

1 Comment

works flawlessly
26

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.

2 Comments

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 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 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.
3

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.

1 Comment

Nice answer. Would there be any problem with == in case any of the two are null?
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.

Comments

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.

4 Comments

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..?
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 '=='.
Ok, I have researched a little on what you and @Migol have said. I came across this. 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?
Darn, missed the time limit for edits. Regarding my comment immediately above, Steve's comment seems to go against your statements on performance
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.

4 Comments

Other than system performance, do the two ways have no difference?
@ylun well, you also have coding conventions - using method is breaking them.
Is there a specific document on the conventions for comparisons? I can't seem to find them in Oracle's Java Conventions
@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.
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.