This question already has answers here:
Java logical operator short-circuiting
(10 answers)
Closed 6 years ago.
I work on Java 8 and I have a simple issue that I have not figured out.
I have a 3 methods which are validating the data from db and returning true or false based on whether they got a row or not. The tricky part is, even if I know that the first part
is returning false, I still want it to check for the other two methods. I have written my code like this :
boolean flag = true;
flag = flag && validateMethod1();
flag = flag && validateMethod2();
flag = flag && validateMethod3();
return flag;
The issue is, when validateMethod1() returns false, it is not calling validateMethod2(). Can someone explan why ?
I tried this :
boolean flag = true;
flag = flag & validateMethod1();
flag = flag & validateMethod2();
flag = flag & validateMethod3();
return flag;
Still face the same issue.
&& is a short circuited AND operator. It doesn't evaluate the second operand if the first operand is evaluated to false.
In order to evaluate all the operands, use the non-short-circuit version of the AND operator :
return validateMethod1() & validateMethod2() & validateMethod3();
As you can see, your logic can be reduced to a single line of code.
Java uses sort-circuit evaluation of expressions - i.e. as soon as it knows for sure the result will be false, it stops the evaluation.
Since your expression is a conjunction, once flag is found to be false, it is clear the whole expression will be false.
One way around it (quite verbose) is:
boolean flag1 = validateMethod1();
boolean flag2 = validateMethod2();
boolean flag3 = validateMethod3();
return flag1 && flag2 && flag3;
That's because you are using short circuit && instead of &, which leads to check only first argument in this case, when this argument is false.
The & operator, when used as logical operator, always evaluate both sides.
Related
This question already has answers here:
Difference between "!= true" and "== false"?
(2 answers)
Closed 4 years ago.
I've faced a situation where "!= true" gave me a different output than "= false". I thought that if something isn't true it'd be false automatically. Can anyone please explain me how it works? Thanks!
It gives different output because you confused with Comparison vs Assignment
!= will compares the value with RHS and =false do an assignment to LHS. If you wish to check for equality use the == operator instead.
And I don't think it won't make much difference when you compare in difference styles since both do the same job unless you have some weird line of code.
== is comparison operator, = is assignment operator
!= is not equal to, and == is equal to
In addition to the other answers,
if something isn't true it'd be false automatically
is also wrong.
(Boolean) null != true is true, but (Boolean) null == false is of course false.
!= true is used a comparator. It compare the LHS to true. However = false is an assignment. An equivalent of != true will be == false. == is also a comparator operator that checks for equality while != checks for inequality.
It is all about writing or checking the value...
look this example...
boolean flag = true; a boolean variable is defined and assig to true
if (flag!=true) { //you should do instead if(!flag)
//this is checking the content of the flag variable
}
if (flag=true) { //you should do instad if(flag)
//this is writing the content of the flag assigning it to true
}
In a boolean statement, if you use != true, if the boolean is null, the operator will allow it to run whatever it is comparing. If you use == false, it will only run if the boolean is currently set to false.
First is comparison, in later case you are assigning
This question already has answers here:
Using NOT operator in IF conditions
(8 answers)
Closed 7 years ago.
I have a boolean variable collision initialized to false.
Now in an if statement, suppose my if condition is the following:
if(!collision)
does this mean that the if statement will execute if collision is the opposite of what is initialized? Meaning, will it execute when !collision returns true?
Just a bit confused since I initialized it to false, and I want this if statement to run when collision is false, but don't know if !collision is the right way to do it or not.
Code as requested. Still confused on what the condition would be. I have collision initialized to false. As a result, I want the statement to be executed when it is false. Should I write if(collision) or if(!collision)?
boolean collision = false;
boolean winner = false;
while(!winner){
//Main loop where user will be able to move the ships and try to destroy the ship
//boolean shipAlive = true/false; YET TO ADD!
//if(!shipAlive) -> winner = true; YET TO ADD!
//movement of ships
if(!collision){
System.out.println("Player 1: L, R, or S? (L = Left, R = Right, S = Stay)");
String p1Input = IO.readString();
int k = movement(p1Input, player1);
while (k == 1){
System.out.print("Error! Enter either L, R or S: ");
p1Input = IO.readString();
k = movement(p1Input, player1);
}
}
collision = fireProjectileUp();
if(collision){
winner = true;
}
Yes, it is the right way to do it:
In if (!someBoolExpr) { ... }, the "then-clause" will run if someBoolExpr == false.
See the JLS ยง15.15.6: Logical Complement Operator ! for more information:
The value of the unary logical complement expression is true if the (possibly converted) operand value is false, and false if the (possibly converted) operand value is true.
! represents NOT in Java. So if you have something like
if(!true) {
//doSomething
} else {
//Something else --- This is executed.
}
if(!false) {
//doSomething --- This is executed.
} else {
//Something else
}
true and false are the final result of your comparison operations
! means not, so your expression will be translated to if(NOcollision).
Check documentation for further info.
Yes, your if statement will be executed when collision is false.
!false returns true
You've asked a question, but I suspect this is a bit of an XY problem for you. You've asked about clarification of the ! operator, then proceeded to explain exactly what a not operation is.
When constructing your conditions, you want to manipulate the logic so that it evaluates to true when you want it too. For example, I want something to run if there has been a collision.
if(collision)
Simple. This is because this will evaluate to true when you want it too. Now you want something to run if their hasn't been a collision.
if(!collision)
Once again, it evaluates to true if collision is false. Or, when you want it too. The trick here is working out how to express what you want in a way that the compiler understands, and this is done through logical expressions that resolve to some boolean true or boolean false.
EDIT
Just incase, ! operator is simply the opposite of the value. !true is false, !false is true. Going by what I explained above, you can combine this knowledge to create your solution.
When if(!collision) is executed then first of all it checks the value of collision. Let's assume its is 'false'. Then ! operator converts it to true. opposite of false. Then the value is 'true ' so, if statement will execute its code block.
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
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.
I've seen this before in code, but forgotten it. Basically it toggles a boolean variable. If it's true, it'll set to false and vice-versa. But unfortunately forgot the syntax.
It's basically a one liner for this:
if (myVar) {
myVar = false;
} else {
myVar = true;
}
It's something like this, but don't know what it's called or the correct syntax of it:
myVar = myVar : false ? true;
How about
myVar = !myVar
?
myVar = myVar ? false : true; is using the conditional operator.
You can just do this though
myVar = !myVar;
Another option is XOR:
myVar ^= true;
It's notable in that only the LHS of the assignment ever changes; the right side is constant and will toggle any boolean variable. Negation's more self-documenting IMO, though.
What you are thinking of is the conditional operator:
myVar = myVvar ? false : true;
(As you see, a lot of people call this "the ternary operator", but that only means that it is an operator with three operands. As it happens, there is only one operator with three operands in this language, but it still says nothing about what the operator does.)
It's of course easier to use the negation operator:
myVar = !myVar;
The smallest code I can think of at the moment. I don't know what its called (if it has a name, as you seem to suggest)
myVar = !myVar
What you're talking about is the "ternary" or "conditional" operator, which does an inline substitution as per a condition.
The syntax is:
condition ? trueValue : falseValue
I usually throw parentheses around my condition, sometimes around the whole conditional operator. Depends on how much I'm trying to delineate it from everything else.
So for example, suppose you want to return the larger of two numbers:
public int max(int a, int b)
{
return (a > b) ? a : b;
}
Notice that it can be substituted into the middle of something else.
Okay, now let's tackle your actual question about toggling a boolean type.
myVar = (myVar) ? false : true;
is how you would do it with the conditional operator. (Again, parentheses aren't required, I just favor them.)
But there's a simpler way to toggle the boolean... using the logical NOT ("!") operator:
myVar = !myVar;
Keep it simple. :-)
if(myVar == true)
{
myVar = false;
}
else if (myVar == false)
{
myVar = true;
}
else
{
myVar = FILE_NOT_FOUND
}
This also works :P
v=v?!v:!v;
There is a ternary operator (wikipedia). Which allows you to write a condensed if-else statement like in the second example.
In java:
myVar = (myVar) ? true : false;
There is also the NOT operator, which toggles a boolean variable. In java that is !. I believe that is what you want.
myVar = !myVar;
public boolean toggle(boolean bool)
{
return !bool;
}
I recently (on my own) found a similar answer to one already stated here. However, the simplest and shortest (non-repeating variable name with least code) answer is:
formControl.disabled ^= 1;
This works best in JavaScript when wanting to toggle boolean, DOM-based attributes (for example, a form control/input's disabled property -- going from a non-editable to edit state). After much searching (with no result that I liked) and some trial and error, I found my solution to be the simplest (however, true instead of a 1 would be clearer -- as was previously posted).
Since this syntax isn't very clear, immediately, I would not advise using it very often (I believe it is appropriate when the variable or property makes the context obvious). I have posted this response (instead of making it a comment) because the context in which the XOR bitwise self-assignment should be used is very important. This "trick" should mostly be avoided when considering best practices.
As others have noted, there are two ways to negate something: "lvalue = !lvalue;" and "lvalue ^= 1;". It's important to recognize the differences.
Saying "lvalue = !lvalue" will cause lvalue to be set to 1 if it was zero, and 0 if it was set to anything else. The lvalue will be evaluated twice; this is not a factor for simple variables, but saying "someArray[index1][index2][index3][index4] = !someArray[index1][index2][index3][index4]" could slow things down.
Saying "lvalue ^= 1;" will cause lvalue to be set to 1 if it was 0, 0 if it was 1, and something else if it was neither zero nor 1. The lvalue need only be specified or evaluated once, and if the value is known to be either zero or 1, this form is likely to be faster.
Too bad there's no auto-negate operator; there are times such a thing would be handy.
You can also use the binary form of negation as shown here.
if ((v == true) && !(v = false)) {
v != true; /* negate with true if true. */
} else {
v =! false; /* negate with false if false. */
}