The |= operator in java, What does this code do? [duplicate] - java

This question already has answers here:
What does "|=" mean? (pipe equal operator)
(6 answers)
Closed 7 years ago.
int equal = 0;
for (int i = 0; i < a.length(); i++) {
equal |= a.charAt(i) ^ b.charAt(i);
}
return equal == 0;
I understand pipe and XOR operator But what is |= doing?

It is similar to +=. See the table here
|= bitwise inclusive OR and assignment operator C |= 2 is same as C = C | 2
So it is equivalent to writing your code as:
equal = equal | a.charAt(i) ^ b.charAt(i)
Also as luk2302 has pointed out correctly, that there (bitwise exclusive OR)^ has higher precedence over (bitwise inclusive OR)| so you can include it inside the brackets like this:
equal = equal | (a.charAt(i) ^ b.charAt(i))

Diatribe
This code is appears to be a great example of why goofballs should not be hired as programmers.
Answer
Here is an explanation of the code:
Start with two strings, which are presumed to be the same length.
Perform an xor operation on two characters.
"Add" the result of the xor operation to an accumulator (named equal; as an aside, in context I prefer the even less obvious variable name artificialSweetener) using the or-equals operator.
If not at the end of string a, repeat starting at step 2 above.
If, after the loop completes, the value of the equal (or artificialSweetener as you wish) operator is zero, then return true. Else return false.
Notes
The or-equals operator performs a bitwise or operation between the left hand argument and the right hand argument then assigns the result to the left hand argument. This means that this statement:
left |= right
performs the same work as this statement:
left = (left | right)
Why the Anger
It is common for goofballs to regularly reinvent already existing functionality and to do it poorly. In this sense, the code above is a success; it both reinvents existing functionality and does it terribly.
This code exhibits some disturbingly incompetent behaviour
It continues performing comparison even after a difference has been found.
It will throw value-free NullPointerExceptions if a and/or b are null.
It has the benefit of being not at all obvious to a newer java programmer.
It throws an exception if string b is shorter in length than string a.
It returns a false positive when string a is an initial subset of string b. For example, a = "Blah" and b = "BlahNotAtAllEqual" will result in a false positive.
What would a competent programmer do
A programmer who is not an idiot would perform a string comparison operation using the String.equals method or, if they are more than just barely competent, they would use a utility like the Apache Commons Lang StringUtils to perform null safe comparisons.

It's simple mate. The following lines do the same thing:
equal |= a.charAt(i) ^ b.charAt(i);
equal = equal | (a.charAt(i) ^ b.charAt(i));

Related

Ternary Operator Limits [duplicate]

This question already has answers here:
ternary operator not working
(3 answers)
Closed 8 years ago.
Let's say we have following if statement:
int a = 1;
int b = 2;
if(a < b) {
System.out.println("A is less than B!");
}
else {
System.out.println("A is greater or equal to B!");
}
I have been wondering that if ternary operator replaces if statement when if statement consists from one line of code in each sub-block (if and else blocks), then why above example is not possible to write like this with ternary operator?
(a < b) ? System.out.println("A is less than B!") : System.out.println("A is greater or equal to B!");
You can only use ? : for expressions, not statements. Try
System.out.println(a < b ? "A is less than B!" : "A is greater or equal to B!");
Note: this is also shorter/simpler.
Because it doesn't replace an if statement.
The ternary operator only works on expressions and not statements, itself being an expression.
Because it is an expression, it is evaluated rather than executed, and it has to return a (non-void) value. The type of that value is inferred from the types of the two optional expressions specified, and the rules are fairly complex, with some unexpected gotchas.
(So as a rule I only use ?: in the simplest situations to keep the code easy to read.)

Why should I always use || instead of | and && instead of &?

