Shortcut "or-assignment" (|=) operator in Java

64,441

Solution 1

The |= is a compound assignment operator (JLS 15.26.2) for the boolean logical operator | (JLS 15.22.2); not to be confused with the conditional-or || (JLS 15.24). There are also &= and ^= corresponding to the compound assignment version of the boolean logical & and ^ respectively.

In other words, for boolean b1, b2, these two are equivalent:

 b1 |= b2;
 b1 = b1 | b2;

The difference between the logical operators (& and |) compared to their conditional counterparts (&& and ||) is that the former do not "shortcircuit"; the latter do. That is:

  • & and | always evaluate both operands
  • && and || evaluate the right operand conditionally; the right operand is evaluated only if its value could affect the result of the binary operation. That means that the right operand is NOT evaluated when:
    • The left operand of && evaluates to false
      • (because no matter what the right operand evaluates to, the entire expression is false)
    • The left operand of || evaluates to true
      • (because no matter what the right operand evaluates to, the entire expression is true)

So going back to your original question, yes, that construct is valid, and while |= is not exactly an equivalent shortcut for = and ||, it does compute what you want. Since the right hand side of the |= operator in your usage is a simple integer comparison operation, the fact that | does not shortcircuit is insignificant.

There are cases, when shortcircuiting is desired, or even required, but your scenario is not one of them.

It is unfortunate that unlike some other languages, Java does not have &&= and ||=. This was discussed in the question Why doesn't Java have compound assignment versions of the conditional-and and conditional-or operators? (&&=, ||=).

Solution 2

It's not a "shortcut" (or short-circuiting) operator in the way that || and && are (in that they won't evaluate the RHS if they already know the result based on the LHS) but it will do what you want in terms of working.

As an example of the difference, this code will be fine if text is null:

boolean nullOrEmpty = text == null || text.equals("")

whereas this won't:

boolean nullOrEmpty = false;
nullOrEmpty |= text == null;
nullOrEmpty |= text.equals(""); // Throws exception if text is null

