& vs | in java, which one should be used and when? [duplicate] - java

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

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.

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.

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.

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.

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

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

& 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).

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!

&& ; || 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,

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

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:
Evaluating some of the expressions is time consuming
Evaluating one of the expression can be done only if the previous one was true
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.

Related

I am working on a Android Studio weather app, and I keep getting the following error: NullPointerException [duplicate]

I always thought that && operator in Java is used for verifying whether both its boolean operands are true, and the & operator is used to do Bit-wise operations on two integer types.
Recently I came to know that & operator can also be used verify whether both its boolean operands are true, the only difference being that it checks the RHS operand even if the LHS operand is false.
Is the & operator in Java internally overloaded? Or is there some other concept behind this?
& <-- verifies both operands
&& <-- stops evaluating if the first operand evaluates to false since the result will be false
(x != 0) & (1/x > 1) <-- this means evaluate (x != 0) then evaluate (1/x > 1) then do the &. the problem is that for x=0 this will throw an exception.
(x != 0) && (1/x > 1) <-- this means evaluate (x != 0) and only if this is true then evaluate (1/x > 1) so if you have x=0 then this is perfectly safe and won't throw any exception if (x != 0) evaluates to false the whole thing directly evaluates to false without evaluating the (1/x > 1).
EDIT:
exprA | exprB <-- this means evaluate exprA then evaluate exprB then do the |.
exprA || exprB <-- this means evaluate exprA and only if this is false then evaluate exprB and do the ||.
Besides not being a lazy evaluator by evaluating both operands, I think the main characteristics of bitwise operators compare each bytes of operands like in the following example:
int a = 4;
int b = 7;
System.out.println(a & b); // prints 4
//meaning in an 32 bit system
// 00000000 00000000 00000000 00000100
// 00000000 00000000 00000000 00000111
// ===================================
// 00000000 00000000 00000000 00000100
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
It depends on the type of the arguments...
For integer arguments, the single ampersand ("&")is the "bit-wise AND" operator. The double ampersand ("&&") is not defined for anything but two boolean arguments.
For boolean arguments, the single ampersand constitutes the (unconditional) "logical AND" operator while the double ampersand ("&&") is the "conditional logical AND" operator. That is to say that the single ampersand always evaluates both arguments whereas the double ampersand will only evaluate the second argument if the first argument is true.
For all other argument types and combinations, a compile-time error should occur.
&& is a short circuit operator whereas & is a AND operator.
Try this.
String s = null;
boolean b = false & s.isEmpty(); // NullPointerException
boolean sb = false && s.isEmpty(); // sb is false
I think my answer can be more understandable:
There are two differences between & and &&.
If they use as logical AND
& and && can be logical AND, when the & or && left and right expression result all is true, the whole operation result can be true.
when & and && as logical AND, there is a difference:
when use && as logical AND, if the left expression result is false, the right expression will not execute.
Take the example :
String str = null;
if(str!=null && !str.equals("")){ // the right expression will not execute
}
If using &:
String str = null;
if(str!=null & !str.equals("")){ // the right expression will execute, and throw the NullPointerException
}
An other more example:
int x = 0;
int y = 2;
if(x==0 & ++y>2){
System.out.print(“y=”+y); // print is: y=3
}
int x = 0;
int y = 2;
if(x==0 && ++y>2){
System.out.print(“y=”+y); // print is: y=2
}
& can be used as bit operator
& can be used as Bitwise AND operator, && can not.
The bitwise AND " &" operator produces 1 if and only if both of the bits in
its operands are 1. However, if both of the bits are 0 or both of the bits are different then this operator produces 0. To be more precise bitwise AND " &" operator returns 1 if any of the two bits is 1 and it returns 0 if any of the bits is 0. 
From the wiki page:
http://www.roseindia.net/java/master-java/java-bitwise-and.shtml
it's as specified in the JLS (15.22.2):
When both operands of a &, ^, or | operator are of type boolean or Boolean, then the type of the bitwise operator expression is boolean. In all cases, the operands are subject to unboxing conversion (§5.1.8) as necessary.
For &, the result value is true if both operand values are true; otherwise, the result is false.
For ^, the result value is true if the operand values are different; otherwise, the result is false.
For |, the result value is false if both operand values are false; otherwise, the result is true.
The "trick" is that & is an Integer Bitwise Operator as well as an Boolean Logical Operator. So why not, seeing this as an example for operator overloading is reasonable.
‘&&’ : - is a Logical AND operator produce a boolean value of true or false based on the logical relationship of its arguments.
For example: - Condition1 && Condition2
If Condition1 is false, then (Condition1 && Condition2) will always be false, that is the reason why this logical operator is also known as Short Circuit Operator because it does not evaluate another condition. If Condition1 is false , then there is no need to evaluate Condtiton2.
If Condition1 is true, then Condition2 is evaluated, if it is true then overall result will be true else it will be false.
‘&’ : - is a Bitwise AND Operator. It produces a one (1) in the output if both the input bits are one. Otherwise it produces zero (0).
For example:-
int a=12; // binary representation of 12 is 1100
int b=6; // binary representation of 6 is 0110
int c=(a & b); // binary representation of (12 & 6) is 0100
The value of c is 4.
for reference , refer this http://techno-terminal.blogspot.in/2015/11/difference-between-operator-and-operator.html
&& and || are called short circuit operators. When they are used, for || - if the first operand evaluates to true, then the rest of the operands are not evaluated. For && - if the first operand evaluates to false, the rest of them don't get evaluated at all.
so if (a || (++x > 0)) in this example the variable x won't get incremented if a was true.
With booleans, there is no output difference between the two. You can swap && and & or || and | and it will never change the result of your expression.
The difference lies behind the scene where the information is being processed. When you right an expression "(a != 0) & ( b != 0)" for a= 0 and b = 1, The following happens:
left side: a != 0 --> false
right side: b 1= 0 --> true
left side and right side are both true? --> false
expression returns false
When you write an expression (a != 0) && ( b != 0) when a= 0 and b = 1, the following happens:
a != 0 -->false
expression returns false
Less steps, less processing, better coding, especially when doing many boolean expression or complicated arguments.
Besides && and || being short circuiting, also consider operator precedence when mixing the two forms.
I think it will not be immediately apparent to everybody that result1 and result2 contain different values.
boolean a = true;
boolean b = false;
boolean c = false;
boolean result1 = a || b && c; //is true; evaluated as a || (b && c)
boolean result2 = a | b && c; //is false; evaluated as (a | b) && c
& is a bitwise operator plus used for checking both conditions because sometimes we need to evaluate both condition.
But && logical operator go to 2nd condition when first condition give true.
all answers are great, and it seems that no more answer is needed
but I just wonted to point out something about && operator called dependent condition
In expressions using operator &&, a condition—we’ll call this the dependent condition—may require another condition to be true for the evaluation of the dependent condition to be meaningful.
In this case, the dependent condition should be placed after the && operator to prevent errors.
Consider the expression (i != 0) && (10 / i == 2). The dependent condition (10 / i == 2) must appear after the && operator to prevent the possibility of division by zero.
another example (myObject != null) && (myObject.getValue() == somevaluse)
and another thing: && and || are called short-circuit evaluation because the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression
References: Java™ How To Program (Early Objects), Tenth Edition
In respect of the AND and OR operators, Java has got two types of evaluation namely Short-Circuit evaluation and full evaluation.
&& || Short-Circuit Evaluation
Short-Circuit evaluation enables you to not evaluate the right-hand side of AND and OR expressions, when the overall result can be predicted from the left-side value.
int numberOne = 1;
int numberTwo = 2;
boolean result = false;
// left-side is false so the the overall result CAN be predicted without evaluating the right side.
// numberOne will be 1, numberTwo will be 2, result will be false
result = (numberOne > numberTwo) && (++numberOne == numberTwo);
System.out.println(numberOne); // prints 1
System.out.println(numberTwo); // prints 2
System.out.println(result); // prints false
// left-side is true so the the overall result CAN NOT be predicted without evaluating the right side.
// numberOne will be 2, numberTwo will be 2, result will be true
result = (numberTwo > numberOne) && (++numberOne == numberTwo);
System.out.println(numberOne); // prints 2
System.out.println(numberTwo); // prints 2
System.out.println(result); // prints true
& | ^ Full Evaluation
Although in some cases it is possible to predict the result, It is necessary to evaluate the right-hand side.
int numberOne = 1;
int numberTwo = 2;
boolean result = false;
// left-side is false so the the overall result will be false BUT the right side MUST be evaluated too.
// numberOne will be 2, numberTwo will be 2, result will be false
result = (numberOne > numberTwo) & (++numberOne == numberTwo);
System.out.println(numberOne); // prints 2
System.out.println(numberTwo); // prints 2
System.out.println(result); // prints false
Notice:
Notice that for XOR (^) there is no short-circuit, because both sides are always required to determine the overall result.
Notice that other possible names for Short-Circuit evaluation are minimal evaluation and McCarthy evaluation.
It is not recommenced to mix boolean logic and actions in the same expression
& can also act as a Bitwise AND operator which is very academic and can be used in cryptography. When both bits are 1, the result is 1, or either of the bits is not 1, the result is 0. (Check the following code)
AND Bitwise example:
byte a = 5; // 00000101
byte b = 3; // 00000011
byte c = (byte) (a & b); // 00000001 (c is 1)
Almost every point of comparison is very well covered in all the answers. I just want to add one example. To demonstrate how the output changes based on which operator we use. Consider the below example
int a = 10;
if(++a==10 & ++a==12) {
++a;
}
System.out.println(a); //12
In the above code, We are using bitwise & operator. So It will evaluate both the arguments(left and right) irrespective of the individual result.
so a will increment 2 times within if condition. But as the condition will not become true, It will not enter inside the if-loop and 3rd increment will not happen. So the final value of a would become 12 in this case.
Now suppose, in the same above example If we use short-circuit && operator. then after evaluating ++a==10 to false, It will not go to check the second argument. And Hence the final value of a would-be 11.
int a = 10;
if(++a==10 && ++a==12) {
++a;
}
System.out.println(a); //11
Based on this, We can say that performance of bitwise & operator is relatively low compare to the short-circuit && operator. As bitwise operator will go to evaluate both the arguments irrespective of the result of the first argument. While && operator will stop evaluating the second argument if the first argument's result is false.
One more difference between these two is, Bitwise & operator is applicable for boolean as well as integral types. While short-circuit && operator is applicable only for the boolean type.
We can write
System.out.println(4 & 5); // 4
But if We try to write like ,
System.out.println(4 && 5);
Then it will give an error saying,
bad operand types for binary operator '&&'

