239

I'm just wondering why we usually use logical OR || between two booleans not bitwise OR |, though they are both working well.

I mean, look at the following:

if(true  | true)  // pass
if(true  | false) // pass
if(false | true)  // pass
if(false | false) // no pass
if(true  || true)  // pass
if(true  || false) // pass
if(false || true)  // pass
if(false || false) // no pass

Can we use | instead of ||? Same thing with & and &&.

Michael
  • 41,989
  • 11
  • 82
  • 128
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
  • 18
    Most people forget that | is a non-short-circuiting boolean operator in addition to being a bitwise operator. – John Meagher Sep 18 '08 at 20:47
  • 1
    Details on the difference are in the JLS. See http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.22.2 – John Meagher Sep 18 '08 at 20:57
  • 66
    They are not the same. Please check out the tutorials on them especially regarding [short-circuit evaluation vs eager evaluation](http://en.wikipedia.org/wiki/Short-circuit_evaluation). `||` and `&&` short-circuit while `|` and `&` are eager. – Hovercraft Full Of Eels Aug 18 '11 at 03:23
  • 4
    Just out of curiosity, in what case would you actually want to use the non-short circuited versions? I almost always see `&&` and `||`, but never `&` `|`. If you're doing something that depends on side effects, I don't see why you'd use something like `(a & b | c)` since someone could easily think "I can optimize this by using the short circuited versions." – Mike Bailey Aug 18 '11 at 23:57
  • 1
    It's the difference between (bitwise) Boolean vs "logical" (ie, having to do with mathematical "logic"). It is somewhat incidental (but very important) that the logical operators are "short-circuiting". – Hot Licks Sep 04 '14 at 20:49
  • 2
    And, of course, they have different precedence. – Hot Licks Sep 04 '14 at 20:49
  • Updated JLS link: https://docs.oracle.com/javase/specs/jls/se11/html/jls-15.html#jls-15.22.2 – Vadzim Dec 26 '18 at 17:10

28 Answers28

369

If you use the || and && forms, rather than the | and & forms of these operators, Java will not bother to evaluate the right-hand operand alone.

It's a matter of if you want to short-circuit the evaluation or not -- most of the time you want to.

A good way to illustrate the benefits of short-circuiting would be to consider the following example.

Boolean b = true;
if(b || foo.timeConsumingCall())
{
   //we entered without calling timeConsumingCall()
}

Another benefit, as Jeremy and Peter mentioned, for short-circuiting is the null reference check:

if(string != null && string.isEmpty())
{
    //we check for string being null before calling isEmpty()
}

more info

Jeremy
  • 22,188
  • 4
  • 68
  • 81
Shawn
  • 7,235
  • 6
  • 33
  • 45
  • 120
    The canonical example is `foo != null && foo.hasBar()` – Jeremy Aug 18 '11 at 03:47
  • 1
    If you add in about possible null reference exception using | from @Jeremy's comment then this is great answer. – Peter Kelly Aug 18 '11 at 07:55
  • Also remember that && and || mean a branch instruction at the machine code level (remember branches can cause branch mispredictions), so if you are *super-pedantic* about performance only use them when they are actually required (`foo != null && foo.hasBar()`) or faster (`b || foo.timeConsumingCall()`). 99% of developers shouldn't need to worry about this level of micro-optimization though. – Jonathan Dickinson Aug 18 '11 at 07:55
  • 4
    I'm surprised noone mentioned when you want to use |. The most common scenario I use it is when a variable is modified in the check like (j>3 | ++i>3) or (++i > 3 | modifiesGlobalAmongOtherThings() = true). Not too common though. – AndSoYouCode Aug 18 '11 at 08:30
  • 9
    Another canonical example is `string == null || string.isEmpty()` ;) – Peter Lawrey Aug 18 '11 at 09:42
  • the example might be changed to `if(string != null && !string.isEmpty())`, otherwise it's true only for the empty string - not sure if this is what you were going for – Paul Bellora Aug 18 '11 at 18:59