Since I started programming Java, I've noticed that everyone was using && and || instead of & and |. What is the reason for this? I've been using && and || all this time because I didn't know you can use & and | on booleans.
class A{static{
boolean t = true;
boolean f = false;
System.out.println("&ff " + (f&&f) + " " + (f&f));
System.out.println("&ft " + (f&&t) + " " + (f&t));
System.out.println("&tf " + (t&&f) + " " + (t&f));
System.out.println("&tt " + (t&&t) + " " + (t&t));
System.out.println("|ff " + (f||f) + " " + (f|f));
System.out.println("|ft " + (f||t) + " " + (f|t));
System.out.println("|tf " + (t||f) + " " + (t|f));
System.out.println("|tt " + (t||t) + " " + (t|t));
}}
As far as I can tell, they are the same:
$ javac A.java && java A
&ff false false
&ft false false
&tf false false
&tt true true
|ff false false
|ft true true
|tf true true
|tt true true
Exception in thread "main" java.lang.NoSuchMethodError: main
Does using || and && improve my code in any way?
As a simple test, I replaced hundreds of occurrences with the short form, and all of my unit tests still pass.
|| and && uses short circuit evaluation
From same article
Short-circuit evaluation, minimal evaluation, or McCarthy evaluation
denotes the semantics of some Boolean operators in some programming
languages in which the second argument is only executed or evaluated
if the first argument does not suffice to determine the value of the
expression
Consider you have an object and you want to check one of its property for some value if you do:
if(obj != null & obj.ID == 1)
If your object obj is null you will get a null reference exception, since you used single &, the first condition evaluate to false, but it will still continue to the next condition and raising null reference exception.
If you used && then the second condition will never get evaluated, thus no exception.
if(obj != null && obj.ID == 1)
With your code you will not see any difference, but using bitwise | or & with multiple conditions would result in no short circuiting at all.
More Explanation.
consider that you following code:
Boolean conditionA = 2 > 1; //some condition which returns true
if(conditionA | obj.SomeTimeConsumingMethod()){
}
Now in above code snippet, suppose you have an object with a method SomeTimeConsumingMethod which takes a lot of time in processing and returns true or false. If you use single | it would evaluate both the conditions, since first conditionA is true it will process obj.SomeTimeConsumingMethod as well. End result will be true for the whole if statement since | (OR) is used.
If your condition is using double || (OR Logical operator)
if(conditionA || obj.SomeTimeConsumingMethod())
Then the second condition obj.SomeTimeConsumingMethod() will not be evaluated. This is short circuiting and that just saved you from executing some time consuming method. Still the end result is true regardless of what was returned from obj.SomeTimeConsumingMethod().
As has already been pointed out, && and || do short-circuit evaluation. & and |, with boolean operands, do the same operations but evaluate both operands regardless of the value of the first operand.
There are cases where it matters which you use, such as when the left operand is a pre-condition for exception-free evaluation of the right hand operand.
In most cases, it does not matter. I use && and || in those cases for readability, because that is the commoner choice. Using & or | with boolean operands would tend to make most Java programmers have to stop and think, and ask themselves whether there is some specific reason for it. I suspect it may be so common because of the inheritance from C and C++.
|| is logical or, where | is the bitwise operation or. Same with && and &. Use && and || if you're in an if statement, and | or & if you're doing bit operations.
While you may get the "correct" result using the bit-wise operators, understand they do NOT represent the same thing. For instance, this works
public static void main(String[] args){
int x = 5;
int y = 9;
System.out.println(x&y); // prints "1"
}
However, this won't
public static void main(String[] args){
int x = 5;
int y = 9;
System.out.println(x&&y); // Compile error: java: operator && cannot
// be applied to int,int
}
The reason you don't use bit-wise operators for boolean logic is so that it's clear what the code is trying to do (as well as knowing that it actually works). Bit-wise operators are for manipulating bit values, where as boolean operators are for evaluating first-order logic statements.
While not the same, it is along the same reasoning for using .equals() vs == for comparison -- You don't want readers guessing as to what you meant to do. It may work in some instances (like comparing constant, hard-coded strings with ==), but it is poor form because what it says is that you are asking for instance equality as opposed to value equality, which is usually implied. And using bit-wise operators implies you want to do bit manipulation, not first-order logic evaluation.
Arguing that short circuit evaluation is mandatory because of performance is weak. You can make an argument that is almost as weak: that short circuit evaluation encourages extra nondeterminism and side channels. Random optimizations or random loss of nondeterminism/side channels, I'd prefer the latter.
The only remaining argument is this: If your code base relies on short circuit behaviour, e.g., the trick described by Habib (if (obj != null && obj.ID == 1)), then it may not be a good idea to start mixing in &, because programmers might get it confused with &&. i.e., if you use &/| everywhere, but only use && in a few places where you rely on short circuit evaluation, someone might make an error and put only &, it may be hard to spot. In this case, if you relied on && for performance instead of something like null checking, it may be harder to spot when someone accidentally puts & alone, since there would be no stacktrace.
Does using || and && improve my code in any way?
Let me demonstrate two examples on how the conditional boolean operators may improve your code. Compare
if (a != null && a.equals("b") || z != null && z.equals("y"))
System.out.println("correct");
with
boolean b1 = a != null, b2 = z != null;
if (b1) b1 = b1 & a.equals("b");
if (b2) b2 = b2 & z.equals("y");
if (b1 | b2) System.out.println("correct");
which is the best way I can think of relying solely on the logical boolean operators.
Second, say you have two tests to perform: simpleTest() and heavyTest(), where the latter involves making an HTTP request and parsing the response. You have
if (simpleTest() & heavyTest()) System.out.println("success");
else throw new IllegalStateException();
and want to optimize it. What would you rather do, this:
if (simpleTest()) {
if (heavyTest()) System.out.println("success");
else throw new IllegalStateException("operation could not be completed");
} else throw new IllegalStateException("operation could not be completed");
this:
boolean b = simpleTest();
if (b) b = b & heavyTest());
if (b) System.out.println("success");
else throw new IllegalStateException("operation could not be completed");
or this:
if (simpleTest() && heavyTest()) System.out.println("success");
else throw new IllegalStateException();
Why should I always use || instead of | and && instead of &?
You shouldn't always use them, but you would do yourself a favor by making them your default because in 99.9% of uses they either don't hurt or make your code much better. Reserve the logical operators for that 0.1% of cases where you truly do need their semantics.
It has been mentioned elsewhere on this page that relying on the conditional evaluation of the right operand makes for counterintuitive code. I refuse to accept such a view on intuition because, by definition, intuition is a learned skill. It is a facility bestowed to you by evolution to recognize a pattern in situations you encounter often, and to quickly (and subconciously) cut through to the correct conclusions. One of the most important aspects of learning a language is acquiring the right intuitions. The argument that a language feature is bad because it is counterintuitive to someone who looks at it for the first time cannot be taken seriously.
In Java (and C/C++ if I remember correctly) the single "|" and "&" are bit-wise operators, not logical operators, they are used for completely different things.
You use the "&&" and "||" for boolean statements
You use the "&" and "|" for bit operations, given the following are binary numbers
dont make assumption so fast. It because this wont compile:
static boolean f(boolean a) {
boolean x = (true|a) ? a : x;
return x;
}
Bro.java:6: variable x might not have been initialized
boolean x = (true|a) ? a : x;
^
and this will:
static boolean f(boolean a) {
boolean x = (true||a) ? a : x;
return x;
}
&& and || are short cut operators. For example:
A && B
Condition B will not be evaluated if condition A is false
A || B
Condition B will not be evaluated if condition A is true
You should always use shortcut operators for multiple conditions evaluation. | or & are used for bit-wise operations.

