Wtat does it mean "^=" [duplicate] - java

I have a long set of comparisons to do in Java, and I'd like to know if one or more of them come out as true. The string of comparisons was long and difficult to read, so I broke it up for readability, and automatically went to use a shortcut operator |= rather than negativeValue = negativeValue || boolean.
boolean negativeValue = false;
negativeValue |= (defaultStock < 0);
negativeValue |= (defaultWholesale < 0);
negativeValue |= (defaultRetail < 0);
negativeValue |= (defaultDelivery < 0);
I expect negativeValue to be true if any of the default<something> values are negative. Is this valid? Will it do what I expect? I couldn't see it mentioned on Sun's site or stackoverflow, but Eclipse doesn't seem to have a problem with it and the code compiles and runs.
Similarly, if I wanted to perform several logical intersections, could I use &= instead of &&?

The |= is a compound assignment operator (JLS 15.26.2) for the boolean logical operator | (JLS 15.22.2); not to be confused with the conditional-or || (JLS 15.24). There are also &= and ^= corresponding to the compound assignment version of the boolean logical & and ^ respectively.
In other words, for boolean b1, b2, these two are equivalent:
b1 |= b2;
b1 = b1 | b2;
The difference between the logical operators (& and |) compared to their conditional counterparts (&& and ||) is that the former do not "shortcircuit"; the latter do. That is:
& and | always evaluate both operands
&& and || evaluate the right operand conditionally; the right operand is evaluated only if its value could affect the result of the binary operation. That means that the right operand is NOT evaluated when:
The left operand of && evaluates to false
(because no matter what the right operand evaluates to, the entire expression is false)
The left operand of || evaluates to true
(because no matter what the right operand evaluates to, the entire expression is true)
So going back to your original question, yes, that construct is valid, and while |= is not exactly an equivalent shortcut for = and ||, it does compute what you want. Since the right hand side of the |= operator in your usage is a simple integer comparison operation, the fact that | does not shortcircuit is insignificant.
There are cases, when shortcircuiting is desired, or even required, but your scenario is not one of them.
It is unfortunate that unlike some other languages, Java does not have &&= and ||=. This was discussed in the question Why doesn't Java have compound assignment versions of the conditional-and and conditional-or operators? (&&=, ||=).