92

| does not do short-circuit evaluation in boolean expressions. || will stop evaluating if the first operand is true, but | won't.

In addition, | can be used to perform the bitwise-OR operation on byte/short/int/long values. || cannot.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Michael Myers
  • 188,989
  • 46
  • 291
  • 292
64

So just to build on the other answers with an example, short-circuiting is crucial in the following defensive checks:

if (foo == null || foo.isClosed()) {
    return;
}

if (bar != null && bar.isBlue()) {
    foo.doSomething();
}

Using | and & instead could result in a NullPointerException being thrown here.

Paul Bellora
  • 54,340
  • 18
  • 130
  • 181
  • If you applied the NullObject pattern it wouldn't (or rather would negate the answer). Also, I'd say checking whether the foo is blue is something internal to foo. If it's blue, then doSomething should do nothing. – nicodemus13 Aug 18 '11 at 16:07
  • @nicodemus13 - good points, though the Null Object pattern is only sometimes desirable, and the body might be something other than another call to `foo`. Peter Lawrey's "canonical example" is the best. – Paul Bellora Aug 18 '11 at 18:33
  • @Khan: Yes, I was being rather pernickety, and the Null Object isn't always suitable. I've just rather got into the habit of sub-consciously refactoring things. There's nothing particularly wrong with your answer. – nicodemus13 Aug 18 '11 at 20:45
42

Logical || and && check the right hand side only if necessary. The | and & check both the sides everytime.

For example:

int i = 12;
if (i == 10 & i < 9) // It will check if i == 10 and if i < 9
...

Rewrite it:

int i = 12;
if (i == 10 && i < 9) // It will check if i == 10 and stop checking afterward because i != 10
...

Another example:

int i = 12;
if (i == 12 | i > 10) // It will check if i == 12 and it will check if i > 10
...

Rewrite it:

int i = 12;
if (i == 12 || i > 10) // It will check if i == 12, it does, so it stops checking and executes what is in the if statement
...
Mistu4u
  • 5,132
  • 15
  • 53
  • 91
Dair
  • 15,910
  • 9
  • 62
  • 107
20

Also notice a common pitfall: The non lazy operators have precedence over the lazy ones, so:

boolean a, b, c;
a || b && c; //resolves to a || (b && c)
a | b && c; //resolves to (a | b) && c

Be careful when mixing them.

Mister Smith
  • 27,417
  • 21
  • 110
  • 193
15

In addition to short-circuiting, another thing to keep in mind is that doing a bitwise logic operation on values that can be other than 0 or 1 has a very different meaning than conditional logic. While it USUALLY is the same for | and ||, with & and && you get very different results (e.g. 2 & 4 is 0/false while 2 && 4 is 1/true).

If the thing you're getting from a function is actually an error code and you're testing for non-0-ness, this can matter quite a lot.

This isn't as much of an issue in Java where you have to explicitly typecast to boolean or compare with 0 or the like, but in other languages with similar syntax (C/C++ et al) it can be quite confusing.

Also, note that & and | can only apply to integer-type values, and not everything that can be equivalent to a boolean test. Again, in non-Java languages, there are quite a few things that can be used as a boolean with an implicit != 0 comparison (pointers, floats, objects with an operator bool(), etc.) and bitwise operators are almost always nonsensical in those contexts.

fluffy
  • 5,212
  • 2
  • 37
  • 67
  • 3
    I am glad that *at least someone* mentioned the whole purpose of bitwise operators existence. – ulidtko Aug 18 '11 at 16:20
10

The only time you would use | or & instead of || or && is when you have very simple boolean expressions and the cost of short cutting (i.e. a branch) is greater than the time you save by not evaluating the later expressions.

