What would the if condition be using this example.
A - if true, B or C must also be true; Pass
if false, B and C do not matter; Fail
B - if true, A must also be true and C can be false or true
if false, A must be true and C must be true; Pass, else Fail
C - if true, A must also be true and B can be false or true
if false, A must be true and B must be true; Pass, else Fail
I am not sure how to set this up. Here is what I think the if may look like:
//Not sure if the "or" needs to be double or single bar.
if(A && B | C){
//pass
}else{//fail}
The broken apart code for this logic would be this:
if(A){
if(B|C){
//PASS
}else{//fail}
}else{//fail}
Depending on the language you're working with it's mostly || double bars.
I think this will work:
if(A && (B || C)) {
pass;
} else {
fail;
}
This means if A is true and B or C is true pass, otherwise fail.
In Java, the difference btw single and double operators is that double operators (&& and ||) are short-circuit (i.e. if the result of the expression is pre-determined, the right side won't be executed).
e.g. in these cases, foo() would never be called:
false && foo(); // evaluates to false
true || foo(); // evaluates to true
but in these cases it would:
false & foo(); // still evaluates to false
true | foo(); // still evaluates to true
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.
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.
I'm trying to get prepared for the OCA Java certification and got stuck in some questions dealing assignment in if conditions. Can anyone explain me the reason of the different behaviours in the code below? By my point of view I'm just putting the same two boolean values in an "inclusive or" condition 6 times...
package pck;
class SuperMain{
boolean b;
public static void main(String args[]){
new SuperMain();
}
SuperMain(){
if(_true()|_false())
System.out.println(b); //1 - prints false
if(b=true|_false())
System.out.println(b); //2 - prints true
if(_true()|(b=false))
System.out.println(b); //3 - prints false
if((b=true)|_false())
System.out.println(b); //4 - prints false
if(b=true|(b=false))
System.out.println(b); //5 - prints true
if((b=true)|(b=false))
System.out.println(b); //6 - prints false
}
boolean _true(){return b=true;}
boolean _false(){return b=false;}
}
The difference is in precedence. | has higher precedence ("binds tighter") than =.
So this:
if(b=true|_false())
is effectively:
if (b = (true | _false()))
...
Likewise this:
if(b=true|(b=false))
is effectively:
if (b = (true | (b = false))
In these cases, the assignment of false to b occurs before the assignment of true to b... so b ends up being true. In every other case, the assignments occur in the opposite order.
I'm doing the oracle certified associate Java SE7 Programmer practice exams (the book) and came across a question, and I don't understand the answer even with the explanation.
Here's the explanation and the code:
It will print 3. The loop body is executed twice and the program will print 3.
I don't understand how the loop body is executed twice, maybe I don't understand what the b=!b means. Can someone explain please?
class TestClass {
public static void main(String args[]){
boolean b = false;
int i = 1;
do{
i + + ;
} while (b = !b);
System.out.println(i);
}
}
b = !b is an assignment which assigns the inverse of b to itself (effectively flipping between true and false)
in java, an assignment returns what was assigned (so that a=b=1 is possible)
therefore while (b=!b) will flip the value of b, and then check the value of b.
b=!b
Will always be true, why?
Because, what you are doing is that you insert to "b" the opposite value (T->F, F->T),and if there was no problem while (b = !b); will return TRUE....
So at your case while (b = !b); will always return true
Iteration 1
boolean b = false;
int i = 1;
do{
i++ ; // i = 2
} while (b = !b); // b = !false = true so one more execution
Iteration 2
do{
i++ ; // i = 3
} while (b = !b); // b = !true = false so loop breaks
So it will print 3. simple :)
Actually the confusion is with = sign. = is assigning operator where as == is the conditional operator. The first will assign the value whereas later will check for the condition. You can play with it and have some other result like
int a = 6;
int b = 10;
System.out.println(a = b);
System.out.println(a == b);
and you will get the idea.
At the end of the first iteration the variable i will be 2 because of the increment operator. The expression b=!b will result to true (b = !false) and set the variable b to true as well. So the loop gets executed again.
At the end of the second iteration the variable i is now 3. The expression b=!b will result to false (b = !true), which will be also the value of the variable b. So the whole do-while-loop terminates and the println() statement shows 3.
Keep in mind: = (assign operator) is not the same as == (equality check).
The condition
b = !b;
uses the assignment operator, which returns the value that has been assigned.
Initially, b is false, and therefore true is assigned to b, and used for the condition. The while loop therefore executes a second time. In this execution, b is true, and therefore false is assigned to b and used for the loop condition. The loop therefore exits.
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 &&