Java: boolean expression (x==y && a<b) [duplicate]

Which set is short-circuiting, and what exactly does it mean that the complex conditional expression is short-circuiting?
public static void main(String[] args) {
int x, y, z;
x = 10;
y = 20;
z = 30;
// T T
// T F
// F T
// F F
//SET A
boolean a = (x < z) && (x == x);
boolean b = (x < z) && (x == z);
boolean c = (x == z) && (x < z);
boolean d = (x == z) && (x > z);
//SET B
boolean aa = (x < z) & (x == x);
boolean bb = (x < z) & (x == z);
boolean cc = (x == z) & (x < z);
boolean dd = (x == z) & (x > z);
}
The && and || operators "short-circuit", meaning they don't evaluate the right-hand side if it isn't necessary.
The & and | operators, when used as logical operators, always evaluate both sides.
There is only one case of short-circuiting for each operator, and they are:
false && ... - it is not necessary to know what the right-hand side is because the result can only be false regardless of the value there
true || ... - it is not necessary to know what the right-hand side is because the result can only be true regardless of the value there
Let's compare the behaviour in a simple example:
public boolean longerThan(String input, int length) {
return input != null && input.length() > length;
}
public boolean longerThan(String input, int length) {
return input != null & input.length() > length;
}
The 2nd version uses the non-short-circuiting operator & and will throw a NullPointerException if input is null, but the 1st version will return false without an exception.
SET A uses short-circuiting boolean operators.
What 'short-circuiting' means in the context of boolean operators is that for a set of booleans b1, b2, ..., bn, the short circuit versions will cease evaluation as soon as the first of these booleans is true (||) or false (&&).
For example:
// 2 == 2 will never get evaluated because it is already clear from evaluating
// 1 != 1 that the result will be false.
(1 != 1) && (2 == 2)
// 2 != 2 will never get evaluated because it is already clear from evaluating
// 1 == 1 that the result will be true.
(1 == 1) || (2 != 2)
Short circuiting means the second operator will not be checked if the first operator decides the final outcome.
E.g. Expression is: True || False
In case of ||, all we need is one of the side to be True. So if the left hand side is true, there is no point in checking the right hand side, and hence that will not be checked at all.
Similarly, False && True
In case of &&, we need both sides to be True. So if the left hand side is False, there is no point in checking the right hand side, the answer has to be False. And hence that will not be checked at all.
boolean a = (x < z) && (x == x);
This kind will short-circuit, meaning if (x < z) evaluates to false then the latter is not evaluated, a will be false, otherwise && will also evaluate (x == x).
& is a bitwise operator, but also a boolean AND operator which does not short-circuit.
You can test them by something as follows (see how many times the method is called in each case):
public static boolean getFalse() {
System.out.println("Method");
return false;
}
public static void main(String[] args) {
if(getFalse() && getFalse()) { }
System.out.println("=============================");
if(getFalse() & getFalse()) { }
}
In plain terms, short-circuiting means stopping evaluation once you know that the answer can no longer change. For example, if you are evaluating a chain of logical ANDs and you discover a FALSE in the middle of that chain, you know the result is going to be false, no matter what are the values of the rest of the expressions in the chain. Same goes for a chain of ORs: once you discover a TRUE, you know the answer right away, and so you can skip evaluating the rest of the expressions.
You indicate to Java that you want short-circuiting by using && instead of & and || instead of |. The first set in your post is short-circuiting.
Note that this is more than an attempt at saving a few CPU cycles: in expressions like this
if (mystring != null && mystring.indexOf('+') > 0) {
...
}
short-circuiting means a difference between correct operation and a crash (in the case where mystring is null).
Java provides two interesting Boolean operators not found in most other computer languages. These secondary versions of AND and OR are known as short-circuit logical operators. As you can see from the preceding table, the OR operator results in true when A is true, no matter what B is.
Similarly, the AND operator results in false when A is false, no matter what B is. 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. This is very useful when the right-hand operand depends on the left one being true or false in order to function properly.
For example, the following code fragment shows how you can take advantage of short-circuit logical evaluation to be sure that a division operation will be valid before evaluating it:
if ( denom != 0 && num / denom >10)
Since the short-circuit form of AND (&&) is used, there is no risk of causing a run-time exception from dividing by zero. If this line of code were written using the single & version of AND, both sides would have to be evaluated, causing a run-time exception when denom is zero.
It is standard practice to use the short-circuit forms of AND and OR in cases involving Boolean logic, leaving the single-character versions exclusively for bitwise operations. However, there are exceptions to this rule. For example, consider the following statement:
if ( c==1 & e++ < 100 ) d = 100;
Here, using a single & ensures that the increment operation will be applied to e whether c is equal to 1 or not.
Logical OR :- returns true if at least one of the operands evaluate to true. Both operands are evaluated before apply the OR operator.
Short Circuit OR :- if left hand side operand returns true, it returns true without evaluating the right hand side operand.
There are a couple of differences between the & and && operators. The same differences apply to | and ||. The most important thing to keep in mind is that && is a logical operator that only applies to boolean operands, while & is a bitwise operator that applies to integer types as well as booleans.
With a logical operation, you can do short circuiting because in certain cases (like the first operand of && being false, or the first operand of || being true), you do not need to evaluate the rest of the expression. This is very useful for doing things like checking for null before accessing a filed or method, and checking for potential zeros before dividing by them. For a complex expression, each part of the expression is evaluated recursively in the same manner. For example, in the following case:
(7 == 8) || ((1 == 3) && (4 == 4))
Only the emphasized portions will evaluated. To compute the ||, first check if 7 == 8 is true. If it were, the right hand side would be skipped entirely. The right hand side only checks if 1 == 3 is false. Since it is, 4 == 4 does not need to be checked, and the whole expression evaluates to false. If the left hand side were true, e.g. 7 == 7 instead of 7 == 8, the entire right hand side would be skipped because the whole || expression would be true regardless.
With a bitwise operation, you need to evaluate all the operands because you are really just combining the bits. Booleans are effectively a one-bit integer in Java (regardless of how the internals work out), and it is just a coincidence that you can do short circuiting for bitwise operators in that one special case. The reason that you can not short-circuit a general integer & or | operation is that some bits may be on and some may be off in either operand. Something like 1 & 2 yields zero, but you have no way of knowing that without evaluating both operands.
if(demon!=0&& num/demon>10)
Since the short-circuit form of AND(&&) is used, there is no risk of causing a run-time exception when demon is zero.
Ref. Java 2 Fifth Edition by Herbert Schildt
Document from docs.oracle
As logical expressions are evaluated left to right, they are tested for possible “short-circuit” evaluation using these rules:
false && anything is short-circuit evaluated to false.
true || anything is short-circuit evaluated to true.
The rules of logic guarantee that these evaluations are always correct. Note that the anything part of the above expressions is not evaluated, so any side effects of doing so do not take effect.
https://docs.oracle.com/cd/E57185_01/HIRUG/ch31s05s01.html

