124

I know the rules for && and || but what are & and |? Please explain these to me with an example.

Machavity
  • 30,841
  • 27
  • 92
  • 100
Sumithra
  • 6,587
  • 19
  • 51
  • 50
  • See this post of a great explanation: https://stackoverflow.com/questions/7101992/why-do-we-usually-use-over-what-is-the-difference – JavaGeek Sep 22 '21 at 02:19

11 Answers11

156

Those are the bitwise AND and bitwise OR operators.

int a = 6; // 110
int b = 4; // 100

// Bitwise AND    

int c = a & b;
//   110
// & 100
// -----
//   100

// Bitwise OR

int d = a | b;
//   110
// | 100
// -----
//   110

System.out.println(c); // 4
System.out.println(d); // 6

Thanks to Carlos for pointing out the appropriate section in the Java Language Spec (15.22.1, 15.22.2) regarding the different behaviors of the operator based on its inputs.

Indeed when both inputs are boolean, the operators are considered the Boolean Logical Operators and behave similar to the Conditional-And (&&) and Conditional-Or (||) operators except for the fact that they don't short-circuit so while the following is safe:

if((a != null) && (a.something == 3)){
}

This is not:

if((a != null) & (a.something == 3)){
}

"Short-circuiting" means the operator does not necessarily examine all conditions. In the above examples, && will examine the second condition only when a is not null (otherwise the whole statement will return false, and it would be moot to examine following conditions anyway), so the statement of a.something will not raise an exception, or is considered "safe."

The & operator always examines every condition in the clause, so in the examples above, a.something may be evaluated when a is in fact a null value, raising an exception.

Amongalen
  • 3,101
  • 14
  • 20
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
  • 1
    wanted to clarify.. & will return 1 only if BOTH are 1? So 101 & 001 would be 001? Right? – gideon Oct 25 '10 at 12:41
  • @giddy @Jonathon - I updated my values to better show that situation. – Justin Niessner Oct 25 '10 at 12:44
  • 1
    incomplete: they are also LOGICAL operators (for booleans). – user85421 Oct 25 '10 at 13:04
  • 1
    @Carlos- No. They're still bitwise operators. They just behave the same as non-short circuiting logical operators. There is a difference. – Justin Niessner Oct 25 '10 at 13:05
  • 4
    and what are the non-short circuiting logical operators? The operators & and | (asked by OP) are "Integer Bitwise Operators" (JLS 15.22.1) **and** "Boolean Logical Operators" (JLS 15.22.2). Or is the Java Language Specification wrong about that? – user85421 Oct 25 '10 at 20:29
  • @Carlos - Good call. Thanks for pointing out the appropriate spot in the specification. I updated my answer. – Justin Niessner Oct 26 '10 at 12:21
  • You can improve the answer further by illuminating on "this is safe" and "this is not safe." It's better to have a method call (which will have a "side affect") instead of accessing a property to show the later could be unsafe. – Jaywalker Oct 26 '10 at 12:26
  • The spec link is broken with the move to Oracle. The new links are around http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.22.2. I second @Jaywalker s remark. && can be unsafe if the expression after the && is an operation you would like to be executed in any case. Some clarification would be helpful. – Chris Dec 28 '12 at 14:53
116

I think you're talking about the logical meaning of both operators, here you have a table-resume:

boolean a, b;

Operation     Meaning                       Note
---------     -------                       ----
   a && b     logical AND                    short-circuiting
   a || b     logical OR                     short-circuiting
   a &  b     boolean logical AND            not short-circuiting
   a |  b     boolean logical OR             not short-circuiting
   a ^  b     boolean logical exclusive OR
  !a          logical NOT

short-circuiting        (x != 0) && (1/x > 1)   SAFE
not short-circuiting    (x != 0) &  (1/x > 1)   NOT SAFE

Short-circuit evaluation, minimal evaluation, or McCarthy evaluation (after John McCarthy) is the semantics of some Boolean operators in some programming languages in which the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression: when the first argument of the AND function evaluates to false, the overall value must be false; and when the first argument of the OR function evaluates to true, the overall value must be true.

Not Safe means the operator always examines every condition in the clause, so in the examples above, 1/x may be evaluated when the x is, in fact, a 0 value, raising an exception.