However, this is a micro-optimisation which rarely matters except in the most low level code.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • 1
    It would be interesting whether the compiler does this automatically in some cases. – starblue Aug 18 '11 at 13:56
  • Perhaps the JIT could, but the compiler tends to only deal with simple optimisations. – Peter Lawrey Aug 18 '11 at 16:37
  • Cool that you mention it. I once got a _massive_ boost by rewriting some bottleneck logic to be branchless (and replacing || by | was one of the things I did there). Anyway, one shall still remember the golden rule: *"profile first, optimise second"*. Branch prediction is in our CPUs for a reason too! – Kos Aug 18 '11 at 20:34
  • 2
    Yes, I've also seen situations where | is significantly faster than the branch overhead of ||, especially on CPUs with no or limited branch prediction. It's rare but not unheard of. One of my coworkers got into a revert war in some code with a contractor because he was (correctly) using | and the contractor kept thinking that was "wrong." – fluffy Aug 19 '11 at 05:17
  • 4
    @Fluffy, the moral of the story being that if you do something tricky, it needs to commented as to why you did this or your efforts could be wasted later. ;) – Peter Lawrey Aug 19 '11 at 15:54
  • 1
    Yeah, eventually he added a comment (at my suggestion for how to get the contractor to stop 'fixing' it), and all is well. – fluffy Aug 19 '11 at 17:56
  • @PeterLawrey +1 you have 2 answers on this thread, one-year time difference between them ;) – Eng.Fouad Apr 08 '12 at 06:13
8

a | b: evaluate b in any case

a || b: evaluate b only if a evaluates to false

Community
  • 1
  • 1
user18596
  • 129
  • 1
  • 2
  • 6
8

|| is the logical or operator while | is the bitwise or operator.

boolean a = true;
boolean b = false;

if (a || b) {
}

int a = 0x0001;
a = a | 0x0002;
Jorge Ferreira
  • 96,051
  • 25
  • 122
  • 132
7

In Addition to the fact that | is a bitwise-operator: || is a short-circuit operator - when one element is false, it will not check the others.

 if(something || someotherthing)
 if(something | someotherthing)

if something is TRUE, || will not evaluate someotherthing, while | will do. If the variables in your if-statements are actually function calls, using || is possibly saving a lot of performance.

Michael Stum
  • 177,530
  • 117
  • 400
  • 535
  • Why would you ever use | in an if statement. || is boolean, | is not, | would only be boolean if your already working on two boolean values. – FlySwat Sep 18 '08 at 20:44
  • This is the first answer to get it all. – John Meagher Sep 18 '08 at 20:46
  • This answer is incorrect. If something is FALSE, both operators will go on to the next operand. The difference arises only when the first operand is true. – Michael Myers Sep 18 '08 at 20:47
  • To bad it has an absolutely ridiculous example. – FlySwat Sep 18 '08 at 20:47
  • I have no idea why anyone would use | or & in an if-statement for simple boolean comparison, but it's perfectly legal, and i've actually seen examples of that when I started learning programming. – Michael Stum Sep 18 '08 at 20:47
  • Ok, so he got to exact example wrong (it would be right for &&), he got the concepts right (hopefully someone will edit it). – John Meagher Sep 18 '08 at 20:48
  • thanks, indeed confused && and ||, fixed. Feel free to edit and append if you think that this unusual but valid use is a bad example, that's what StackOverflow is for :) – Michael Stum Sep 18 '08 at 20:49
  • Don't have enough rep to edit other's posts. Thanks for correcting. For the record, I think the example is just fine (if a little simplistic). – John Meagher Sep 18 '08 at 20:51
  • Yes, because as Jonathan pointed out: While using | in an if-statement is not used, it is actually one legal usage, although the only "proper "usage *I* can think if would be a huge WTF: if(importantFunction | otherImportantFunction) - to ensure both functions run but only one needs to return true. – Michael Stum Sep 18 '08 at 22:52
  • To clarify the previous (correct) comment, You use & or | if your right-hand argument has a side-effect and must run every time the if is evaluated. This is not a good programming practice and if you find yourself using it this way you are almost certainly adding to the length, complexity and buggyness of your project. – Bill K Apr 27 '10 at 18:23
