Java: OR Operator after AND in "If" Statement - java

Based on this and this answer Java employs short circuiting with regard to && and || operators. It also gives && higher precedence over ||. Yet the following code evaluates to true:
boolean condition1 = true;
boolean condition2 = true;
boolean condition3 = true;
if ( !condition3 && condition1 || condition2 ) {
System.out.println("Condition is true"); // prints Condition is true
}
Since condition3 is set to true this should cause !condition3 to be false so why is Java even checking condition1?
If I add parentheses around the first condition it still evaluates to true:
if ( (!condition3) && condition1 || condition2 ) {
System.out.println("Condition is true");
}
I understand why this code evaluates to true:
if ( condition1 || condition2 && !condition3) {
System.out.println("Condition is true");
}
Because once Java encounters the || after condition1 it doesn't even bother checking the following conditions. But I don't understand why the first two examples evaluate to true.
My goal is to require condition3 to be false and then have either conditon1 or condition2 (or both) to be true (but if condition3 is true then I don't want print statement to execute regardless of how condition1 and condition2 evaluate)
Thanks

You said:
It also gives && higher precedence over ||.
which means !condition3 && condition1 will be evaluated first.
So this
!condition3 && condition1 || condition2
equals:
(!condition3 && condition1) || condition2
since condition2 is true, the expression is true.

Related

OR operator inside of If statements

else if (!emailGet.endsWith(".com") && !emailGet.endsWith(".info")){
errors += "Email should end with .info or .com";
}
Why is && playing the role of an "OR" statement, but when I use "OR" itself it does nothing. The only way I can get the code to tell me if one or the other statement is true, is by using && which evaluates 2 statements unlike "OR", the logic behind using && makes no sense to me. Am I missing something?
Note the following concepts about || and && operators:
When multiple conditions are combined with &&, the evaluation of the conditions continues as long as conditions evaluate as true. If any condition evaluates as false, the further evaluation stops and the combination results in false. The combination results in true only when all the conditions evaluate as true.
When multiple conditions are combined with ||, the evaluation of the conditions continues as long as conditions evaluate as false. If any condition evaluates as true, the further evaluation stops and the combination results in true. The combination results in false only when all the conditions evaluate as false.
Based on these concepts,
!emailGet.endsWith(".com") && !emailGet.endsWith(".info")
is same as
!(emailGet.endsWith(".com") || emailGet.endsWith(".info"))
Let's analyse them in the following scenarios:
Let's say emailGet = "a#b.com"
!emailGet.endsWith(".com") && !emailGet.endsWith(".info") => !(true) && !emailGet.endsWith(".info") => false && !emailGet.endsWith(".info") => false.
!(emailGet.endsWith(".com") || emailGet.endsWith(".info")) => !(true || emailGet.endsWith(".info")) => !(true) => false.
Let's say emailGet = "a#b.info"
!emailGet.endsWith(".com") && !emailGet.endsWith(".info") => !(false) && !emailGet.endsWith(".info") => true && !(true) => true && false => false.
!(emailGet.endsWith(".com") || emailGet.endsWith(".info")) => !(false || true) => !(true) => false.
Let's say emailGet = "a#b.c"
!emailGet.endsWith(".com") && !emailGet.endsWith(".info") => !(false) && !emailGet.endsWith(".info") => true && !(false) => true && true => true.
!(emailGet.endsWith(".com") || emailGet.endsWith(".info")) => !(false || false) => !(false) => true.
I think the negatives in combination with and (&&) and or (||)
caused misunderstanding.
if (!emailGet.endsWith(".com") && !emailGet.endsWith(".info")) {
errors += "Email should end with .info or .com";
}
if (emailGet.endsWith(".com") || emailGet.endsWith(".info")) {
sucesses += "Email did end with .info or .com";
}
if (!(emailGet.endsWith(".com") || emailGet.endsWith(".info"))) {
errors += "Email should end with .info or .com";
}
It is always:
! <this-case> && ! <other-case>
<this-case> || <other-case>
Should you see
! <this-case> || ! <other-case> // *** ERROR *** always true
<this-case> && <other-case> // *** ERROR *** always false
you know it is wrong.
Yes, in java the boolean operator for conditional or is ||.(represented by two vertical bars or "pipes", not lowercase L's) Similarly you've already found the boolean operator for conditional and which is &&. These two are not the same although they will both evaluate to true when both statements are true.

If else condition combine && and || in one row statement

Thank you for your time, i create some if else statement in checkbox to display result, can i combine && and || condition in one statement? for example
if (radioMale && chestPain && (leftArm || bothArm || jaw || throat)) {
highPossibilityOfHeartDisease = true;
}
User have to tick radioMale && chest pain && can tick either leftArm, bothArm, jaw or throat (one or more) to return true for highPossibilityOfHeartDisease. Is the code above valid? need some help here.
Yes you can combine && and || in a if...else statement. See it logically before considering programmatic side.
true AND true AND true AND (true OR false OR false) the condition inside brackets will be verified and set as one resulted Boolean that may be true or false according to the condition.
Then the resulting booleans will be verified linearly as normal.
You can read some articles explaining maths of boolean expressions, for example:
The Mathematics of Boolean Algebra: From StanFord University
Boolean Expressions
Boolean algebra

Multiple conditions in one if statement in JAVA [duplicate]

Lets say I have this:
if(bool1 && bool2 && bool3) {
...
}
Now. Is Java smart enough to skip checking bool2 and bool3 if bool1 was evaluated to false? Does java even check them from left to right?
I'm asking this because i was "sorting" the conditions inside my if statements by the time it takes to do them (starting with the cheapest ones on the left). Now I'm not sure if this gives me any performance benefits because i don't know how Java handles this.
Yes, Java (similar to other mainstream languages) uses lazy evaluation short-circuiting which means it evaluates as little as possible.
This means that the following code is completely safe:
if(p != null && p.getAge() > 10)
Also, a || b never evaluates b if a evaluates to true.
Is Java smart enough to skip checking bool2 and bool2 if bool1 was evaluated to false?
Its not a matter of being smart, its a requirement specified in the language. Otherwise you couldn't write expressions like.
if(s != null && s.length() > 0)
or
if(s == null || s.length() == 0)
BTW if you use & and | it will always evaluate both sides of the expression.
Please look up the difference between & and && in Java (the same applies to | and ||).
& and | are just logical operators, while && and || are conditional logical operators, which in your example means that
if(bool1 && bool2 && bool3) {
will skip bool2 and bool3 if bool1 is false, and
if(bool1 & bool2 & bool3) {
will evaluate all conditions regardless of their values.
For example, given:
boolean foo() {
System.out.println("foo");
return true;
}
if(foo() | foo()) will print foo twice, and if(foo() || foo()) - just once.
Yes,that is called short-circuiting.
Please take a look at this wikipedia page on short-circuiting

OR operator - which statement is more efficient?

When I use the OR operator, only one expression has to be true. Is the first if statement more efficient because java checks only the first expression? Or does java check both?
public class Test {
public static void main(String args[]) {
boolean test = true;
if (test || calculate()) {
// do something
}
if (calculate() || test) {
// do something
}
}
public static boolean calculate() {
// processor-intensive algorithm
}
}
if (test || calculate())
would never call calculate() when test is true, since || operator is short circuited, so that statement is more efficient when test is true.
Yes , it is . because calculate() is never called , as long as test is true and it is the contract of || statements.
From ยง15.24,
The conditional-or operator || operator is like | , but
evaluates its right-hand operand only if the value of its left-hand
operand is false.
There are two or operators:
if ( condition | condition2 ){
Here, it will test the second condition regardless of the outcome of the second condition.
if ( condition || condition2 ){
Here, the second condition will only be checked if the first condition returned false.
The same way of double operators is implemented for the 'and' operators & and &&

if the first condition fails then the second condition will be examine -java [duplicate]

This question already has answers here:
short-circuiting behavior of conditional OR operator(||)
(3 answers)
Two conditions in one if statement does the second matter if the first is false?
(7 answers)
Closed 8 years ago.
if i have a while condition in java as follows while(j>=1 && i<=7) my question is if the first condition fails then the second condition will be examine??
in other word if j=0 the compiler will check if I<=7 or it will ignore it .
please help me
thank you
No, if the first condition returns false then the whole expression automatically returns false.
Java will not bother examining the other condition.
(j>=1 && i<=7 && cond1 && cond2 && ... && condN) // will evaluate until the one condition fails
(j>=1 & i<=7 & cond1 & cond2 & ... & condN) // will evaluate all the conditions
and with or
(j>=1 || i<=7 || cond1 || cond2 || ... || condN) // will evaluate until the one condition is true
(j>=1 | i<=7 | cond1 | cond2 | ... | condN) // will evaluate all conditions
example:
lets use this 2 methods:
public boolean isTrue(){
System.out.println("true");
return true;
}
public boolean isFalse(){
System.out.println("false");
return false;
}
so, in the first case:
boolean cond = isFalse() && isTrue();
output is:
false
value of cond is false
and in the second case:
boolean cond = isFalse() & isTrue();
output is:
false
true
value of cond is false
It won't. Logical operator && shortcuts and will stop evaluation if its left side argument is false.
Note that Java also has logical (in addition to the bitwise &!) operator &, which will not shortcut; therefore, if a is a boolean expression evaluating to false in a & b, then b will be evaluated nonetheless (but the end result will still be false).
No while evaluating && if the first condition is false then it doesn't evaluate the second condition.
Similarly while evaluating || if the first condition is true then the second condition is not evaluated.
This is called lazy evaluation. In order to make it greedy, use the single ampersand logical operator. In that case, it will also evaluate the second conditional, even if the first turns out to be false.
I agree with what others are saying. The answer is no. This is known as short-circuit evaluation.
http://en.wikipedia.org/wiki/Short-circuit_evaluation

Categories

Resources