It's not a "shortcut" (or short-circuiting) operator in the way that || and && are (in that they won't evaluate the RHS if they already know the result based on the LHS) but it will do what you want in terms of working.
As an example of the difference, this code will be fine if text is null:
boolean nullOrEmpty = text == null || text.equals("")
whereas this won't:
boolean nullOrEmpty = false;
nullOrEmpty |= text == null;
nullOrEmpty |= text.equals(""); // Throws exception if text is null
(Obviously you could do "".equals(text) for that particular case - I'm just trying to demonstrate the principle.)

You could just have one statement. Expressed over multiple lines it reads almost exactly like your sample code, only less imperative:
boolean negativeValue
= defaultStock < 0
| defaultWholesale < 0
| defaultRetail < 0
| defaultDelivery < 0;
For simplest expressions, using | can be faster than || because even though it avoids doing a comparison it means using a branch implicitly and that can be many times more expensive.

Though it might be overkill for your problem, the Guava library has some nice syntax with Predicates and does short-circuit evaluation of or/and Predicates.
Essentially, the comparisons are turned into objects, packaged into a collection, and then iterated over. For or predicates, the first true hit returns from the iteration, and vice versa for and.

If it is about readability I've got the concept of separation tested data from the testing logic. Code sample:
// declare data
DataType [] dataToTest = new DataType[] {
defaultStock,
defaultWholesale,
defaultRetail,
defaultDelivery
}
// define logic
boolean checkIfAnyNegative(DataType [] data) {
boolean negativeValue = false;
int i = 0;
while (!negativeValue && i < data.length) {
negativeValue = data[i++] < 0;
}
return negativeValue;
}
The code looks more verbose and self-explanatory. You may even create an array in method call, like this:
checkIfAnyNegative(new DataType[] {
defaultStock,
defaultWholesale,
defaultRetail,
defaultDelivery
});
It's more readable than 'comparison string', and also has performance advantage of short-circuiting (at the cost of array allocation and method call).
Edit:
Even more readability can be simply achieved by using varargs parameters:
Method signature would be:
boolean checkIfAnyNegative(DataType ... data)
And the call could look like this:
checkIfAnyNegative( defaultStock, defaultWholesale, defaultRetail, defaultDelivery );

It's an old post but in order to provide a different perspective for beginners, I would like give an example.
I think the most common use case for a similar compound operator would be +=. I'm sure we all wrote something like this:
int a = 10; // a = 10
a += 5; // a = 15
What was the point of this? The point was to avoid boilerplate and eliminate the repetitive code.
So, next line does exactly the same, avoiding to type the variable b1 twice in the same line.
b1 |= b2;

List<Integer> params = Arrays.asList (defaultStock, defaultWholesale,
defaultRetail, defaultDelivery);
int minParam = Collections.min (params);
negativeValue = minParam < 0;

|| logical boolean OR
| bitwise OR
|= bitwise inclusive OR and assignment operator
The reason why |= doesn't shortcircit is because it does a bitwise OR not a logical OR.
That is to say:
C |= 2 is same as C = C | 2
Tutorial for java operators

Related

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.

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

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.

Is there a difference between using a logical operator or a bitwise operator in an if block in Java?

The contents of both of the following if blocks should be executed:
if( booleanFunction() || otherBooleanFunction() ) {...}
if( booleanFunction() | otherBooleanFunction() ) {...}
So what's the difference between using | or using ||?
Note: I looked into this and found my own answer, which I included below. Please feel free to correct me or give your own view. There sure is room for improvement!
The two have different uses. Although in many cases (when dealing with booleans) it may appear that they have the same effect, it is important to note that the logical-OR is short circuit, meaning that if its first argument evaluates to true, then the second argument is left unevaluated. The bitwise operator evaluates both of its arguments regardless.
Similarly, the logical-AND is short-circuit, meaning that if its first argument evaluates to false, then the second is left unevaluated. Again, the bitwise-AND is not.
You can see this in action here:
int x = 0;
int y = 1;
System.out.println(x+y == 1 || y/x == 1);
System.out.println(x+y == 1 | y/x == 1);
The first print statement works just fine and returns true since the first argument evaluates to true, and hence evaluation stops. The second print statement errors since it is not short circuit, and a division by zero is encountered.
The logical operator works on booleans, and the bitwise operator works on bits. In this case, the effect is going to be the same, but there are two differences:
The bitwise operator is not meant for that, which makes it harder to read but most importantly
The logical OR operator will evaluate the first condition. If it's true, it does not matter what the next condition results in, the result will be true, so the second clause is not executed
Here's some handy code to prove this:
public class OperatorTest {
public static void main(String[] args){
System.out.println("Logical Operator:");
if(sayAndReturn(true, "first") || sayAndReturn(true, "second")){
//doNothing
}
System.out.println("Bitwise Operator:");
if(sayAndReturn(true, "first") | sayAndReturn(true, "second")){
//doNothing
}
}
public static boolean sayAndReturn(boolean ret, String msg){
System.out.println(msg);
return ret;
}
}
for programmers, there is only one difference.
your logical operators are logical ones,i.e. they test only one condition and get result based on that.
booleanFunction() || otherBooleanFunction() will be true if either is true. likewise, booleanFunction() && otherBooleanFunction() will be false if either is false. So, why test the other one. that's what logical operators do.
But bitwise ones check both. A frequent application of this concept is as follows.
if(someObject != null && someObject.somemethod())
So, in this case if you replace && by & then wait for a disaster. You will get nasty NullPointerException soon...
if( booleanFunction() || otherBooleanFunction() ) {...}
In this condition if booleanFunction() returns true then otherBooleanFunction() would not be executed.
if( booleanFunction() | otherBooleanFunction() ) {...}
But in bitwise operator both functions - booleanFunction() and otherBooleanFunction() would be executed no matter booleanFunction() returns true or false
Difference between bitwise a d logical operator-
1. Bitwise operator works on bit whereas logical operator works on statement.
2. Bitwise and is represented by & whereas logical and is represented by &&.
3. Bitwise or is represented by | whereas logical or is represented by ||.

Java Operators : |= bitwise OR and assign example [duplicate]

This question already has answers here:
What does "|=" mean? (pipe equal operator)
(6 answers)
Closed 7 years ago.
I just going through code someone has written and I saw |= usage, looking up on Java operators, it suggests bitwise or and assign operation, can anyone explain and give me an example of it?
Here is the code that read it:
for (String search : textSearch.getValue())
matches |= field.contains(search);
a |= b;
is the same as
a = (a | b);
It calculates the bitwise OR of the two operands, and assigns the result to the left operand.
To explain your example code:
for (String search : textSearch.getValue())
matches |= field.contains(search);
I presume matches is a boolean; this means that the bitwise operators behave the same as logical operators.
On each iteration of the loop, it ORs the current value of matches with whatever is returned from field.contains(). This has the effect of setting it to true if it was already true, or if field.contains() returns true.
So, it calculates if any of the calls to field.contains(), throughout the entire loop, has returned true.
a |= b is the same as a = (a | b)
Boolean Variables
In a boolean context, it means:
if (b) {
a = true;
}
that is, if b is true then a will be true, otherwise a will be unmodified.
Bitwise Operations
In a bit wise context it means that every binary bit that's set in b will become set in a. Bits that are clear in b will be unmodified in a.
So if bit 0 is set in b, it'll also become set in a, per the example below:
This will set the bottom bit of an integer:
a |= 0x01
This will clear the bottom bit:
a &= ~0x01
This will toggle the bottom bit:
a ^= 0x01;
This code:
int i = 5;
i |= 10;
is equivalent to this code:
int i = 5;
i = i | 10;
Similarly, this code:
boolean b = false;
b |= true;
is equivalent to this one:
boolean b = false;
b = b | true;
In the first example, a bit-wise OR is being performed. In the second example, a boolean OR is performed.
a |= b is the same as a = a | b
a | b is a bitwise operator if both operands are integral types (int, short, etc...). If both operands are booleans, then its is a boolean or.
When both a and b are booleans, the difference between a | b and a || b is that in the first, both sides are always evaluated, in the later b is only evaluated if a is false. It is sort of a "shortcut" operator.
This is useful for situations like this:
if (a == null || a.equals(b)) { .. do something .. } // works
if (a == null | a.equals(b)) { .. do something .. } // NPE if a is null
On the other hand, || actually is implemented as another conditional jump in the bytecode/machine-code. In some cases, it may be faster to evaluate boolean conditions using the | operator to avoid the additional jump (and thus branch predition, etc...). Definitely something for low-level micro-benchmarking to figure out which is better (and usually not important in most applications).
When you do a |= b you are always evaluating both a and b. It doesn't really make sense to have an a ||= b operators, since the equivalent a = a || b would translate to:
if (a) a = true;
else if (b) a = true
else a = false;
...due to the conditional nature of || evaluation. In other words, b would not be evaluated if a was already true.
Could it be possible that the code has a bug and it was meant
matches = matches || field.contains(search);
so that matches should be true if at least one field contains the search variable?
That code snippet is a poor example of when to use that operator. Honestly I can't think of a great example of when to use this operator, but here's my best attempt:
boolean somethingIsTrue = testSomethingTrue();
if(somethingIsTrue){
//Do something
}
somethingIsTrue |= testSomethingElseTrue();
if(somethingIsTrue){
//Do something else
}
somethingIsTrue |= testSomethingElseTrue2();
if(somethingIsTrue){
//Do something else than something or something else
}
Note: You need 3 ifs because otherwise you could just do somethingIsTrue | testSomethingElseTrue() for the second if.
In case you were wondering why you shouldn't use the operator in the first example, here's why:
From a performance standpoint, it is poor because it does a compare and an assign for each loop instead of just a compare. Also, it continues iterating even when future iterations will have no effect (once matches gets set to true it will not change, and String.contains has no side effects).
It is also poor from a readability standpoint, based solely on the existence of this question ;)
Thus, in place of that snippet I'd go for:
for (String search : textSearch.getValue()){
if(field.contains(search)){
matches = true;
break;
}
}
On a side note, it seems to me like the original coder might have been playing a bit too much code-golf when (s)he wrote this :)