Java: boolean in println (boolean ? "print true":"print false") [duplicate]

This question already has answers here:
What is the Java ?: operator called and what does it do?
(17 answers)
Closed 9 years ago.
I came across this syntax:
System.out.println(boolean_variable ? "print true": "print false");
What is this syntax with two dots : called?
Where can I find info about it?
Does it work just for booleans or is it implemented in other different ways?
? : is the conditional operator. (It's not just the : part - the whole of the method argument is one usage of the conditional operator in your example.)
It's often called the ternary operator, but that's just an aspect of its nature - having three operands - rather than its name. If another ternary operator is ever introduced into Java, the term will become ambiguous. It's called the conditional operator because it has a condition (the first operand) which then determines which of the other two operands is evaluated.
The first operand is evaluated, and then either the second or the third operand is evaluated based on whether the first operand is true or false... and that ends up as the result of the operator.
So something like this:
int x = condition() ? result1() : result2();
is roughly equivalent to:
int x;
if (condition()) {
x = result1();
} else {
x = result2();
}
It's important that it doesn't evaluate the other operand. So for example, this is fine:
String text = getSomeStringReferenceWhichMightBeNull();
int usefulCharacters = text == null ? 0 : text.length();
It's the conditional operator, often called ternary operator because it has 3 operands: An example would be:
int foo = 10;
int bar = foo > 5 ? 1 : 2; // will be 1
int baz = foo > 15 ? 3 : 4; // will be 4
So, if the boolean expression evaluates to true, it will return the first value (before the colon), else the second value (after the colon).
You can read the specifics in the Java Language Specification, Chapter 15.25 Conditional Operator ?
It's a ternary operator, meaning that instead of having two operands like many other operators, it has three. Wikipedia on Ternary Operation and how it's used in Java. What it boils down to: the boolean operation (or just a variable) is evaluated. If it evaluates to true, the operator returns the value / executes the code before the :, otherwise the one after it.
That's an if statement.
What's to the left of ? is the condition, what's between the ? and : is the result if the condition is true, and what's to the right of : is the result if the condition is false.
This is ternary operator (http://en.wikipedia.org/wiki/?:). It can be used anywhere when you need a small if expression.
For your questions:
The ?: (both characters together) are called conditional operator (or ternary operator). Only both together will work.
Search for java ternery operator
It only works for boolean
In principle the ternery operator is a shortened if/else. The boolean will be the condition to the if, the part between ? and : is the if branch and the part after this is the else branch.
Please note that the return type of the conditional operator is determined by the first branch.
It's the ternary operator and it works with booleans. It can be used as a shorthand for if-else in some cases, but shouldn't be used for too complicated things as it can be difficult to read.
An example would be assigning value to a variable depending on a condition:
String message = doOperation() ? "Success" : "Error occurred";
System.out.println(message);
In this case, if doOperation returns a boolean telling whether it succeeded or not, the message to be shown can be assigned on a single line.
Please note that this example does not represent good programming practices.
Its ternary operator.
The ternary operator or ?, is a shorthand if else statement. It can be used to evaluate an expression and return one of two operands depending on the result of the expression.
boolean b = true;
String s = ( b == true ? "True" : "False" );
This will set the value of the String s according to the value of the boolean b. This could be written using an if else statement like this:
boolean b = true;
String s;
if(b == true){
s = "True";
}else{
s = "False";
}
Its a short form of if-else statement.
It works in this way
(yourCondition ? STATEMENT1 : STATEMENT2)
The compiler checks for the condition.
IF it returns TRUE then STATEMENT1 will be executed.
ELSE STATEMENT2 will be executed.
The question mark followed by a colon (two dots) is a ternary operator usually called inline if.
In this case it returns a string depending on the value of boolean_variable.
http://en.wikipedia.org/wiki/%3F:
See here. The ternary operator is similar to an if expression but differs in that it is an expression - it has a return value, while if expressions don't. Sometimes you want to use it to make your code a little less cluttered.

Difference between OR operator || and | in Java? [duplicate]

This question already has answers here:
Why do we usually use || over |? What is the difference?
(28 answers)
Closed 9 months ago.
Can any one explain the difference between and usage of OR operator ( || and | ) in java. thanks
e.g:
if(a || b) {
// Do something.
}
and
if(a | b) {
// Do something.
}
This is simple. http://www.roseindia.net/help/java/o/java-operator.shtml says:
OR operator is a kind of a conditional operators, which is represented
by | symbol. It returns either true or false value based on the state
of the variables i.e. the operations using conditional operators are
performed between the two boolean expressions.
The OR operator (|) is similar to the Conditional-OR operator (||) and
returns true, if one or another of its operand is true.
Note: In || operator if have more than one condition and if first condition return true then other conditions ignored but in | operator all condition examin.
There are more information on http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
The first one is a logical or. Both sides of the operator are handled as boolean values and it results in a boolean. In case the variables in question are not boolean themselves they become false if they are 0 or null.
The second one is a bit-wise or operator. This one usually only works with integer numbers. I compares the two values bit by bit and gives the resulting number. For example:
5 | 6 = 7 (decimal)
101 | 110 = 111 (binary)
For further details have a look at Wikipedia: Logical disjunction
If you use the operator || JVM will not bother to evaluate the right-hand operand alone.
the || operator is a boolean operator
it can be interpreted in simple english as...
if ( a is true or b is true)
{
//do soemthing
}
the | operator is a logical operator
it works only on integral types like int, char etc...
it is the bitwise OR operation on the two operands
example:
bool a = true;
bool b = false;
bool c = a | b;
//c will be true
if(a | b )
{
}
is same as
c = a | b;
if ( c == true)
{
do something;
}
The first is a logical-or, the latter a bitwise-or. HOWEVER, if the two operators (a and b in your example), are boolean, the bitwise-or is seen as logical-or without short circuiting. This can be be convenient at times.
For example, consider:
boolean getTrue() {
System.out.println("getTrue() called");
return true;
}
public static void main(String[] args) {
boolean a = getTrue() || getTrue();
System.out.println("Result: " + a);
}
The above will only print "getTrue() called" once as the logical-or (||) can determine the result of the expression immediately, without calling getTrue() a second time. Changing to a bitwise-or (i.e. boolean a = getTrue() | getTrue();) will result in two calls to getTrue().
A similar result will be produced with a bitwise-& operation and a getFalse() method.
Another aspect to keep into consideration is that the bit-wise operators gets preference before logical operators. Therefore, mixing them is not recommended as bitwise-or will be executed before a logical-and, which can cause unwanted behaviour. It can be fixed using brackets (), but I think this should be avoided.

Differences in boolean operators: & vs && and | vs ||

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.

Categories