(Obviously you could do "".equals(text) for that particular case - I'm just trying to demonstrate the principle.)

Solution 3

You could just have one statement. Expressed over multiple lines it reads almost exactly like your sample code, only less imperative:

boolean negativeValue
    = defaultStock < 0 
    | defaultWholesale < 0
    | defaultRetail < 0
    | defaultDelivery < 0;

For simplest expressions, using | can be faster than || because even though it avoids doing a comparison it means using a branch implicitly and that can be many times more expensive.

Solution 4

Though it might be overkill for your problem, the Guava library has some nice syntax with Predicates and does short-circuit evaluation of or/and Predicates.

Essentially, the comparisons are turned into objects, packaged into a collection, and then iterated over. For or predicates, the first true hit returns from the iteration, and vice versa for and.

Solution 5

If it is about readability I've got the concept of separation tested data from the testing logic. Code sample:

// declare data
DataType [] dataToTest = new DataType[] {
    defaultStock,
    defaultWholesale,
    defaultRetail,
    defaultDelivery
}

// define logic
boolean checkIfAnyNegative(DataType [] data) {
    boolean negativeValue = false;
    int i = 0;
    while (!negativeValue && i < data.length) {
        negativeValue = data[i++] < 0;
    }
    return negativeValue;
}

The code looks more verbose and self-explanatory. You may even create an array in method call, like this:

checkIfAnyNegative(new DataType[] {
    defaultStock,
    defaultWholesale,
    defaultRetail,
    defaultDelivery
});

It's more readable than 'comparison string', and also has performance advantage of short-circuiting (at the cost of array allocation and method call).

Edit: Even more readability can be simply achieved by using varargs parameters:

Method signature would be:

boolean checkIfAnyNegative(DataType ... data)

And the call could look like this:

checkIfAnyNegative( defaultStock, defaultWholesale, defaultRetail, defaultDelivery );
Share:
64,441
David Mason
Author by

David Mason

I have loved coding from the moment I discovered it! I love to learn, so I try to become familiar with as many technologies as possible. The major benefits I reap from this are that I tend not to be overly constrained when selecting the right tool for the job, I can usually provide some insight to my peers when they need help, and I gain a stronger appreciation for the common principles underlying various technologies. I work professionally in web development using all the usual tools. I work across the full stack, but lean towards the frontend and user experience side. When I can find some spare time, I dabble in game development.

Updated on March 09, 2020

Comments

  • David Mason
    David Mason about 4 years

    I have a long set of comparisons to do in Java, and I'd like to know if one or more of them come out as true. The string of comparisons was long and difficult to read, so I broke it up for readability, and automatically went to use a shortcut operator |= rather than negativeValue = negativeValue || boolean.

    boolean negativeValue = false;
    negativeValue |= (defaultStock < 0);
    negativeValue |= (defaultWholesale < 0);
    negativeValue |= (defaultRetail < 0);
    negativeValue |= (defaultDelivery < 0);
    

    I expect negativeValue to be true if any of the default<something> values are negative. Is this valid? Will it do what I expect? I couldn't see it mentioned on Sun's site or stackoverflow, but Eclipse doesn't seem to have a problem with it and the code compiles and runs.


    Similarly, if I wanted to perform several logical intersections, could I use &= instead of &&?

  • Jon Skeet
    Jon Skeet about 14 years
    I think I'd prefer negativeValue = defaultStock < 0 || defaultWholesale < 0 etc. Aside from the inefficiency of all the boxing and wrapping going on here, I don't find it nearly as easy to understand what your code would really mean.
  • Roman
    Roman about 14 years
    I he has even more then 4 parameters and the criterion is the same for all of them then I like my solution, but for the sake of readability I would separate it into several lines (i.e. create List, find minvalue, compare minvalue with 0).
  • David Mason
    David Mason about 14 years
    That does look useful for a large number of comparisons. In this case I think the reduction in clarity isn't worth the saving in typing etc.
  • David Mason
    David Mason about 14 years
    I did start with just one, but as stated in the original question I felt that "The string of comparisons was long and difficult to read, so I broke it up for readability". That aside, in this case I'm more interested in learning the behaviour of |= than in making this particular piece of code work.
  • Carl
    Carl about 14 years
    +1, very thorough. it seems plausible that a compiler might well convert to a short-circuit operator, if it could determine that the RHS has no side effects. any clue about that?
  • polygenelubricants
    polygenelubricants about 14 years
    I read that when RHS is trivial and SC is not necessary, the "smart" SC operators are actually a bit slower. If true, then it's more interesting to wonder if some compilers can convert SC to NSC under certain circumstances.
  • user85421
    user85421 over 11 years
    there is NO bitwise OR with booleans! The operator | is integer bitwise OR but is also logical OR - see Java Language Specification 15.22.2.
  • oneklc
    oneklc about 11 years
    You are correct because for a single bit (a boolean) bitwise and logical OR are equivalent. Though practically, the result is the same.
  • David Mason
    David Mason about 11 years
    Array allocation and a method call are a pretty big cost for short-circuiting, unless you've got some expensive operations in the comparisons (the example in the question is cheap though). Having said that, most of the time the maintainability of the code is going to trump performance considerations. I would probably use something like this if I were doing the comparison differently in a bunch of different places or comparing more than 4 values, but for a single case it's somewhat verbose for my tastes.
  • Krzysztof Jabłoński
    Krzysztof Jabłoński about 11 years
    @DavidMason I agree. However keep in mind, that most modern calculators would swallow that kind of overhead in less than a few millis. Personally I wouldn't care about overhead until performance issues, which appears to be reasonable. Also, code verbosity is an advantage, especially when javadoc is not provided or generated by JAutodoc.
  • JAB
    JAB almost 10 years
    @polygenelubricants short-circuited operators involve a branch of some sort under the hood, so if there's no branch-prediction-friendly pattern to the truth values used with the operators and/or the architecture in use does not have good/any branch prediction (and assuming the compiler and/or virtual machine don't do any related optimizations themselves), then yes, SC operators will introduce some slowness compared to non-short-circuiting. The best way to find out of the compiler does anything would be to compile a program using SC vs. NSC and then compare the bytecode to see if it differs.
  • user253751
    user253751 over 9 years
    Also, not to be confused with the bitwise OR operator which is also |
  • Andrei
    Andrei about 5 years
    It it harder to spot mistakes in the operation and the operator names, especially when the names are long. longNameOfAccumulatorAVariable += 5; vs. longNameOfAccumulatorAVariable = longNameOfAccumulatorVVariable + 5;
  • Farid
    Farid over 3 years
    I can't seem to be find a nice use case for this specific operator. I mean if all you care is the result why not stop where your condition are met?
  • Vishy
    Vishy over 3 years
    @Farid sometimes you don't want to stop, say I want to detect if any of a number of tasks did something. I have a busy flag, just because one of my tasks did something doesn't mean I don't want to run my other tasks, but if no task is busy, I want to take an action instead.