3

The operators || and && are called conditional operators, while | and & are called bitwise operators. They serve different purposes.

Conditional operators works only with expressions that statically evaluate to boolean on both left- and right-hand sides.

Bitwise operators works with any numeric operands.

If you want to perform a logical comparison, you should use conditional operators, since you will add some kind of type safety to your code.

Bruno Reis
  • 37,201
  • 11
  • 119
  • 156
  • Um, `|` and `&` are also conditional operators. Please see the link in my comment to the original post. – Hovercraft Full Of Eels Aug 18 '11 at 03:30
  • @Hovercraft Full Of Eels: That chart is a bit misleading; it's referring to them as conditional operators ONLY in the context of boolean values, where they are mathematically equivalent to eager logical operators. When you start dealing with things that have values other than 0 or 1, or floating point values or pointers or whatever, the comparison breaks down. – fluffy Aug 18 '11 at 17:19
  • @fluffy: there's nothing misleading about the chart since the discussion was only about boolean operators. That the `|` and `&` can be used as bit-wise operators is a completely separate issue. – Hovercraft Full Of Eels Aug 18 '11 at 17:54
  • 1
    It would be more accurate to refer to them as bit-wise operators used on boolean values, and not boolean operators. They just HAPPEN to be mathematically-equivalent when there's only a single bit. – fluffy Aug 18 '11 at 19:57
3
| is the binary or operator

|| is the logic or operator
Lucas S.
  • 13,391
  • 8
  • 46
  • 46
2

1).(expression1 | expression2), | operator will evaluate expression2 irrespective of whether the result of expression1 is true or false.

Example:

class Or 
{
    public static void main(String[] args) 
    {
        boolean b=true;

        if (b | test());
    }

    static boolean test()
    {
        System.out.println("No short circuit!");
        return false;
    }
}

2).(expression1 || expression2), || operator will not evaluate expression2 if expression1 is true.

Example:

class Or 
{
    public static void main(String[] args) 
    {
        boolean b=true;

        if (b || test())
        {
            System.out.println("short circuit!");
        }
    }

    static boolean test()
    {
        System.out.println("No short circuit!");
        return false;
    }
}
FacelessTiger
  • 89
  • 1
  • 1
  • 11
Veeresh
  • 21
  • 1
2

The other answers have done a good job of covering the functional difference between the operators, but the answers could apply to just about every single C-derived language in existence today. The question is tagged with , and so I will endeavor to answer specifically and technically for the Java language.

& and | can be either Integer Bitwise Operators, or Boolean Logical Operators. The syntax for the Bitwise and Logical Operators (§15.22) is:

AndExpression:
  EqualityExpression 
  AndExpression & EqualityExpression

ExclusiveOrExpression:
  AndExpression 
  ExclusiveOrExpression ^ AndExpression

InclusiveOrExpression:
  ExclusiveOrExpression 
  InclusiveOrExpression | ExclusiveOrExpression

The syntax for EqualityExpression is defined in §15.21, which requires RelationalExpression defined in §15.20, which in turn requires ShiftExpression and ReferenceType defined in §15.19 and §4.3, respectively. ShiftExpression requires AdditiveExpression defined in §15.18, which continues to drill down, defining the basic arithmetic, unary operators, etc. ReferenceType drills down into all the various ways to represent a type. (While ReferenceType does not include the primitive types, the definition of primitive types is ultimately required, as they may be the dimension type for an array, which is a ReferenceType.)

The Bitwise and Logical Operators have the following properties:

  • These operators have different precedence, with & having the highest precedence and | the lowest precedence.
  • Each of these operators is syntactically left-associative (each groups left-to-right).
  • Each operator is commutative if the operand expressions have no side effects.
  • Each operator is associative.
  • The bitwise and logical operators may be used to compare two operands of numeric type or two operands of type boolean. All other cases result in a compile-time error.