Short - Circuit OR and OR [duplicate]

Which set is short-circuiting, and what exactly does it mean that the complex conditional expression is short-circuiting?
public static void main(String[] args) {
int x, y, z;
x = 10;
y = 20;
z = 30;
// T T
// T F
// F T
// F F
//SET A
boolean a = (x < z) && (x == x);
boolean b = (x < z) && (x == z);
boolean c = (x == z) && (x < z);
boolean d = (x == z) && (x > z);
//SET B
boolean aa = (x < z) & (x == x);
boolean bb = (x < z) & (x == z);
boolean cc = (x == z) & (x < z);
boolean dd = (x == z) & (x > z);
}
The && and || operators "short-circuit", meaning they don't evaluate the right-hand side if it isn't necessary.
The & and | operators, when used as logical operators, always evaluate both sides.
There is only one case of short-circuiting for each operator, and they are:
false && ... - it is not necessary to know what the right-hand side is because the result can only be false regardless of the value there
true || ... - it is not necessary to know what the right-hand side is because the result can only be true regardless of the value there
Let's compare the behaviour in a simple example:
public boolean longerThan(String input, int length) {
return input != null && input.length() > length;
}
public boolean longerThan(String input, int length) {
return input != null & input.length() > length;
}
The 2nd version uses the non-short-circuiting operator & and will throw a NullPointerException if input is null, but the 1st version will return false without an exception.
SET A uses short-circuiting boolean operators.
What 'short-circuiting' means in the context of boolean operators is that for a set of booleans b1, b2, ..., bn, the short circuit versions will cease evaluation as soon as the first of these booleans is true (||) or false (&&).
For example:
// 2 == 2 will never get evaluated because it is already clear from evaluating
// 1 != 1 that the result will be false.
(1 != 1) && (2 == 2)
// 2 != 2 will never get evaluated because it is already clear from evaluating
// 1 == 1 that the result will be true.
(1 == 1) || (2 != 2)
Short circuiting means the second operator will not be checked if the first operator decides the final outcome.
E.g. Expression is: True || False
In case of ||, all we need is one of the side to be True. So if the left hand side is true, there is no point in checking the right hand side, and hence that will not be checked at all.
Similarly, False && True
In case of &&, we need both sides to be True. So if the left hand side is False, there is no point in checking the right hand side, the answer has to be False. And hence that will not be checked at all.
boolean a = (x < z) && (x == x);
This kind will short-circuit, meaning if (x < z) evaluates to false then the latter is not evaluated, a will be false, otherwise && will also evaluate (x == x).
& is a bitwise operator, but also a boolean AND operator which does not short-circuit.
You can test them by something as follows (see how many times the method is called in each case):
public static boolean getFalse() {
System.out.println("Method");
return false;
}
public static void main(String[] args) {
if(getFalse() && getFalse()) { }
System.out.println("=============================");
if(getFalse() & getFalse()) { }
}
In plain terms, short-circuiting means stopping evaluation once you know that the answer can no longer change. For example, if you are evaluating a chain of logical ANDs and you discover a FALSE in the middle of that chain, you know the result is going to be false, no matter what are the values of the rest of the expressions in the chain. Same goes for a chain of ORs: once you discover a TRUE, you know the answer right away, and so you can skip evaluating the rest of the expressions.
You indicate to Java that you want short-circuiting by using && instead of & and || instead of |. The first set in your post is short-circuiting.
Note that this is more than an attempt at saving a few CPU cycles: in expressions like this
if (mystring != null && mystring.indexOf('+') > 0) {
...
}
short-circuiting means a difference between correct operation and a crash (in the case where mystring is null).
Java provides two interesting Boolean operators not found in most other computer languages. These secondary versions of AND and OR are known as short-circuit logical operators. As you can see from the preceding table, the OR operator results in true when A is true, no matter what B is.
Similarly, the AND operator results in false when A is false, no matter what B is. 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. This is very useful when the right-hand operand depends on the left one being true or false in order to function properly.
For example, the following code fragment shows how you can take advantage of short-circuit logical evaluation to be sure that a division operation will be valid before evaluating it:
if ( denom != 0 && num / denom >10)
Since the short-circuit form of AND (&&) is used, there is no risk of causing a run-time exception from dividing by zero. If this line of code were written using the single & version of AND, both sides would have to be evaluated, causing a run-time exception when denom is zero.
It is standard practice to use the short-circuit forms of AND and OR in cases involving Boolean logic, leaving the single-character versions exclusively for bitwise operations. However, there are exceptions to this rule. For example, consider the following statement:
if ( c==1 & e++ < 100 ) d = 100;
Here, using a single & ensures that the increment operation will be applied to e whether c is equal to 1 or not.
Logical OR :- returns true if at least one of the operands evaluate to true. Both operands are evaluated before apply the OR operator.
Short Circuit OR :- if left hand side operand returns true, it returns true without evaluating the right hand side operand.
There are a couple of differences between the & and && operators. The same differences apply to | and ||. The most important thing to keep in mind is that && is a logical operator that only applies to boolean operands, while & is a bitwise operator that applies to integer types as well as booleans.
With a logical operation, you can do short circuiting because in certain cases (like the first operand of && being false, or the first operand of || being true), you do not need to evaluate the rest of the expression. This is very useful for doing things like checking for null before accessing a filed or method, and checking for potential zeros before dividing by them. For a complex expression, each part of the expression is evaluated recursively in the same manner. For example, in the following case:
(7 == 8) || ((1 == 3) && (4 == 4))
Only the emphasized portions will evaluated. To compute the ||, first check if 7 == 8 is true. If it were, the right hand side would be skipped entirely. The right hand side only checks if 1 == 3 is false. Since it is, 4 == 4 does not need to be checked, and the whole expression evaluates to false. If the left hand side were true, e.g. 7 == 7 instead of 7 == 8, the entire right hand side would be skipped because the whole || expression would be true regardless.
With a bitwise operation, you need to evaluate all the operands because you are really just combining the bits. Booleans are effectively a one-bit integer in Java (regardless of how the internals work out), and it is just a coincidence that you can do short circuiting for bitwise operators in that one special case. The reason that you can not short-circuit a general integer & or | operation is that some bits may be on and some may be off in either operand. Something like 1 & 2 yields zero, but you have no way of knowing that without evaluating both operands.
if(demon!=0&& num/demon>10)
Since the short-circuit form of AND(&&) is used, there is no risk of causing a run-time exception when demon is zero.
Ref. Java 2 Fifth Edition by Herbert Schildt
Document from docs.oracle
As logical expressions are evaluated left to right, they are tested for possible “short-circuit” evaluation using these rules:
false && anything is short-circuit evaluated to false.
true || anything is short-circuit evaluated to true.
The rules of logic guarantee that these evaluations are always correct. Note that the anything part of the above expressions is not evaluated, so any side effects of doing so do not take effect.
https://docs.oracle.com/cd/E57185_01/HIRUG/ch31s05s01.html

