OR operator - which statement is more efficient? - java

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 &&

Related

Boolean logical operators for flow controls in java

Can't we use Boolean logical operators (such as &,|,!,^ etc) in java flow controls ( for loop,while loop etc) ???
I want to print all even numbers between 1 and 100.So I used below two source codes.
import java.util.*;
class Example{
public static void main(String args[]){
int i=1;
while(i<100){
if(i%2==0)
System.out.print(i+" ");
i++;
}
}
}
This code is compiled and prints all even numbers between 1 and 100.
import java.util.*;
class Example{
public static void main(String args[]){
int i=1;
while(i<100 & i%2==0){
System.out.print(i+" ");
i++;
}
}
}
This code is compiled without any error.but doesn't give any print.
Why is that ?
Can't we use Boolean logical operators within a while loop ?
Remember that the while loop condition is the condition to continue the loop, which means that when the condition is false, the loop stops.
If you negate the condition in the second code:
!(i<100 & i%2==0)
Using De Morgan's Law, This is equivalent to:
i>=100 | i%2!=0
Or in words:
i is greater than or equal to 100 OR i is odd.
This is the stopping condition of the while loop. Well, i is initially 1, which is odd, so the loop stops without even executing one iteration.
In other words, you can't rewrite the first code as the second code. They are not equivalent. What goes in the if condition goes in the if condition. You can't "merge" it into the while condition, because they are for different purposes.
I also recommend && for the logical AND, as it only evaluates the right operand when necessary. For more info, see What is the difference between & and && in Java?
The error is in this line:
while(i<100 & i%2==0){
& should be replaced with &&:
while(i<100 && i%2==0){
U have tearn the logical operators...
and it is a logical operator it can be true only if 2 operators are true( x>5 and y<7) will be true if only x>5 is true and y<7 is true that is give us the condition is true but if one of them is not verified the condition is false....
but if we have or operator the condition will be true only if one of them is true or both........
so let's explain ur code.
You have condition (i<100 and i%2==0).
0%2 ==0 so it is true and of course i<100 so while returns true(both true at the same time) but when i==1 here we have a problem 1%2!=0 so i<100 is true but i%2==0 is false so we get **true && false ** the result is false .
(true && true==true) (false && true==false) (false and false==false) (true ||true==true) (true || false==true) (false||false==false)

ORing true with some function

Supposed I have a method fun()
boolean fun()
{
System.out.println("Hello World");
return true;
}
I also have a variable a
boolean a = true;
Now if I write
boolean b = a || fun();
will Java evaluate the right hand side of || or will it stop (since a is already true, so the answer is always going to be true and hence it doesn't evaluate the right hand side of ||).
See documentation from oracle:
The Conditional Operators
The && and || operators perform Conditional-AND and Conditional-OR operations on two boolean expressions.
These operators exhibit "short-circuiting" behavior, which means that the second operand is evaluated only if needed.
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html
So, java will NOT evaluate the fun() expression here, since the "short-circuit" a already determines the final value.
If one needs fun() to be evaluated, a quick fix can be as following:
boolean b = fun() || a;
or
boolean funValue = fun();
boolean b = a || funValue;
Java will not evaluate the right expression.
The same goes for && in case the first expression evaluates to false.
This is required, so you can do things like:
if (a != null && !a.isEmpty()) {
//...
}

How java test conditions [duplicate]

This question already has answers here:
Does Java evaluate remaining conditions after boolean result is known?
(7 answers)
Closed 7 years ago.
Does java calculate the second condition in ( test1 || test2 ) if the first one is true ?
I use Optional and I have something like that :
if (!opt.isPresent() || opt.get() == currentPlayer.getSelectedRegion())
and there will be a problem if the first test is true and java compute the second test.
If first condition is true second condition is not evaluated.
If first condition is false also second condition is evaluated.
That's why you can write a code like the following without a NullPointerException
if (str == null || str.length() == 0) {
// do something
}
The operator | (instead of || ) will evaluated both conditions
So the code
if (str == null | str.length() == 0) {
// do something
}
can generate a NullPointerException if str is null
Does java calculate the second condition in ( test1 || test2 ) if the first one is true ?
No. Boolean or will short-circuit, the first true is sufficient to make the expression true. No further conditions will be evaluated after that.
If you use the || and &&, rather than the | and &, Java will not bother to evaluate the right-hand operand.
No, java short-cut operators, the second argument is not evaluated if the first is. Ore more formal:
for x || y, y is only evaluated if x is false; and
for x && y, x is only evaluated if y is true.
This will increase performance and can be both useful and tricky:
usefull: to prevent you from doing things such that an error is thrown. The most typical example is the null check:
if(x != null && x.someTest())
this will prevent .someTest being called if x is null.
tricky: the problematic aspect can be if you call a method that does not only return something, but changes state as well. For instance:
public class Foo {
private int checked = 0;
bool someCondition () {
return (checked % 2) == 0;
}
bool neverChecked () {
checked++;
return checked == 1;
}
}
if you now call:
if(foo.someCondition() || foo.neverChecked());
this is one of the main reasons it is adviseable to keep "getters" (thinks that calculate things of an object), and "setters" (things that modify the state of an object), clearly separated. From the moment you start mixing, one can get complicated behavior in some circumstances.
it can be the intention that you always increment checked, but it will only if .someCondition happens to be false.

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

Does Java waste time to check conditionA in "if(isOK && conditionA)" if isOK=false?

Ok, i am building program to check many fields. If at least 1 field is not ok then i don't want my program to spend time to check other fields. So let look at this code:
// Util.isReadyToUse method return true if the string is ready for using, & return false if it is not.
boolean isOK=true;
if(!Util.isReadyToUse(firstName)){
isOK=false;
}
else if(isOK && !Util.isReadyToUse(lastName)){
isOK=false;
}
else if(isOK && !Util.isReadyToUse(email)){
isOK=false;
}
.....more checking
if(isOK) {
//do sthing
}
Ok, when running, the program will first check !Util.isReadyToUse(firstName). Suppose it returns (isOK=false). Next the program will check isOK && !Util.isReadyToUse(lastName).
So my question here is that Since the isOK currently false, then will the program spend time to check the condition !Util.isReadyToUse(lastName) after &&?
Ok, As a human being, if you see isOK=false and now you see isOK && !Util.isReadyToUse(email), then you don't want to waste time to look at !Util.isReadyToUse(email) since isOK=false and u saw && after isOK.
Will machine also work like that?
I am thinking to use break but why people say break doesn't work in if statement:
if(!Util.isReadyToUse(firstName)){
isOK=false;
break;
}
else if(isOK && !Util.isReadyToUse(lastName)){
isOK=false;
break;
}......
What is the best solution in this situation?
So my question here is that Since the isOK currently false, then will
the program spend time to check the condition
!Util.isReadyToUse(lastName) after &&?
Java is smart, if you have a condition if(somethingFlase && something), then something won't be reached due to Short-circuit evaluation. Since the whole expression will be false regardless of the second condition, there is no need for Java to evaluate that.
From 15.23. Conditional-And Operator &&:
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(a && b) - if a is false, b won't be checked.
if(a && b) - if a is true, b will be checked, because if it's false, the expression will be false.
if(a || b) - if a is true, b won't be checked, because this is true anyway.
if(a || b) - if a is false, b will be checked, because if b is true then it'll be true.
No, it shortcuts the rest of the predicate.
That's you'll see things like
if(A != null && A.SomeVal == someOtherVal)
Java supports what is referred to as Short-Circuit Evaluation. See this page:
http://en.wikipedia.org/wiki/Short-circuit_evaluation
What this means is that if the first boolean in your statement is enough to satisfy the statement, then the rest of the values are skipped. If we have the following:
boolean a = false;
boolean b = true;
if(a && b) /*Do something*/;
'b' will never be checked, because the false value for 'a' was enough to break out of the if statement.
That being said, your program will never take advantage of this because the only time isOK is set to false is within one of your else if statements.
As the other responders mentioned Java will do the smart thing.
But it could be the case that you want Java to continue to check, in that case you can use & vs && or | vs ||.
if (someMethod() | anotherMethod() {
If the first method reutrns true, Java will still execute the second method.
if (someMethod() & anotherMethod() {
If the first method is false, Java will still execute the second method.
No, Java won't "waste time" for it. It's called short circuit evaluation.
This mechanism is commonly used e.g. for null checking :
if (foo != null && foo.neverFailsWithNPE()) {
// ...
}
You don't need to use break on an if..else if.. else statement because once it finds a condition which is true the rest aren't even looked at.

Categories

Resources