The distinction between whether the operator serves as a bitwise operator or a logical operator depends on whether the operands are "convertible to a primitive integral type" (§4.2) or if they are of types boolean or Boolean (§5.1.8).

If the operands are integral types, binary numeric promotion (§5.6.2) is performed on both operands, leaving them both as either longs or ints for the operation. The type of the operation will be the type of the (promoted) operands. At that point, & will be bitwise AND, ^ will be bitwise exclusive OR, and | will be bitwise inclusive OR. (§15.22.1)

If the operands are boolean or Boolean, the operands will be subject to unboxing conversion if necessary (§5.1.8), and the type of the operation will be boolean. & will result in true if both operands are true, ^ will result in true if both operands are different, and | will result in true if either operand is true. (§15.22.2)

In contrast, && is the "Conditional-And Operator" (§15.23) and || is the "Conditional-Or Operator" (§15.24). Their syntax is defined as:

ConditionalAndExpression:
  InclusiveOrExpression 
  ConditionalAndExpression && InclusiveOrExpression

ConditionalOrExpression:
  ConditionalAndExpression 
  ConditionalOrExpression || ConditionalAndExpression

&& is like &, except that it only evaluates the right operand if the left operand is true. || is like |, except that it only evaluates the right operand if the left operand is false.

Conditional-And has the following properties:

  • The conditional-and operator is syntactically left-associative (it groups left-to-right).
  • The conditional-and operator is fully associative with respect to both side effects and result value. That is, for any expressions a, b, and c, evaluation of the expression ((a) && (b)) && (c) produces the same result, with the same side effects occurring in the same order, as evaluation of the expression (a) && ((b) && (c)).
  • Each operand of the conditional-and operator must be of type boolean or Boolean, or a compile-time error occurs.
  • The type of a conditional-and expression is always boolean.
  • At run time, the left-hand operand expression is evaluated first; if the result has type Boolean, it is subjected to unboxing conversion (§5.1.8).
  • If the resulting value is false, the value of the conditional-and expression is false and the right-hand operand expression is not evaluated.
  • If the value of the left-hand operand is true, then the right-hand expression is evaluated; if the result has type Boolean, it is subjected to unboxing conversion (§5.1.8). The resulting value becomes the value of the conditional-and expression.
  • Thus, && computes the same result as & on boolean operands. It differs only in that the right-hand operand expression is evaluated conditionally rather than always.

Conditional-Or has the following properties:

  • The conditional-or operator is syntactically left-associative (it groups left-to-right).
  • The conditional-or operator is fully associative with respect to both side effects and result value. That is, for any expressions a, b, and c, evaluation of the expression ((a) || (b)) || (c) produces the same result, with the same side effects occurring in the same order, as evaluation of the expression (a) || ((b) || (c)).
  • Each operand of the conditional-or operator must be of type boolean or Boolean, or a compile-time error occurs.
  • The type of a conditional-or expression is always boolean.
  • At run time, the left-hand operand expression is evaluated first; if the result has type Boolean, it is subjected to unboxing conversion (§5.1.8).
  • If the resulting value is true, the value of the conditional-or expression is true and the right-hand operand expression is not evaluated.
  • If the value of the left-hand operand is false, then the right-hand expression is evaluated; if the result has type Boolean, it is subjected to unboxing conversion (§5.1.8). The resulting value becomes the value of the conditional-or expression.
  • Thus, || computes the same result as | on boolean or Boolean operands. It differs only in that the right-hand operand expression is evaluated conditionally rather than always.

In short, as @JohnMeagher has repeatedly pointed out in the comments, & and | are, in fact, non-short-circuiting boolean operators in the specific case of the operands being either boolean or Boolean. With good practices (ie: no secondary effects), this is a minor difference. When the operands aren't booleans or Booleans, however, the operators behave very differently: bitwise and logical operations simply don't compare well at the high level of Java programming.