Torres
  • 5,330
  • 4
  • 26
  • 26
  • 1
    @Torres - Please expand your answer by explaining "short circuiting" and "safe". Also is "exclusive or" and "logical not" also "not short-circuiting"? And why is it called "logical not" instead of "boolean logical not"? And why is the "logical NOT" not grouped with the "logical AND" and "logical OR"? Good answer but needs work. – tim-montague Nov 03 '17 at 21:38
  • @tfmontague, I have explained what short circuiting means (by editing this answer).. Waiting for my edit to be "peer reviewed". – Taslim Oseni Dec 17 '17 at 15:24
  • what is "unsafe" about not short-circuiting? shouldn't it be more safe than using short-circuits? btw: you don't really explain the "short-circuit" term. it means that on "not short-circuit" all parts are first evaluated, then the boolean operation is applied, while on short-circuit the evaluation is stopped, when the first expression satisfies the condition, like (a || b) will not evaluate b, if a is true and the or operation will return true, no matter what b is. – SCI Jun 07 '18 at 07:25
32

I know there's a lot of answers here, but they all seem a bit confusing. So after doing some research from the Java oracle study guide, I've come up with three different scenarios of when to use && or &. The three scenarios are logical AND, bitwise AND, and boolean AND.

Logical AND: Logical AND (aka Conditional AND) uses the && operator. It's short-circuited meaning: if the left operand is false, then the right operand will not be evaluated.
Example:

