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.
Related
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
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.
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
I'm studying some Java at the moment at I've come across the following piece of code. I understand how the typical ternary operator (e.g. the line beginning with "boolean a" below), but I can't understand how to read the expression on the line beginning with "boolean b". Any help on how to read this line would be much appreciated! Thanks!
public class Ternary{
public static void main (String[] args){
int x = 10;
int i = 2;
boolean a = x > 10 ? true: false;
boolean b = a = true ? ++i > 2 ? true:false:false;
System.out.print(b);
}
}
Break it up like this:
true ? (++i > 2 ? true
: false)
: false;
So here the testing condition is always set to true. So the branch of the ternary that executes is the ++i > 2 ? true : false part.
This simply checks to see if after incrementing, i is greater than 2. If so, it will return true. Otherwise it will return false.
This whole expression is actually needlessly complex. It can simply be written as such:
boolean b = a = (++ i > 2);
However, the code is probably logically incorrect since this abstruse expression doesn't make that much sense. Since the previous line sets the value of a, I'm assuming that the next line actually intends to test a. So the actual intent might be:
boolean b = a == true ? ++i > 2 ? true : false : false; //notice the ==
In which case you can break it up as:
(a == true) ? (++i > 2 ? true
: false)
: false;
But you don't need to actually do a == true since a is already a boolean, so you can do:
a ? (++i > 2 ? true
: false)
: false;
Here, it checks to see if a is true. If it is, it performs the check we already went over (i.e., to see if the incremented value of i is greater than 2), otherwise it returns false.
But even this complicated expression can be simplified to just:
boolean b = a && (++i > 2);
Ah! Never write code like that. But I would assume that is not written by you. But you can read it like this:
// I assume that's `a == true` instead of `a = true`
boolean b = a == true ? (++i > 2 ? true : false)
: false;
which can be broken further as:
// a == true is better written as just `a`. You shouldn't do boolean comparison
// like that.
boolean b = a ? (++i > 2) : false;
// If that is really a = true, then you can break it as:
boolean b = a = true ? (++i > 2) : false;
which can be further broken down as:
// If that is `a == true`
boolean b = a && (++i > 2)
// If that is really a = true, then you can break it as:
boolean b = a = (++i > 2);
Also, the first assignment:
boolean a = x > 10 ? true: false;
can also be written as:
boolean a = x > 10;
boolean nu = f=='f' && t=='f'; //0
boolean ei = f=='f' && t=='t'; //1
boolean zw = f=='t' && t=='f'; //2
boolean dr = f=='t' && t=='t'; //3
System.out.println( nu ? 0 : ei ? 1 : zw ? 2 : dr ? 3 : "invalid");
In boolean b = a = true ? ++i > 2 ? true:false:false; the following happens:
a = true
This will give a true value and evaluate to true.
Than we get another condition, ++i > 2 from ++i > 2 ? true:false, which will be also true in this case. The outcome will be true.
Ternary operators are
condition then true or false
The condition is always true (because a equals true).
Then the result is true because ++i is greater than 2 (it's 3).
Therefore, it assigns true to b. If the condition was false, it would assign false. That false would be assigned from the last false.
It would help if you could use parentheses and review that code as follows;
boolean b = a = (true ? (++i > 2 ? true : false) : false);
You can think it as:
if (true) // # If Number:1
{
if (++i > 2) // # If Number:2
{
a = true;
}
else { a = false; }
}
else { a = false; }
Where if(true) is a Tautology and If Number:2 will always be executed. Therefore; it becomes;
if (++i > 2)
{
a = true;
}
else { a = false; }
Which can be evaluated to; a = (++i > 2) ? true : false); and which becomes: a = ++i > 2 as a result b = a which is ++i > 2.
With some guesses at what is being attempted and some renaming of variables, and assuming the a = true was meant to be a == true you get:
boolean failed = result > 10 ? true: false;
boolean b = failed ? ++retries > 2 ? true:false:false;
This can then be tidied up to the much more logical:
boolean failed = result > 10;
boolean giveUp = failed && ++retries > 2;
Horrible code!
There are a couple of clues that the b = a = true ? ... should be b = a == true ? ..., since otherwise the previous line is a useless assignment (a is never read), and the final false of the line becomes unreachable code. The compiler will tell you that.
I'm going to answer assuming a corrected == - but you'll know whether it was a typo on your part, an unreliable source, or a 'spot the bug' test, and be able to use the same techniques on whatever code you like.
The trick is to refactor it step by step. First add brackets and indentation based on precedence rules.
b = a == true ? ++i > 2 ? true:false:false;
... becomes ...
b = (a == true)
? (++i > 2 ? true:false)
:false;
Next note that:
a == true is equivalent to a.
boolean x = a ? true : false; is equivalent to boolean x = a.
Therefore:
b = a
? (++i > 2)
:false;
or:
b = a && ( ++i > 2 );
If this is "serious" code, the way to approach this would be to write a set of unit tests that cover all the possible input cases. Then make these refactorings one at a time, each time re-running the tests to ensure that you've not changed the behaviour of the code.
Notice that there are no true or false literals in the reduced form. Seeing boolean literals in a ternary operation -- or indeed, ternary expressions for boolean values at all -- is a code smell, since the non-ternary version is usually simpler and clearer.
Ternary expressions are very useful for their intended purpose, which is mapping boolean conditions to non-boolean outputs:
shippingPrice = orderTotal >= freeShippingThreshold ? 0 : getStandardShipping();
I have a table which contain two columns in database status and diff_id status column may contain these values
DFG_SGG_RGRG
NULL
EF_SFEG_FTT
IFEF_RGG
abc_id may contain these values
null
43546
45346
45746
53465
Now I am getting these values in an object t ,so I have to make an condition where status column is null and abc_id should have value 435465666L so I have prefer to write an if like shown below please advise is it correct as I am confused between && operator || operator
if ( if f.getStatus()== null || abc_id() .longValue()==435465666L )
{
//perform the logic
}
Please advise - is it correct approach?
& = "and"
&& = "and, but only if preceding condition was true"
| = "or"
|| = "or, but only if preceding condition was false"
If you're saying:
AND - use &&
OR - use ||
Remebmer also that && takes precedence over ||.
If both conditions must be true you need to use the && operator.
if (f.getStatus()== null && abc_id().longValue()==435465666L )
{
//perform the logic
}
Using the && operator causes a condition to be true only if both conditions are true. For example:
System.out.println(true && false); //prints false
System.out.println(false && false); //prints false
System.out.println(true && true); //prints true
System.out.println(false && true); //prints false
The || operator causes a condition to be true if one of the conditions is true.
System.out.println(true || false); //prints true
System.out.println(false || false); //prints false
System.out.println(true || true); //prints true
System.out.println(false || true); //prints true
use
if (f.getStatus()== null && abc_id().longValue() == 435465666L )
{
//perform the logic
}