Difference between "!= true" and "= false" [duplicate] - java

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

Related

Java Boolean Check [duplicate]

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.

Clarification on "!" operator in java [duplicate]

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.

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.

How do you put a if, else statement within a for statement

How do you put an if...else statement within a for statement?
This is the code:
// This is within a actionListener. When ever I press a button, this happens.
for (int i = 0; i < booleanVariable.length; i++) {
//length is 8
System.out.println("booleanVariable is" + booelanVariable[i]);
if (booleanVariable[i] = true) {
booleanVariable[i] = false;
System.out.println("booleanVariable was true")
break;
} else {
System.out.println(" booleanVariable is false");
}
}
This is the output over 3 presses:
booleanVariable is true
booleanVariable was true
//correct
booleanVariable is false
booleanVariable was true
//incorrect.
booleanVariable is false
booleanVariable was true
//incorrect
This means that, for some reason, even if booleanVariable is false, the output says is true, which is false.
What I've found:
Without the break; statement, the program goes around the for all 8 times and outputs exactly the same as without a break, only incorrect values another 5 times.
What I've tried:
Changing the if from true to false (out of desperation)
If within a While within a For
else, else if
case switch
Normally, I'd just use a switch, but I'm using booleans, and booleans dont work is switches.
If someone knows the answer, I'd be forever grateful. Thanks.
Change your
if (booleanVariable[i] = true) {
to
if (booleanVariable[i] == true) {
You need to use == operator for comparison. One = sets the value to true which returns always true.
You can also change it to
if (booleanVariable[i]) {
Your problem may be in this line:
if (booleanVariable[i] = true) {
Boolean comparisons should use ==, unless you are intending to set the value to true. In any event, this line will always evaluate to true.
Note also that you never really need to compare to true, you can simply say something like:
if (booleanVariable[i]) {
since if the value is true, the code block will be entered, and if it is false, it will proceed to the else case.
You have to use == to compare the values. Yu use the = that asigns the value true to the variable so it will always be true
if (booleanVariable[i] == true)
There's an error in the if statement --
You are assigning true to the variable, that's why it's outputting true each time.
it needs to be == (equals) not = (assign).
if (booleanVariable[i]) instead of if (booleanVariable[i] = true)....= is assignment operator...you could also use == instead
You should change if (booleanVariable[i] = true) as if (booleanVariable[i] == true).
need '==' instead of '='.

Categories

Resources