sequence of actions in the logical expression - java

I want to ask about correct sequence "reading" of this logical expression:
(true && false | true)
I thought it returns false, because of first expression - true && false
But probably I'm doing something wrong and it's should be "reading" another way.
Can you explain what's correct way to reading it?

By keeping below the point in the notice:
All binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated right to left.
This will be get executed from left to right. After that 2nd point to consider is Operator Precedence.
| is a bitwise operator and && is a logical operation. the bitwise operator has more priority than the logical operator.
In your case, the first evaluation will be false | true which is true.
then it will evaluate the true && result of above which is true.
so the given statement will be true.

Check the following table of Operators Precedence.
| (bitwise inclusive OR) has higher precedence than && (logical AND), so false | true is evaluated first.
That said, the evaluation order doesn't matter in your example. Both (true && false) | true and true && (false | true) return true. In the first case it's false | true), which is true. In the second case it's true && true, which is also true.
Now, here's an example where the operator precedence makes a difference:
System.out.println (false && true | true);
System.out.println (false && true || true);
| has a higher precedence than &&, but && has a higher precedence than ||.
Therefore these expressions are evaluated as:
System.out.println (false && (true | true));
System.out.println ((false && true) || true);
As a result, the first returns false and the second returns true.

Related

Java: Short-circuting && after OR

I understand && and || are short circuited in Java (whereas & and | are not)
However, I do not understand why the following code (which starts off with short circuited OR but ends with && condition) is also short circuited:
String x, y;
if ( x.contains("this") || x.contains("that") && y.contains("something else")!= true)
I would think that even if condition x.contains("this") evaluates to true the program will still need to evaluate the last condition y.contains("something else") != true because there's the && operator before the last condition. But apparently this isn't the case.
Can anyone explain why?
Two factors are in play here to determine the order of evaluation:
Operation precedence, and
Short-circuiting rules
Since && has higher precedence than ||, operator && "stays closer to its operands", so your expression is parsed as follows:
Because both && and || operators are left-to-right associative*, Java evaluates this expression left-to-right, stopping as soon as it determines the outcome. In case the string contains "this" substring, evaluation stops without evaluating the &&.
Note: If you are not sure of the order of operations, you can always force the order that you want by parenthesizing parts of your predicate. If the expression is not entirely obvious to you, good chances are that it is going to be non-obvious to other readers, so adding some extra parentheses is a good idea.
* Some operators are right-to-left associative. For example, assignment operator a[i] = b + c evaluates b + c before evaluating a[i]. Thanks T.J. Crowder for a great comment.
This is because of operator precedence.
The equivalent form of your (a || b && c) is (a || (b && c))
Cf. https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
...even if condition x.contains("this") evaluates to true the program will still need to evaluate the last condition y.contains("something else") != true...
Nope. :-) The operands to the || in that expression are
x.contains("this")
and
x.contains("that") && y.contains("something else")!= true
...because && has higher precedence than || (details). So if you have a || b && c, it's a || (b && c) (just like a + b * c is a + (b * c) rather than (a + b) * c). The precedence defines how the operands are grouped.
If you want the expression grouped differently, you can use () to group it.
if ( (x.contains("this") || x.contains("that")) && y.contains("something else")!= true)
It has to do with operator precedence. Most standard operators are binary, that is they take two inputs and produce an output. Whenever you have an expression with more than two operators, the compiler uses precedence and associativity rules to figure out how to transform that expression into one where it's clear what inputs each operations has.
In your case, you have an expression like A || B && C. && has higher precedence than ||, so the compiler will interpret it as A || (B && C), not like (A || B) && C, which you might get at by just looking at the expression.
This means that it's enough for A to be true for the whole expression to be true.
This is the way the syntax works in java as the && operations are grouped before the || opertaion, therefore when it reads the equation (A || B && C) it only see's comparing A || D (where D is really B && C). So when A is evaluated as True, it doesn't even need to evaluate B && C.
Refer to this link for further syntax related questions on the order of operations
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
&& is an operator with a higher precedence than ||.
Operators with higher precedence are evaluated before operators with lower precedence.
So here :
if ( x.contains("this") || x.contains("that") && y.contains("something else")!= true)
These two expressions are evaluated together :
x.contains("that") && y.contains("something else")!= true
So you get a conditional statement with a form such as :
if (something || somethingElse)
something is true, so somethingElse is never evaluated.
And the whole conditional statement is true.
Java have some operator precedence. You need to understand it to work with it.
First of all
In your if statement, you have two logical operators: || and &&.You know about short circuited. But you need to know that the &&operator will run first than ||.
AND operator (&&)
The && operator will, first, verify the left condition. There's no need to check two of them, to && return true, if the first one is true, then he can check the second.
OR operator (||)
The || operator will execute right after &&. It will verify if the two conditions return false, for this reason he needs to verify both.
Parentheses
You should know, but to make it work the way you want, you need to use parentheses (). To do it in the way you need, use () to present a new rule to your if statement:
if ( (x.contains("this") || x.contains("that")) && y.contains("something else")!= true)