What is the difference between '==' and '='?

I know that one of them is bitwise and the other is logical but I can not figure this out:
Scanner sc = new Scanner(System.in);
System.out.println("Enter ur integer");
int x=sc.nextInt();
if(x=0)//Error...it can not be converted from int to boolean
System.out.println("...");
The error means that x cannot be converted to boolean or the result of x=0 can not be converted to boolean.
== checks for equality.
= is assignment.
What you're doing is:
if( x = Blah ) - in Java this statement is illegal as you can not test the state of an assignment statement. Specifically, Java does not treat assignment as a boolean operation, which is required in an if statement. This is in contrast with C/C++, which DOES allow you to treat assignment as a boolean operation, and can be the result of many hair-pulling bugs.
When you write 'x = 0' you are saying "Store 0 in the variable x". The return value on the whole expression is '0' (it's like this so you can say silly things like x = y = 0).
When you write 'x == 0' it says "Does x equal 0?". The return value on this expression is going to be either 'true' or 'false'.
In Java, you can't just say if(0) because if expects a true/false answer. So putting if(x = 0) is not correct, but if(x == 0) is fine.
== is a comparison operator, and = is assignment.
== is an equality check. if (x == 0) // if x equals 0
= is an assignment. x = 0; // the value of x is now 0
I know the question has been answered, but this still comes up from time to time not as a programmer error but as a typographical error (i.e., the programmer knew what he meant, but failed). It can be hard to see, since the two look so similar.
I've found that a way to help avoid doing this is to put the constant expression on the left-hand-side, like so:
if (0 == x)
...
That way, if I accidentally use only one "=" sign, the compiler will fail with an error about assigning to a constant expression, whether or not the assignment operator is left-associative and whether the if conditional expects a strongly-typed Boolean.
if(x=0)
Here you're assigning the value of 0 to the variable x. The if statement in Java can't evaluate an integer argument as it can in many other languages. In Java, if requires a boolean. Try
if(x == 0)
to do a comparison.
Interpret the error to mean
"The expression
x=0
cannot be converted to Boolean."
Just to clarify about C/C++ - assignment is evaluated to the right operand
if(a = n)
is evaluated to n, so (n = 1) is true (n = 0) is false
One interesting note: Since assignment operator evaluates to the right operand, the following is valid in Java(albeit not pretty):
if (( x = blah ) > 0) ...
Parenthesis are needed because of operator precedence ( '>' binds stronger than '=').
As others have already said, '=' is assignment; '==' is compare.
in your program change
if(x=0)
to
if(x==0)
"==" checks for equality
"=" Is used for assignment.
It is giving you error cause you're assigning value to x in if(), where you're supposed to check for the equality. Try changing it to equality instead of assignment operator.
As others stated, = assigns while == compares.
However, these statements have their own values as well.
The = operator returns the value of its right-hand operand. This is how statements like a = b = c = 5 work: they are parsed as a = (b = (c = 5)), which evaluates to a = (b = 5) and then a = 5.
The == operator returns a boolean that is true if its operands are equal. The if statement runs its body if its argument is true. Thus, if headers like if (5 == 5) translate to if (true). This is why sometimes you see infinite while loops with header while (true); the while loop runs "while" toe argument is true.
If you had a boolean in your if statement, it would give no error and run the code if the value being assigned (or "compared to") was true. This is why it is so important to never mix up the = and == operators, especially when working with booleans.
Hope this helped!!

Categories

Resources