0

I understand the difference between && and &, and || and |. But what about | and &, don't they do the same thing?


I mean, won't these two if be statements the same?

if (a | !b)
  //Code here
if (a & !b)
  //Code here

|| says only if boolean 1 is false, then try boolean 2.

&& says only if boolean 1 is true, then try boolean 2.


However, according my information,:

& says even if boolean 1 is false or true, evaluate the next statement.

| says even if boolean 1 is false or true, evaluate the next statement.


Am I incorrect? If not, are there any other differences between & and |? All I've found by research was the difference between && and || and I couldn't find anything else.

Ali Bdeir
  • 4,151
  • 10
  • 57
  • 117
  • You are not incorrect that `&` and `|` evaluate both operands unconditionally, but clearly `if (a | !b)` is not the same as `if (a & !b)`: if both `a` and `b` are `true`, then `a | !b == true`, and `a & !b == false`. – Andy Turner Aug 04 '16 at 19:31
  • @NikolasCharalambidis Did you read my question? I specifically said ***"All I've found by research was the difference between && and || and I couldn't find anything else."*** – Ali Bdeir Aug 04 '16 at 19:32
  • 1
    And that post explains that the differences are BITWISE vs BOOLEAN as well as the short-circuiting – OneCricketeer Aug 04 '16 at 19:33
  • @cricket_007 Ah, Sorry. Well the title is certainly confusing, I thought that was && vs & and || vs | – Ali Bdeir Aug 04 '16 at 19:35
  • [This post](http://stackoverflow.com/questions/7101992/why-do-we-usually-use-not-what-is-the-difference) has some decent information about `|` and `&` as boolean operators – jonhopkins Aug 04 '16 at 19:35
  • You can read the [**JLS 15.22.2**](http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.22.2) for the answer you are looking for – OneCricketeer Aug 04 '16 at 19:37
  • OK, I got extremely confused. Lets say I have `if(true | true)`, will it pass? And if I have `if(false | false)`, will it pass? Why? Can someone give me a decent example of when they differ? (@AndyTurner 's example is good, but I got mixed up too) – Ali Bdeir Aug 04 '16 at 19:48
  • @AbAppletic `true | true == true`, `false | false == false`. – Andy Turner Aug 04 '16 at 19:59
  • @AndyTurner And if we use this with `&`, then `true | true == false` and vise versa? – Ali Bdeir Aug 04 '16 at 20:06
  • @AbAppletic No. `true | true == true`, that's the only value it ever has. `true & true == true` also, but that's a different operator. This is just basic boolean arithmetic. – Andy Turner Aug 04 '16 at 20:08
  • And can you explain `true | false` and `true & false`? Sorry, I get confused too quickly... I'm just trying to understand something stupid and I can't get it, sorry – Ali Bdeir Aug 04 '16 at 20:08

0 Answers0