SOS for Java boolean statement

Why this boolean statement is true?
a= 10;
b = 0;
7 < a || a == b && b > 9 - a / b
Since anything divided by 0 is error
Since the first operand of the OR (||) operator (a > 7) evaluates to true, it short circuits and nothing else is evaluated. Therefore the entire expression evaluates to true.
7 < a returns true. Since it's a || after, the rest isn't executed.
This is because true || false is true, and true || true is true too, so evaluing the second member is but a waste of time.
Your OR-Operator || uses lazy evaluation or short-circuit evaluation. This means, since the very first expression 7 < ais true, it won't evaluate any other statements including the one with a division by zero, since java already found something true.
If you actually want to get an error, you can use this OR-Operator | which should enforce the evaluation of all statements. Most only use it as a bitwise-operator, but its also a non-short-circuit version of ||. For a more in-depth look at || vs. |, look here.
For example,
boolean c = (7 < a | a == b && b > 9 - a / b);
will cause an ArithmeticExcption, as expected.

Confusing example about '&&' and '||' precedence

I was testing the precedence between && and || and I had an example that was confusing. In Java, && has higher operator precedence than the operator ||.
So if we have those 3 expressions:
//expr1 = true , expr2 = false; expr3 = false;
if(expr1 || expr2 && expr3);
It should be evaluated as:
if(expr1 || (expr2 && expr3));
So expr2 && expr3 should be evaluated before expr1. However, this example:
int a1 = 10;
int a2 = 20;
System.out.println(a1 < a2 || ++a1 > a2 && ++a2 < a1);
System.out.println(a1);
System.out.println(a2);
Outputs:
true
10
20
That proves that only a1 < a2 is evaluated.
Can you explain why this is the case?
The expression is short-circuiting. From the link:
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.
It sees that the rest of the condition doesn't matter because one of the operands of || is already true (10 < 20). If one of the operands is true, then no matter what the rest of the condition is, it's true.
You may use bitwise & and | to prevent this.
But, the ( expr2 && expr3 ) should be evaluated before expr1, no ?
No. You have to separate concepts of precedence and evaluation order.
Precedence: Dictates the parenthesization of an expression, not the order in which an expression is evaluated. For an example:
true || false && false
Is parenthesized to this because && has higher precedence than ||:
true || (false && false)
This does not mean that things in parentheses is evaluated first in Java's case. Precedence just clarifies what the operands of an operator are, in this case false and false, where as in this case:
(true || false) && (false || false)
The operands for && are true and false, not false and false.
Evaluation Order: Describes in what order each operand is evaluated and operator is applied and is sometimes language specific. This dictates how an expression is evaluated, unlike precedence.
In this case, your example:
true || false && false
As established earlier, becomes this due to precedence:
true || (false && false)
But Java, unlike C++, JavaScript, or a number of other languages has a strictly left to right evaluation. Per the Java Language Specification:
15.7. Evaluation Order
The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.
15.7.1. Evaluate Left-Hand Operand First
The left-hand operand of a binary operator appears to be fully evaluated before any part of the right-hand operand is evaluated.
So, when you have:
true || (false && false)
Java first evaluates the left operand which turns out to be true. Then the whole condition short circuits. The right operand of || in the parentheses is never evaluated at all. The same goes for your other example:
a1 < a2 || (++a1 > a2 && ++a2 < a1)
^^^^^^^^^^^^^^^^^^^^^^^^
Step 0, precedence and parenthesization
a1 < a2 || (++a1 > a2 && ++a2 < a1)
^^^^^^^
Step 1, left operand evaluated, variables resolved to values 10 and 20, condition is true
true || (++a1 > a2 && ++a2 < a1)
^^^^
Step 2, short circuits, left operand is not evaluated
Take another more complex example:
false || false || true && (false || true) || false
Due to precedence, it becomes:
false || false || (true && (false || true)) || false
Then, evaluation begins, left to right:
false || false || (true && (false || true)) || false
^^^^^^^^^^^^^^
Step 1, false || false, does not short circuit, right operand is evaluated, is false
false || (true && (false || true)) || false
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Step 2, false || (true && (false || true)), does not short circuit, right operand is evaluated
Step 2A, (true && (false || true)), does not short circuit, right operand is evaluated
Step 2B, (false || true), does not short circuit, right operand is evaluated, is true
Step 2C, (true && true), does not short circuit, right operand is evaluated, is true
Step 2D, false || true, does not short circuit, right operand is evaluated, is true
true || false
^^^^
Step 3, true || false short circuits, right operand is not evaluated, is true
Thus the whole expression evaluates to true. The whole expression was evaluated left to right the whole way through. Precedence only dictated the operands of an operator via parenthesization, not the evaluation order.
Further reading at Eric Lippert's explanatory article on precedence vs associativity vs evaluation order as mentioned by Daniel Pryden, it clears up a lot of the confusion.
The main takeaway is that precedence does not dictate in what an expression is evaluated. It only dictates how an expression should be parenthesized. Evaluation order, on the other hand, tells us exactly how an expression is evaluated, and in Java's case is always left to right.
The first line prints true because of short-circuiting the || operator.
a1 < a2 is true and so the rest of the boolean expression doesn't need to be evaluated and true is returned.
expr2 should be evaluated before expr1
is incorrect, as operator precedence affects the structure of the expression, rather then the evaluation order (in most cases). If you were to re-order the expression so that it was (expr2 && expr3) || expr1, then yes, expr2 would be evaluated before expr1
Precedence:
boolean result = a || b && c
In order to have the correct value according to the rules of precedence, the compiler must logically evaluate this as:
boolean x = b && c
boolean result = a || x
This speaks to your point that b && c must be evaluated before result can be calculated. However, in Boolean algebra, it is possible to write expressions whose results do not depend on all the operands. This fact is exploited to enable a compiler optimization called short circuiting.
Short Circuiting:
For any Boolean expression:
a || b
the result does not depend on b if a evaluates to true. When a is true, it does not matter if b evaluates to true or false. Because of this, the compiler executes:
a || b && c
as if it had been written:
boolean result = a;
if (!a) result = b && c;
Note that executed this way, the rules of precedence are still respected. The expression is not evaluated as (a || b) && c. Since the overall result of the expression does not depend on (b && c) in the case where a is true, b && c is simply never evaluated.
This is a good thing. Short circuiting allows you to write correct programs when the correctness of one operand depends on the correctness of another. For example:
if (myString == null || !myString.isEmpty() && myString != "break") return;
Without short circuit evaluation, the boolean expression could throw a NullPointerException. However, because of short circuit evaluation, this expression, as written, can never throw a NullPointerException.
Short circuiting can also be used as a performance optimization. If evaluating one operand is extremely expensive, evaluating another first can save the execution time needed to evaluate an operand whose value does not influence the final result of the whole expression.
Even when you use explicit parentheses as in
if (expr1 || (expr2 && expr3))
expr1 is evaluated first, since the operands of operators are evaluated from left to right. Since || is a short circuited operator, the second operand ((expr2 && expr3) in your case) will only be evaluated if expr1 is false.
When you remove the parentheses, the operator precedence only comes into play if expr1 is false. In that case the && operand will be evaluated before the || operator and its value will be the second operand of the || operator.
This is because of short-circuiting. Where the first expression is evaluated first and if it's able to derive the result as true then it concludes there & would not even go for rest of the expression.If the first expression results as false then the other condition will be checked and the outcome will be derived.
To know more on operator precedence. Please refer below.
https://introcs.cs.princeton.edu/java/11precedence/

How would this expression be evaluated?

Consider the following expression:
!true || false && true || false
This evaluates to false, but what I want to know is how java goes through the operations. I'm aware of the order in terms of precedence, where ! (not) has the highest precedence, followed by && (and) then || (or).
There are a few ways I can see it being evaluated:
(!true) || (false && true) || false
!(true || false) && (true || false)
!(true || (false && true) || false)
You correctly pointed the operator precedence docs, and it derives from the same docs that neither 2nd, nor 3rd option can be correct. Second breaks both ! and && precedence rules, and third one breaks the ! precedence rule.
First option is closest to the way Java does it, but Java will also short-circuit && and || operators (evaluates only to the point where definitive answer can be given - that is first true for || and first false for &&). So in false && true it will only evaluate first condition (false) and skip the rest.

What's the difference between | and || in Java? [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.

Categories