Is following true in java:
In java if you use || then after getting first true condition it neglects the rest conditions. That is If you write if(a || b || c) in java and java finds a is true then it will not check for b and c, just go into the if case.
Yes this is called short circuiting, if you put less expensive checks to the left you might avoid the expensive ones to follow.
This works for || and &&
one of the best uses is checking a value from an object that might be null:
if(myList != null && myList.size() > 6)
the previous line is null safe, reversing the condition will cause a null pointer exception in case myList is null
This is correct. || is called short-circuit OR evaluation, or an OR-ELSE operator.
This is important in situations when evaluating the right-hand side may cause an undesirable consequence:
if (myString == null || myString.indexOf("hello") != -1)
...
would crash if it were not for short-circuiting.
Yes, This way the compiler avoids unnecessary checking and calculation overhead.
That's correct, and that's not just laziness on part of the language implementation, but rather it is a crucial feature - short-circuiting allows you to write something like this:
if (myarray.length > 10 && myarray[10] == 5) { /* ... */ }
Here the second condition may only even be evaluated if the first one is true. Thanks to short-circuiting, if the first condition is false the second is never touched.
YES
(AFAIK)
The same things applies to && but in reverse manner.(for first false).
The same rule as in circuits for AND and OR gates.
Yes, it's called short-circuiting. It also will short circuit &&, i.e.
if (a && b && c)
If a is false then the condition cannot be true, neither b nor c are checked.
This can be problematic if you call methods that return booleans. To get around this, you can use bitwise & and |.
Yes it is correct. If you use | this operator to check OR condition then it checks rest all conditions. It also applied on AND(&) operator.
Yes, and one important thing, if you do any operations in the second part, they will not be made. For example:
int a = 5;
int b = 5;
if ( a == b || a++ == b){
...
}
//a = 5
//b = 5
BUT in case:
int a = 3;
int b = 5;
if ( a == b || a++ == b){
...
}
//a = 4
//b = 5
I tried to make a simple example, but sometimes you call a method in the second part, (which will not be called if first part was true in case of ||), or the first part was false in case of &&
Related
I'm trying to determine the conditions under which the following expression, where a and b are properly declared boolean variables, evaluates to false:
(a && (b || !a)) == a && b
To me, it seems that this expression will always evaluate to true. If either a or b is false, both sides of the equality operator will evaluate to false. If a and b are both true, then both sides will evaluate to true. That's all the options, and it's the correct answer for my online homework. However, when I run this in IntelliJ CE with the Java 11 JVM, it seems like it prints false whenever b is false:
when a and b are both false, IntelliJ outputs false
I get the same output when b is false and a is true. Can someone explain where the fault in my logic is? Thank you very much.
I think it is giving == operation priority over &&
Try this -
(a && (b || !a)) == (a && b)
You code should be:
boolean c = (a && (b || !a)) == (a && b);
otherwise it is evaluated as:
boolean c = ((a && (b || !a)) == a) && b;
Boolean operations have equivalent mathematical operations (this is what the CPU is ultimately doing). You can use this method to check any equation to make sure that it is coming out how you expect.
It can help you quickly see if your boolean logic is correct for all cases.
Using your equation here is an example:
Replace "true" with 1 and "false" with 0. Replace && with * (as in multiplies) and || with + (as in add). ! does what you expect still. Then check equality
so
a*(b+!a) == a*b
Then when a = false (0) and b = false(0) we have
0*(0+1) == 0*0
or 0=0
Which is true.
We can keep going with the other options to check.
a=1, b=1
1*(1+0) == 1*1
or 1=1
again, true
a=1, b=0
1*(0+1) == 1*0
1*1=0?
Not correct (false).
With that last test, we can see that this equation does not always evaluate to true. Just like in math, boolean operations have an order of operations (as mentioned by many others), but I like using this method to make sure my equations are working as intended.
boolean riddle = !( 1 < 8 || (5 > 2 && 3 < 5));
boolean is a true or false.
! = not
|| = or
&& = and
but I still dont understand this syntax... can someone explain me what this syntax excactly does?
Just dissect it:
There are some comparisons such as
5 > 2 ... true
3 < 5 ... true
Those two are pulled together using &&; so true && true --> true
1 < 8 ... true
That one is or'ed to the rest; so we get true or true --> true
Finally, not (true) --> false
Long story short: if you don't understand the whole picture, break it down into the parts you understand; and then pull those together again.
Edit: and of course, the order I am using in my explanation isn't what happens in reality. There, 1 < 8 is evaluated first; and as that is true; and "true or X" is always true, the other comparisons are not even computed.
The not ! operator negates what it is in front of. In this case !() it will produce the opposite of the what is inside of the parenthesis.
the || or operator checks to see if one condition or the other is true. At least one must be true for the condition to return true.
Finally the && checks both sides of the conditional statement to see if they are both true, and both of them must be true to proceed.
boolean riddle = !( 1 < 8 || (5 > 2 && 3 < 5));
Let's parse it the way Java does :
boolean : Here comes a boolean, i.e. true or false.
riddle : The variable riddle is declared to be a boolean.
= : The boolean variable riddle is initialized with the expression on the right.
!(...) : It returns a boolean, the negation (=opposite) of the boolean inside of the parentheses.
Inside the parentheses is a bool1 || bool2 expression, where || is a "lazy OR" operator. If bool1 is true, there's no need to evaluate bool2.
bool1 is 1 < 8, which is true.
bool2 isn't evaluated
bool1 ||bool2 is true
!(...) is false
riddle is initialized with false
At no point in time are 5 > 2 or 3 < 5 evaluated. Eclipse warns that those 2 expressions are "dead code" and could be removed.
The whole expression could be :
boolean riddle = !( 1 < 8 || (5 > 2 && doSomethingVeryDangerous()));
the result would be the same and no method call would happen at all.
The problem that you have is that you initialize at the same time as you are checking if it's true or false. You cannot compare boolean with integer. If you want to do it then you need to solve it in another way by converting from one datatype to another, or involve another variable in your solution. The way you need to solve your syntax problem is by dividing it like this:
How you did it...
boolean riddle = !( 1 < 8 || (5 > 2 && 3 < 5));
How to potentially solve it...
boolean riddle;
"...some code to decide if riddle will be true or
false and assign it to the variable riddle..."
if (riddle == true){
"...do some code here...";
}
if (riddle == false){
"...do some code here...";
}
Or you can solve the problem by not using boolean as datatype and instead only use integers like this...
int riddle;
"...some code to decide what value riddle will
have and assign it to the variable riddle..."
if ( riddle < 8 && riddle > 1){
"...do some code here...";
}
This question already has answers here:
In Java, what are the boolean "order of operations"?
(6 answers)
Closed 7 years ago.
Is it logically the same to do the following:
if ( a || b || c || d)
vs
if ((a || b) || (c || d))
In other words, how does the order of the && and || operators work, left to right or right to left?
How about:
if ( a && b && c && d)
vs
if ((a && b) && (c && d))
A sequence of identical operators is evaluated left to right if left-associative, or right to left if right-associative. So for example
a || b || c
is the same as
(a || b) || c
Howver if you mix || and && then operator precedence takes over.
I would like to provide a detailed answer in order for you not only understand the Logical (AND) and (OR) but, also how the operators in general are evaluated and what are their order of precedence. There are many ways to evaluate multiple logical expressions.
The first step is to understand the truth table for OR and AND shown below (Source):
As shown above, for different values of x and y the X AND Y (X && Y) and X OR Y (X || Y) yield different values. If you pay attention below AND operation requires both X and Y to be true in order for the result to be true however in case of OR if either X or Y is true then the result is true.
You need to know the above table for AND and OR by heart.
If you wish to be able to evaluate multiple logical expressions (ANDs and ORs), De Morgen's law can help you how to do it using NOT operation.
The rules can be expressed in English as:
The negation of a conjunction is the disjunction of the negations. The
negation of a disjunction is the conjunction of the negations.
or informally as:
"not (A and B)" is the same as "(not A) or (not B)"
also,
"not (A or B)" is the same as "(not A) and (not B)".
Read more on De Morgen's law and how to evaluate multiple logical expressions using it in here and here.
Precedence of logical AND and OR are left to right. See below table (Source) and that should give you an idea which operators are right to left and which ones are left to right as well as order of their precedence for example () and [] has the highest precedence and assignments have the lowest precedence among operators. If you notice
back to your example
if ( a || b || c || d)
According to truth table there are 16 possible combinations starting from
a=true,b=true,c=true,d=true
...
...
...
a=false,b=false,c=false,d=false
As long as any of the a,b,c,d are true then outcome is true hence, out of 16 possible combinations 15 will be true and last one will be false because all a,b,c,d are false.
ON whether below is same as above? Yes.
if ((a || b) || (c || d))
The only difference between the 2 is that in the second one the brackets are evaluated first hence (a || b) is evaluated then ORd with evaluation result of (c || d) but. The same logic true for above is true here too. As long as one of a,b,c,d are true then outcome is true.
In regards to below, yes the two evaluate to same outcome.
if ( a && b && c && d)
vs
if ((a && b) && (c && d))
Same as above 16 possible combinations for different values for a,b,c,d. The only true outcome for the above is when all a,b,c,d are true. Hence only one true and another 15 false.
Both statement if ( a || b || c || d) and if ((a || b) || (c || d)) will return true if either of the variables is true.
And also statement if ( a && b && c && d) and if ((a && b) && (c && d)) will return true only if none of the variables is false.
Also evaluation is from left to right.
These are short-circuiting operators that operate left-to-right, meaning as soon as the logical value of the whole expression can't be changed by the remaining terms, execution halts. As soon as || hits a true, it stops and the whole thing is true, and as soon as && hits a false, it the whole thing is false. So even though these operators are theoretically associative and commutative, order and grouping does have a practical effect. In fact, it's common to do something like:
if (foo == null || foo.someProperty())
or
if (foo != null && foo.someProperty())
Both of these are guaranteed not to have a null pointer exception because if foo is null, the second one doesn't get evaluated.
(a > b) & (c < d), the components are evaluated left to right, so (a >
b) is evaluated first. If (a > b) is false, the entire expression is
false regardless of the result of the component (r < d). Nevertheless,
the component (c < d) will still be evaluated. However, in the
expression (a > b) && (c < d), the component (c < d) will not be
evaluated if (a > b) evaluates to false. This is known as short
circuiting.
Came across this paragraph in a Java book. I have been programming in various languages before, but I've never found a need for '&'. Why would one want to evaluate the second statement if it's known that the end result is not affected by it? Is there any use for it; does it come due to historical reasons?
Same question applies to | and || as well.
The && operator is defined by the Java Language Specification to perform short-circuit evaluation.
However, the & operator is not, even when applied to boolean arguments.
You could exploit this if one of the arguments had side-effects that you did not want short-circuited. However, in my experience this is uncommon, and you'd face the risk of someone "fixing" it. It would be better separated into steps. For example, instead of:
if ( foo() & bar() ) {... }
you could say:
boolean isFoo = foo();
boolean isBar = bar();
if ( isFoo && isBar ) { ... }
if you expect your code to be under attack from timing attacks you want the least amount of branches (conditional execution paths) possible, this is one way to eliminate them
The difference between '&' and '&&' is not well-known and that example from the book doesn't help much.
Here's another example to show how short-circuiting work (using horrible methods having side-effects, but that's not the point).
Imagine you have this:
private int cnt;
private boolean a() {
cnt++;
return false;
}
private boolean b() {
cnt++;
return false;
}
If you execute the following:
cnt = 0;
if ( a() && b() ) {}
System.out.println( cnt );
It shall print 1.
While if you execute the following:
cnt = 0;
if ( a() & b() ) {}
System.out.println( cnt );
It shall print 2. Because in the latter case b() must be evaluated as per the language specs while in the first case b() must not be evaluated, as per the language specs.
You can use & in situations where you have to evaluate both subexpressions. For example, if they both have side effects that are observable by the rest of your application.
Perhaps the 2nd evaluation is in the form of an assignment statement or method call, in which case you might want it to execute. I wouldn't use bitwise operators in place of logical operators like this tho. If you need something to execute passed &&, then do it prior to your logical statement and store the result in a variable.
if(0 != ((a > b) ? 1 : 0) & ((c < d) ? 1 : 0)) {
// but really... (a > b) && (c < d), assuming no side-effects
}
...just use the logical operators (&& and ||) for conditions ;-) That is what they were designed for. If non-shortcircuit behavior is required, then restructure the code accordingly.
I think I have seen one case that had a somewhat valid use of & in this context, but I do not recall what it was so I mustn't have found it that valid ;-) In languages like C/C++ where there is no discreet "boolean" type, the (input) and result of & can be treated such that 0 -> false and non-0 -> true. As can be seen, however, Java has to jump through some fun to get bool -> int -> bool.
The only justification for a bit-wise operator is, well, bit-wise operations, IMOHO. Bit-wise operators are most useful when performing some sort of encoding including "bit fields" and "bit masks". They are also useful when dealing with fun arising from Java's signed-only bytes, etc.
I think the bigger (only?) point to take away is that && and || are short-circuiting -- they are actually the only operators with this behavior (arguments over ?: excluded); the rest is just to explain the eager-behavior of bit-wise operators. This just goes to re-enforce the rule: do not cause side-effects in conditionals (outside of a few well-accepted idioms, but even then, keep it simple).
Happy coding.
Examples of bit-wise usage:
Imagine the use of flags which are stored into a single "integer" slot in a serialized format:
int flags = 0;
if (this.encypted) {
flags |= EncryptedMode;
}
out.write(flags);
// later on
int flags = in.readInt();
this.encrypted = (flags & EncryptedMode) != 0;
Reading the "unsigned value" of a byte:
byte[] data = {-42, ...}; // read in from file or something
int unsignedByte = data[0] & 0xFF;
Your book is confusing things. For the most part, you will only use '&&' and '||'. The single ones, '&' and '|', are bitwise operators - you can read more about them here: http://download.oracle.com/javase/tutorial/java/nutsandbolts/op3.html
The use of a non-short-circuit operator may speed up performance-critical code by avoiding branch mis-prediction stalls, which could easily amount to a dozen or more clock cycles.
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