int x = 0;
if (false && (1 == ++x) {
    System.out.println("Inside of if");
}
System.out.println(x); // "0"

In the above example the value printed to the console of x will be 0, because the first operand in the if statement is false, hence java has no need to compute (1 == ++x) therefore x will not be computed.

Bitwise AND: Bitwise AND uses the & operator. It's used to preform a bitwise operation on the value. It's much easier to see what's going on by looking at operation on binary numbers ex:

int a = 5;     //                    5 in binary is 0101
int b = 12;    //                   12 in binary is 1100
int c = a & b; // bitwise & preformed on a and b is 0100 which is 4

As you can see in the example, when the binary representations of the numbers 5 and 12 are lined up, then a bitwise AND preformed will only produce a binary number where the same digit in both numbers have a 1. Hence 0101 & 1100 == 0100. Which in decimal is 5 & 12 == 4.

Boolean AND: Now the boolean AND operator behaves similarly and differently to both the bitwise AND and logical AND. I like to think of it as preforming a bitwise AND between two boolean values (or bits), therefore it uses & operator. The boolean values can be the result of a logical expression too.

It returns either a true or false value, much like the logical AND, but unlike the logical AND it is not short-circuited. The reason being, is that for it to preform that bitwise AND, it must know the value of both left and right operands. Here's an ex:

int x = 0;
if (false & (1 == ++x) {
    System.out.println("Inside of if");
}
System.out.println(x); //"1"

Now when that if statement is ran, the expression (1 == ++x) will be executed, even though the left operand is false. Hence the value printed out for x will be 1 because it got incremented.

This also applies to Logical OR (||), bitwise OR (|), and boolean OR (|) Hope this clears up some confusion.

J...S
  • 5,079
  • 1
  • 20
  • 35
  • `to preform that bitwise AND, it must know the value of both left and right operands` This does not sound right to me. To perform a `BITWISE AND` you do not need to know the right operand to be able to figure out the outcome if the left operand is `FALSE`. What you explain is correct, but the reasoning you state does not seem so, to me at least.. – Koray Tugay Feb 04 '18 at 08:55
7

The operators && and || are short-circuiting, meaning they will not evaluate their right-hand expression if the value of the left-hand expression is enough to determine the result.

Tassos Bassoukos
  • 16,017
  • 2
  • 36
  • 40
5

& and | provide the same outcome as the && and || operators. The difference is that they always evaluate both sides of the expression where as && and || stop evaluating if the first condition is enough to determine the outcome.

Brian Scott
  • 9,221
  • 6
  • 47
  • 68
  • 1
    Wrong.... For `&&` it evaluates both outcomes while `||` returns only if the first condition is true. – Buhake Sindi Oct 25 '10 at 12:56
  • 1
    Huh? The && only evaluates the right hand side of the expression if the left hand side already evaluates to true. Otherwise it stops evaluating as the first false implictly means that the outcome cannot be true. See http://www.jguru.com/faq/view.jsp?EID=16530 – Brian Scott Oct 25 '10 at 13:10
  • 1
    `( 2 & 4 )` evaluates to `false`, whereas `( 2 && 4 )` evaluates to `true`. How exactly is that the same outcome? – Piskvor left the building Oct 25 '10 at 13:21
  • 1
    @Piskvor - not in Java! `2 & 4` results in an integer, not a boolean (zero in this case). `2 && 4` will not compile, && only accept booleans. Java does not allow mixing booleans and ints: zero is not `false`, `false` is not zero... – user85421 Oct 25 '10 at 20:43
  • @Brian Scott: if you had qualified your answer with *for booleans* as added by KarlP, it would be a very good answer. I still upvoted it to balance the unjustified downvotes. – Sean Patrick Floyd Oct 26 '10 at 08:54
  • 1
    @BuhakeSindi Wrong. For `&&` it only evaluates the second operand if the first operand is `true`. – user207421 Sep 26 '16 at 00:24
3

In Java, the single operators &, |, ^, ! depend on the operands. If both operands are ints, then a bitwise operation is performed. If both are booleans, a "logical" operation is performed.

If both operands mismatch, a compile time error is thrown.

The double operators &&, || behave similarly to their single counterparts, but both operands must be conditional expressions, for example:

if (( a < 0 ) && ( b < 0 )) { ... } or similarly, if (( a < 0 ) || ( b < 0 )) { ... }

source: java programming lang 4th ed

aaron p.
  • 17
  • 2
1

Maybe it can be useful to know that the bitwise AND and bitwise OR operators are always evaluated before conditional AND and conditional OR used in the same expression.

if ( (1>2) && (2>1) | true) // false!
user207421
  • 305,947
  • 44
  • 307
  • 483
alexmeia
  • 5,241
  • 4
  • 24
  • 24
  • 1
    do you mean operator priority rather than evaluation order? I would rather not see the priority difference used in real code. Use parentheses rather than bitwise operators for this purpose. – John Dvorak Sep 04 '13 at 08:16
1

&& ; || are logical operators.... short circuit

& ; | are boolean logical operators.... Non-short circuit

Moving to differences in execution on expressions. Bitwise operators evaluate both sides irrespective of the result of left hand side. But in the case of evaluating expressions with logical operators, the evaluation of the right hand expression is dependent on the left hand condition.

For Example:

int i = 25;
int j = 25;
if(i++ < 0 && j++ > 0)
    System.out.println("OK");
System.out.printf("i = %d ; j = %d",i,j);

This will print i=26 ; j=25, As the first condition is false the right hand condition is bypassed as the result is false anyways irrespective of the right hand side condition.(short circuit)

int i = 25;
int j = 25;
if(i++ < 0 & j++ > 0)
    System.out.println("OK");
System.out.printf("i = %d ; j = %d",i,j);

But, this will print i=26; j=26,

Nickhil
  • 1,267
  • 10
  • 11
1

& and | are bitwise operators on integral types (e.g. int): http://download.oracle.com/javase/tutorial/java/nutsandbolts/op3.html

&& and || operate on booleans only (and short-circuit, as other answers have already said).

Bruno
  • 119,590
  • 31
  • 270
  • 376
0

If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand.

When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand evaluates to false, the evaluation of the second operand is skipped.

If the first operand returns a value of true then the second operand is evaluated. If the second operand returns a value of true then && operator is then applied to the first and second operands.

Similar for | and ||.

RishiKesh Pathak
  • 2,122
  • 1
  • 18
  • 24
0

While the basic difference is that & is used for bitwise operations mostly on long, int or byte where it can be used for kind of a mask, the results can differ even if you use it instead of logical &&.

The difference is more noticeable in some scenarios:

  1. Evaluating some of the expressions is time consuming
  2. Evaluating one of the expression can be done only if the previous one was true
  3. The expressions have some side-effect (intended or not)

First point is quite straightforward, it causes no bugs, but it takes more time. If you have several different checks in one conditional statements, put those that are either cheaper or more likely to fail to the left.

For second point, see this example:

if ((a != null) & (a.isEmpty()))

This fails for null, as evaluating the second expression produces a NullPointerException. Logical operator && is lazy, if left operand is false, the result is false no matter what right operand is.

Example for the third point -- let's say we have an app that uses DB without any triggers or cascades. Before we remove a Building object, we must change a Department object's building to another one. Let's also say the operation status is returned as a boolean (true = success). Then:

if (departmentDao.update(department, newBuilding) & buildingDao.remove(building))

This evaluates both expressions and thus performs building removal even if the department update failed for some reason. With &&, it works as intended and it stops after first failure.

As for a || b, it is equivalent of !(!a && !b), it stops if a is true, no more explanation needed.

Vlasec
  • 5,500
  • 3
  • 27
  • 30