Brian S
  • 4,878
  • 4
  • 27
  • 46
2

A side note: Java has |= but not an ||=

An example of when you must use || is when the first expression is a test to see if the second expression would blow up. e.g. Using a single | in hte following case could result in an NPE.

public static boolean isNotSet(String text) {
   return text == null || text.length() == 0;
}
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1

Non short-circuiting can be useful. Sometimes you want to make sure that two expressions evaluate. For example, say you have a method that removes an object from two separate lists. You might want to do something like this:

class foo {

    ArrayList<Bar> list1 = new ArrayList<Bar>();
    ArrayList<Bar> list2 = new ArrayList<Bar>();

    //Returns true if bar is removed from both lists, otherwise false.
    boolean removeBar(Bar bar) {
        return (list1.remove(bar) & list2.remove(bar));
    }
}

If your method instead used the conditional operand, it would fail to remove the object from the second list if the first list returned false.

//Fails to execute the second remove if the first returns false.
boolean removeBar(Bar bar) {
    return (list1.remove(bar) && list2.remove(bar));
}

It's not amazingly useful, and (as with most programming tasks) you could achieve it with other means. But it is a use case for bitwise operands.

ktbiz
  • 586
  • 4
  • 13
1

The basic difference between them is that | first converts the values to binary then performs the bit wise or operation. Meanwhile, || does not convert the data into binary and just performs the or expression on it's original state.

int two = -2; int four = -4;
result = two | four; // bitwise OR example

System.out.println(Integer.toBinaryString(two));
System.out.println(Integer.toBinaryString(four));
System.out.println(Integer.toBinaryString(result));

Output:
11111111111111111111111111111110
11111111111111111111111111111100
11111111111111111111111111111110

Read more: http://javarevisited.blogspot.com/2015/01/difference-between-bitwsie-and-logical.html#ixzz45PCxdQhk

FacelessTiger
  • 89
  • 1
  • 1
  • 11
Avinash Nath
  • 132
  • 8
  • Untrue when the operands are booleans, and stupid formatting. – user207421 Sep 27 '16 at 11:47
  • 2
    This was helpful for me in understanding why Long.valueOf(100 | 200) = 236. Here is why: 0 1 1 0 0 1 0 0 | 1 1 0 0 1 0 0 0 = 1 1 1 0 1 1 0 0 = 128 64 32 0 8 4 0 0 = 236 – donlys Dec 18 '16 at 17:56
1

When I had this question I created test code to get an idea about this.

public class HelloWorld{

   public static boolean bool(){
      System.out.println("Bool");
      return true;
   }

   public static void main(String []args){

     boolean a = true;
     boolean b = false;

     if(a||bool())
     {
        System.out.println("If condition executed"); 
     }
     else{
         System.out.println("Else condition executed");
     }

 }
}

In this case, we only change left side value of if condition adding a or b.

|| Scenario , when left side true [if(a||bool())]

output "If condition executed"

|| Scenario , when left side false [if(b||bool())]

Output-

Bool
If condition executed

Conclusion of || When use ||, right side only check when the left side is false.

| Scenario , when left side true [if(a|bool())]

Output-

Bool
If condition executed

| Scenario , when left side false [if(b|bool())]

Output-

Bool
If condition executed

Conclusion of | When use |, check both left and right side.

Priyantha
  • 4,839
  • 6
  • 26
  • 46
1

One main difference is that || and && exhibit "short-circuiting", so the RHS will only be evaluated if needed.

For e.g.

if (a || b) {
    path1...
} else {
    path2..
}

Above if a is true then b will not be tested and path1 is executed. If | was used then both sides would be evaluated even if 'a' is true.

See Here and here, for a little more information.

Hope this helps.

Gray
  • 115,027
  • 24
  • 293
  • 354
Alex H
  • 431
  • 5
  • 13
1