Java code output differs: bitwise and boolean operators [duplicate]

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 &&.
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
| 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.
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.
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
...
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.
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.
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.
|| 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;
a | b: evaluate b in any case
a || b: evaluate b only if a evaluates to false
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.
| is the binary or operator
|| is the logic or operator
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.
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;
}
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 java, 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.
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;
}
}
|| 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
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.
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.
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
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.
| = bitwise or, || = logic or
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.
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.
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.
|| is a logical or and | is a bit-wise or.
Java operators
| is bitwise or, || is logical or.
Take a look at:
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/operators.html
| is bitwise inclusive OR
|| is logical OR
| 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.

Java | Operator

I have this question in my beginner Java programming class and I can't find in my book what a single '|' means as an operator.
The question is:
int j = 0;
if ((8 > 4) | (j++ == 7))
System.out.println("j = " + j);
Is j = 1?
Explain why.
The book explains the OR operator "||" with examples but it doesn't show this single "|". Does the meaning of the operator change between the two?
Yes, the meaning changes, || is the logical or operator, while | is the bitwise or.
Since this operator operates (...) at the bit level, it doesn't short circuit the same way as ||, meaning, even if the first operand is true, the second operand will be evaluated.
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.
Boolean b = true;
if(b || foo.test())
{
//we entered without calling test()
}
if(b | foo.test())
{
//we entered calling test()
}
| -> This is bit-wise OR operator performs a bitwise inclusive OR operation and perform the both operand(right and left).
The bitwise OR "|" operator produces 1 if either one or both of the
bits in its operands are 1. However, if both of the bits are 0 then
this operator produces 0. To be more precise OR "|" operator returns 1
in all cases except when both the bits of both the operands are 0.
if ((8 > 4) | (j++ == 7)) System.out.println("j = " + j);
Here 8>4 will return true and j++ == 7 will return false. so it will be if(true|false) and here bit-wise operator will return true or 1 and print value of j which became 1 after j++.
The | operator is bitwise OR, but you may ask why would someone use the bitwise OR on boolean variables?
Logical OR operator (||) has a feature called short-circuiting, which means that if the left operand evaluates to true, no further processing is done, and the right hand operand even will not evaluate. But bitwise OR operator | always evaluates both operands, and if applied on boolean operands, evaluates both of them and then applies a simple or on the results.
In your case, (j++ == 7) is always evaluated, regardless of the result of 8 > 4. This does not happen with || operator. So j will be incremented by one and the output of the program is 1.
The answer is No because j is initialized at 0 but is never assigned after this. So the value of j stays at 0 for the whole time.

Categories

Resources