|| returns a boolean value by OR'ing two values (Thats why its known as a LOGICAL or)

IE:

if (A || B) 

Would return true if either A or B is true, or false if they are both false.

| is an operator that performs a bitwise operation on two values. To better understand bitwise operations, you can read here:

http://en.wikipedia.org/wiki/Bitwise_operation

FlySwat
  • 172,459
  • 74
  • 246
  • 311
0

usually I use when there is pre increment and post increment operator. Look at the following code:

package ocjpPractice;
/**
 * @author tithik
 *
 */
public class Ex1 {

    public static void main(String[] args) {
    int i=10;
    int j=9;
    int x=10;
    int y=9;
    if(i==10 | ++i>j){
        System.out.println("it will print in first if");  
        System.out.println("i is: "+i);
    }

    if(x==10 ||++x>y){
        System.out.println("it will print in second if");   
        System.out.println("x is: "+x);
    }
    }
}

output:

it will print in first if
i is: 11

it will print in second if
x is: 10

both if blocks are same but result is different. when there is |, both the conditions will be evaluated. But if it is ||, it will not evaluate second condition as the first condition is already true.

saluce
  • 13,035
  • 3
  • 50
  • 67
Tithi
  • 9
  • 1
0

There are many use cases suggesting why should you go for || rather than | . Some use cases have to use | operator to check all the conditions.

For example, if you want to check form validation and you want to show the user all the invalid fields with error texts rather than just a first invalid field.

|| operator would be,

   if(checkIfEmpty(nameField) || checkIfEmpty(phoneField) || checkIfEmpty(emailField)) {
      // invalid form with one or more empty fields
   }

   private boolean checkIfEmpty(Widget field) {
      if(field.isEmpty()) {
        field.setErrorMessage("Should not be empty!");
        return true;
      }
      return false;
   }

So with above snippet, if user submits the form with ALL empty fields, ONLY nameField would be shown with error message. But, if you change it to,

   if(checkIfEmpty(nameField) | checkIfEmpty(phoneField) | checkIfEmpty(emailField)) {
      // invalid form with one or more empty fields
   }

It will show proper error message on the each field irrespective of true conditions.

Bharath Mg
  • 1,117
  • 1
  • 9
  • 18
0

After carefully reading this topic is still unclear to me if using | as a logical operator is conform to Java pattern practices.

I recently modified code in a pull request addressing a comment where

if(function1() | function2()){
  ...
}

had to be changed to

boolean isChanged = function1();
isChanged |= function2();
if (isChanged){
  ...
}

What is the actual accepted version?

Java documentation is not mentioning | as a logical non-shortcircuiting OR operator.

Not interested in a vote but more in finding out the standard?! Both code versions are compiling and working as expected.

Dan M
  • 770
  • 1
  • 9
  • 18
  • It's not about code having a bitwise OR operator (|) or logical OR operator (||). However, if you see Dair answer to this very question then it would be clear to you that Logical OR checks the right-hand side only if necessary where bitwise OR checks both the sides every time. – Varun Jain Jan 15 '22 at 19:28
0

| = bitwise or, || = logic or

MagicKat
  • 9,695
  • 6
  • 32
  • 43
-1

|| is a logical or and | is a bit-wise or.

Steve Moyer
  • 5,663
  • 1
  • 24
  • 34
-1

Java operators

| is bitwise or, || is logical or.

diciu
  • 29,133
  • 4
  • 51
  • 68
-1

Take a look at:

http://java.sun.com/docs/books/tutorial/java/nutsandbolts/operators.html

| is bitwise inclusive OR

|| is logical OR

Jeremy
  • 2,870
  • 3
  • 23
  • 31
-2

| is a bitwise operator. || is a logical operator.

One will take two bits and or them.

One will determine truth (this OR that) If this is true or that is true, then the answer is true.

Oh, and dang people answer these questions fast.

scubabbl
  • 12,657
  • 7
  • 36
  • 36