While deciding the order in which operators will operate, I am confused between following two statement.
Statement will be executed from left to right.
It will be executed according to precedence order of operators.
Following code executes from left to right
int i=5;
boolean b = i<5 && ++i<5;//line2
System.out.println(i);//prints 5
//left to right execution in line2.
//< is executed and ++ is not.Even though ++ has higher precedence.
But this code below seems to follow precedence order:
int a=1,b=1,c=1;
boolean b = a==b&&b==c;//line2: (a==b)&&(b==c)
/* In line2 code would not run from left to right.
First a==b is evaluated then b==c and then && operator.*/
I have asked partially this question here but did't get good enough explanation.
Can someone please clarify?
Assignment works from right to left. In your case, the boolean b will be assigned to whatever the expression on the right evaluates to:
a==b&&b==c
Note that assignment operators have different rules than logical/bitwise operators in terms of precedence (i.e. = doesn't have the same precedence as == or &&).
I think you need to know about logical AND and OR.
something && somethingElse - imagine that expression. It's gonna return true ONLY if both values are true. If both are false, or one of them is false - returns false. So, let's say that the first part is actually false (something=false). Like I said, if anything in this expression is false then there is no need to go further, because no matter what is the second one it's gonna return false anyway. That's why in your first example it doesn't go any further - there is no need, i is already not less than 5 so there is no reason to check the second part, because it's already gonna be false.
In your second example a==b is true, BUT we can't return true already, we need to check the second one, because like I said, if the second one is false then it has to return false. So the expression needs to go further to check the second part. Not like in first example where we could stop, here we need to keep checking.
When it comes to OR (||) rules are different. Only one of the parts needs to be true (that's why it's called or, this or that, doesn't matter, one truth is enough). So with || if the first part is true the we can return no matter what, but if the first part is false then we need to keep going no matter what, because the second one may be true.
i<5 && ++i<5;//line2
&&
[&&] eval LHS: i<5 to false
[&&] skip RHS: ++i<5 and yield false
And
//line2: (a==b)&&(b==c)
a==b&&b==c;
&&
[&&] eval LHS: a==b to true
[&&] eval RHS: b==c to true, yield true
The && is a short-cut operator that does not evaluate the right hand side.
The precedences are important for binary operators. The precedence of unary operators cannot reorder anything, but traditionally it has higher precedence, as it is tighter bound to the final value, and especially for postfix operators.
The prefix operator ++ has the important characteristic, that it is called before the evaluation of the term to which it is applied.
It goes without say, that the usage above is something to be get shot for, hung on the nearest AVL tree, tiered and feathered and chased out of town.
Related
This question already has answers here:
Java logical operator short-circuiting
(10 answers)
Closed 5 months ago.
When we're using an if-conditional, we specify the condition in a boolean expression such as following :
if(boolean expression).
If I have two variables in a boolean expression, such as (bagWeight > WEIGHT_LIMIT), does the order of the two variables in which they appear matter? In other words, can I swap those two variables' places such as following? (WEIGHT_LIMIT < bagWeight). Notice it would still be bag weight is less than weight limit, but I just switch the order of which one appears first in the boolean expression. AND Does it depend on which one becomes a subject, like one that gets focused on and evaluated? (In this case, we're trying to figure out if the bag weight is heavier than the limit or not. So the bag weight gets evaluated according to something.. I would call it a subject.)
Eclipse doesn't scream at me that it's wrong, and intuitively it makes sense, but somehow it just bothers me whether there's a more common programming practice or not. So my questions were, can I swap the two variables' places and would not matter? and does it depend on the context of which being a subject? and which is a more common programming practice?
You can freely change the order of the two variables as you prefer. Eclipse (or the compiler) doesn't care, it just evaluates the expression and returns a value, either true of false.
can I swap those two variables' places such as following? (WEIGHT_LIMIT < bagWeight)
Yes, it will still work exactly the same.
Order only comes in to play when using short circuit operates such as || or &&.
examples:
if (boolean1 || boolean2)
In this case, boolean1 will be evaluated first. If it evaluates to true, then boolean2 will not be evaluated, since the first one meets the criteria of the if statement.
if (boolean1 && boolean2)
In this case if boolean1 is evaluates to false, then boolean2 will never be evaluated because the fact that boolean1 is false means that even if boolean2 was true, the condition of the if statement would never be satisfied.
Hope that helps.
The order that Java evaluates && and || is not so important if everything is already evaluated into variables as in your example. If these where method calls instead then the second part of the "if" will not be called unless necessary. Examples of when the myMethod() would not be evaluated at all.
if (true || myMethod())
or
if (false && myMethod())
That's why you might see statements similar to this in actual code.
String myStr = null;
if (myStr != null && myStr.trim().size() > 0)
If Java were to evaluate the second part then you would get a NullPointerException when myStr is null. The fact that Java will bypass the second part keeps that from happening.
The order of the operands doesn't matter in your specific case. Since the if statement is comparing two values, the two values must be evaluated. However, there are some cases when order does matter:
|| and &&
|| and && are shorthand logic operators. The second operand of || will not be evaluated if the first is true. The second operand of && will not be evaluated if the first is false.
++ and --
These can yield different results:
if (i++ > i)
if (i < i++)
In the first line, i is evaluated after the increment is done, so the first operand is 1 less than the second.
In the second line, i is evaluated first, which evaluates to i, then i++, which evaluates to i as well.
I have a ruby background and new to java. Its a little bit confusing for me and i have a very simple exercise that i couldnt save.
My method looks like this:
public void act()
{
while((treeLeft() == false) && (treeRight() == false))
{
move();
}
}
}
So normally my code should check if there is a tree on both sides ( treeleft == true and treeright == true) and when there are really trees on both sides stop and not move.
But somehow it doesnt move although there is only a tree on the left side? What do i wrong?
The way the && operator works, is by first evaluating the left side, and if that evaluates to false it doesn't bother with evaluting the right side, since the result of the expression as a whole will be false no matter the outcome of the right side. So, once treeLeft() evaluates to true, the while is broken and moves stop.
The correct way to do this would be:
while(!(treeLeft() && treeRight()))
Which means that the while will keep looping until both treeLeft() and treeRight() evaluates to true.
Alternative version, using DeMorgan's law:
while(!treeLeft() || !treeRight())
&& operator evaluates to false anytime EITHER value is false.
|| operator evaluates to false only when BOTH values are false, and is probably what you need to use in this situation.
while(!treeLeft() || !treeRight()) { /*do stuff*/ }
For clarity (I'm not familiar with Ruby)... !treeLeft() is exactly the same as treeLeft() == false
I think you are looking for the || (or) operator. for this to click both statements need to be true. As it stands if the first statement is true you will end the loop.
If you are trying to short circuit to put a preference on the left tree then keep it first in the while loop condition. It is important to remember that these are evaluated in order. Short circuiting can be very useful. Look at the this if you want an explanation: https://www.student.cs.uwaterloo.ca/~cs132/Weekly/W02/SCBooleans.html
Also may give you some hints on how you should restructure
In your code move() will only be called if both treeLeft() and treeRight() return false. This means it won´t be called as long as you have a tree on the left OR the right side. So what you want is propably:
while(!(treeLeft() && treeRight()))
Suppose I have an IF condition :
if (A || B)
∧
|
|
left
{
// do something
}
Now suppose that A is more likely to receive a true value then B , why do I care which one is on the left ?
If I put both of them in the IF brackets , then I know (as the programmer of the code) that both parties are needed .
The thing is , that my professor wrote on his lecture notes that I should put the "more likely variable to receive a true" on the left .
Can someone please explain the benefit ? okay , I put it on the left ... what am I gaining ? run time ?
Its not just about choosing the most likely condition on the left. You can also have a safe guard on the left meaning you can only have one order. Consider
if (s == null || s.length() == 0) // if the String is null or empty.
You can't swap the order here as the first condition protects the second from throwing an NPE.
Similarly you can have
if (s != null && s.length() > 0) // if the String is not empty
The reason for choosing the most likely to be true for || or false for && is a micro-optimisation, to avoid the cost of evaluated in the second expression. Whether this translates to a measurable performance difference is debatable.
I put it on the left ... what am I gaining ? run time ?
Because || operator in C++ uses short-circuit evaluation.
i.e: B is evaulated only if A is evaluated to a false.
However, note that in C++ short-circuit evaluation is guaranteed for "built in" data types and not custom data types.
As per javadoc
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
So, if true statement comes first in the order, it short-circuits the second operand at runtime.
If the expression on the left is true, there is no need to evaluate the expression on the right, and so it can be optimized out at run time. This is a technique called short-circuiting. So by placing the expression more likely to be true on the left, we can expect our program to perform better than if it were the other way around.
You should place the condition that is more likely to be true first because that will cause the if statement to short-circuit. Meaning it will not evaluate the rest of the if statement because it will already know the answer is true. This makes code more efficient.
This is especially useful when your if statement is evaluating expensive things:
if(doExpensiveCheck1() || doExpensiveCheck2()) { }
In this case cause the checks are expensive it is in your benefit to place the most likely check first.
In many cases there is no practical difference apart from a tiny performance improvement. Where this becomes useful is if your checks are very expensive function calls (unlikely) or you need to check things in order. Say for example you want to check a property on something and to check if that something is nil first, you might do something like:
If (a != nil && a.attribute == valid)
{}
Yes exactly, you're gaining runtime, it won't seem much for one operation, but you have to keep in mind that operations will get repeated millions of times
Why perform two evaluations when one is enough is the logic
At runtime if(a||b) will test a first, if a is true it will not waste time testing b therefor the compiler will be 1 execution ahead. Therefore if a is more likely to be true than b this test is also likely to cut 1 line. The total number of lines not executed is tiny on a single line but it’s huge if the statement is nested in a loop of some sort(for,while ,recession or database related queries ). Eg per say we have 1million mins to test data in a database at 1 minute per record (30sec for condition A and 30 sec for condition B). Let A have 80% chances to be true and B have 20% chances to be true. The total time needed if you put A first is 600-000hrs yet it’s 900-000hrs if you put B first.if A is tested first[(0,8*1millions hours)*0,5mins+(0,2*1million hours)*1min]===6000-000hrs : if B is tested first [(0,2*1million hours)*0,5mins+(0,2*1million hours)*1min]===9000-000hrs. However you will notice the difference is less significant if the probability of A becoming true is closer to that of B.
public class Main
{
public static void main(String[] args) {
System.out.println("Hello World");
Integer a = null;
Integer b = 3;
Integer c = 5;
if(a != null && a == 2){
System.out.println("both");
}else{
System.out.println("false");
}
}
}
Hello World
false
That is, if I have a statement that evaluates multiple conditions, in say a 'or' statement like so..
if(isVeryLikely() || isSomewhatLikely() || isHardlyLikely())
{
...
}
In the case that isVeryLikely() returns true at runtime, will isSomewhatLikely() and isHardlyLikely() execute? How about if instead of methods they were static booleans?
The || and && operators are short-circuiting.
true || willNeverExecute();
false && willNeverExecute();
The first thing that you need to note is that Java conditional statements can only take boolean, unlike other languages like C/C++ where any non-zero value will evaluate to true.
That being said, there are 2 types of operators, the first is known as the shor-circuit types:
&& and ||
while the other are the NON-short-circuit types:
& and |
For the Short-Circuit types, once a logical output can be found as an answer to the expression, the rest of the statement will be dumped. For the NON-Short-Circuit types, they will continue to evaluate all conditions.
With this in mind, what you have:
if(isVeryLikely() || isSomewhatLikely() || isHardlyLikely())
{
...
}
Java will:
First check if isVeryLikely()
returns true. If true, then it will
not continue further.
If isVeryLikely() returns false,
then invoke isSomewhatLikely() to
see if it returns true. If true,
nothing else if evaluated. If false,
goto 3.
isHardlyLikely() is invoked. If
true, entire expression is true,
otherwise false, entire
expression is false.
The entire concept you're asking about is "How does Java evaluate Logical Expressions." Good question :)
Hope it helps! Cheers!
No, java uses short-circuit evaluation on expressions using || and &&. See here for more info.
Because the || is short circuiting, the statement will be evaluated to true as soon as it hits the first true condition, regardless of whether or not the operands are static.
In short, no the two other functions will not be evaluated if the first returns true.
The short answer is, it will evaluate until has enough to conclude whether it is T/F.
There is something called boolean short-circuiting. Essentially it will try and evaluate only what it needs to (if you use the && or || operators) and the leave. You can take advantage of this in a few ways:
(a() || b())
If b() would throw an exception, if a() is true, then it would not even try and check the b(). A type of chain-checking mechanism.
If the latter evaluations are resource consuming, you can move them to the end of the evaluation (eg. b() takes 10 times longer)
If the most likely path can be determined by a certain clause, put them first. This would also speed up execution.
As an update for Kotlin users, you can use 'or' operator in Kotlin std library in order to check all the expressions in the if statement and not performing a short-circuit.
In the expression presented in the initial question the code in Kotlin should be:
if(isVeryLikely() or isSomewhatLikely() or isHardlyLikely()) {
...
}
Whether for boolean expression specified in the questions are static booleans, or they are methods returning a boolean value, in both the cases - expression evaluation will start from the left and conditions will be evaluated one-by-one. The first condition which gives a value true will short-circuit the evaluation. It will directly give the result as true with the remaining conditions not being evaluated. This is how ||(OR) works in Java using the concept of short-circuit evaluation.
If you want to understand more about short-circuits in general you can refer an article I have written on my blog - http://www.javabrahman.com/programming-principles/short-circuiting-or-short-circuits-in-boolean-evaluations-in-programming-and-java/
I have been working with Java a couple of years, but up until recently I haven't run across this construct:
int count = isHere ? getHereCount(index) : getAwayCount(index);
This is probably a very simple question, but can someone explain it? How do I read it? I am pretty sure I know how it works.
if isHere is true, getHereCount() is called,
if isHere is false getAwayCount() is called.
Correct? What is this construct called?
Yes, it is a shorthand form of
int count;
if (isHere)
count = getHereCount(index);
else
count = getAwayCount(index);
It's called the conditional operator. Many people (erroneously) call it the ternary operator, because it's the only ternary (three-argument) operator in Java, C, C++, and probably many other languages. But theoretically there could be another ternary operator, whereas there can only be one conditional operator.
The official name is given in the Java Language Specification:
§15.25 Conditional Operator ? :
The conditional operator ? : uses the boolean value of one expression to decide which of two other expressions should be evaluated.
Note that both branches must lead to methods with return values:
It is a compile-time error for either the second or the third operand expression to be an invocation of a void method.
In fact, by the grammar of expression statements (§14.8), it is not permitted for a conditional expression to appear in any context where an invocation of a void method could appear.
So, if doSomething() and doSomethingElse() are void methods, you cannot compress this:
if (someBool)
doSomething();
else
doSomethingElse();
into this:
someBool ? doSomething() : doSomethingElse();
Simple words:
booleanCondition ? executeThisPartIfBooleanConditionIsTrue : executeThisPartIfBooleanConditionIsFalse
Others have answered this to reasonable extent, but often with the name "ternary operator".
Being the pedant that I am, I'd like to make it clear that the name of the operator is the conditional operator or "conditional operator ?:". It's a ternary operator (in that it has three operands) and it happens to be the only ternary operator in Java at the moment.
However, the spec is pretty clear that its name is the conditional operator or "conditional operator ?:" to be absolutely unambiguous. I think it's clearer to call it by that name, as it indicates the behaviour of the operator to some extent (evaluating a condition) rather than just how many operands it has.
According to the Sun Java Specification, it's called the Conditional Operator. See section 15.25. You're right as to what it does.
The conditional operator ? : uses the boolean value of one expression to decide which of two other expressions should be evaluated.
The conditional operator is syntactically right-associative (it groups right-to-left), so that a?b:c?d:e?f:g means the same as a?b:(c?d:(e?f:g)).
ConditionalExpression:
ConditionalOrExpression
ConditionalOrExpression ? Expression : ConditionalExpression
The conditional operator has three operand expressions; ? appears between the first and second expressions, and : appears between the second and third expressions.
The first expression must be of type boolean or Boolean, or a compile-time error occurs.
condition ? truth : false;
If the condition is true then evaluate the first expression. If the condition is false, evaluate the second expression.
It is called the Conditional Operator and it is a type of Ternary Operation.
int count = isHere ? getHereCount(index) : getAwayCount(index);
means :
if (isHere) {
count = getHereCount(index);
} else {
count = getAwayCount(index);
}
Not exactly correct, to be precise:
if isHere is true, the result of getHereCount() is returned
otheriwse the result of getAwayCount() is returned
That "returned" is very important. It means the methods must return a value and that value must be assigned somewhere.
Also, it's not exactly syntactically equivalent to the if-else version. For example:
String str1,str2,str3,str4;
boolean check;
//...
return str1 + (check ? str2 : str3) + str4;
If coded with if-else will always result in more bytecode.
Ternary, conditional; tomato, tomatoh. What it's really valuable for is variable initialization. If (like me) you're fond of initializing variables where they are defined, the conditional ternary operator (for it is both) permits you to do that in cases where there is conditionality about its value. Particularly notable in final fields, but useful elsewhere, too.
e.g.:
public class Foo {
final double value;
public Foo(boolean positive, double value) {
this.value = positive ? value : -value;
}
}
Without that operator - by whatever name - you would have to make the field non-final or write a function simply to initialize it. Actually, that's not right - it can still be initialized using if/else, at least in Java. But I find this cleaner.
You might be interested in a proposal for some new operators that are similar to the conditional operator. The null-safe operators will enable code like this:
String s = mayBeNull?.toString() ?: "null";
It would be especially convenient where auto-unboxing takes place.
Integer ival = ...; // may be null
int i = ival ?: -1; // no NPE from unboxing
It has been selected for further consideration under JDK 7's "Project Coin."
This construct is called Ternary Operator in Computer Science and Programing techniques. And Wikipedia suggest the following explanation:
In computer science, a ternary operator (sometimes incorrectly called a tertiary operator) is an operator that takes three arguments. The arguments and result can be of different types. Many programming languages that use C-like syntax feature a ternary operator, ?: , which defines a conditional expression.
Not only in Java, this syntax is available within PHP, Objective-C too.
In the following link it gives the following explanation, which is quiet good to understand it:
A ternary operator is some operation operating on 3 inputs. It's a shortcut for an if-else statement, and is also known as a conditional operator.
In Perl/PHP it works as: boolean_condition ? true_value : false_value
In C/C++ it works as: logical expression ? action for true : action for false
This might be readable for some logical conditions which are not too complex otherwise it is better to use If-Else block with intended combination of conditional logic.
We can simplify the If-Else blocks with this Ternary operator for one code statement line.For Example:
if ( car.isStarted() ) {
car.goForward();
} else {
car.startTheEngine();
}
Might be equal to the following:
( car.isStarted() ) ? car.goForward() : car.startTheEngine();
So if we refer to your statement:
int count = isHere ? getHereCount(index) : getAwayCount(index);
It is actually the 100% equivalent of the following If-Else block:
int count;
if (isHere) {
count = getHereCount(index);
} else {
count = getAwayCount(index);
}
That's it!
Hope this was helpful to somebody!
Cheers!
Correct. It's called the ternary operator. Some also call it the conditional operator.
Its Ternary Operator(?:)
The ternary operator is an operator that takes three arguments. The first
argument is a comparison argument, the second is the result upon a true
comparison, and the third is the result upon a false comparison.
Actually it can take more than 3 arguments. For instance if we want to check wether a number is positive, negative or zero we can do this:
String m= num > 0 ? "is a POSITIVE NUMBER.": num < 0 ?"is a NEGATIVE NUMBER." :"IT's ZERO.";
which is better than using if, else if, else.
?: is a Ternary Java Operator.
Its syntax is:
condition ? expression1 : expression2;
Here, the condition is evaluated and
condition returns true, the expression1 will execute.
condition returns false, the expression2 will execute.
public class Sonycode {
public static void main(String[] args) {
double marks = 90;
String result = (marks > 40) ? "passed in exam" : "failed in exam";
System.out.println("Your result is : " + result);
}
}
Output :-
Your result is : passed in exam
It's the conditional operator, and it's more than just a concise way of writing if statements.
Since it is an expression that returns a value it can be used as part of other expressions.
Yes, you are correct. ?: is typically called the "ternary conditional operator", often referred to as simply "ternary operator". It is a shorthand version of the standard if/else conditional.
Ternary Conditional Operator
I happen to really like this operator, but the reader should be taken into consideration.
You always have to balance code compactness with the time spent reading it, and in that it has some pretty severe flaws.
First of all, there is the Original Asker's case. He just spent an hour posting about it and reading the responses. How longer would it have taken the author to write every ?: as an if/then throughout the course of his entire life. Not an hour to be sure.
Secondly, in C-like languages, you get in the habit of simply knowing that conditionals are the first thing in the line. I noticed this when I was using Ruby and came across lines like:
callMethodWhatever(Long + Expression + with + syntax) if conditional
If I was a long time Ruby user I probably wouldn't have had a problem with this line, but coming from C, when you see "callMethodWhatever" as the first thing in the line, you expect it to be executed. The ?: is less cryptic, but still unusual enough as to throw a reader off.
The advantage, however, is a really cool feeling in your tummy when you can write a 3-line if statement in the space of 1 of the lines. Can't deny that :) But honestly, not necessarily more readable by 90% of the people out there simply because of its' rarity.
When it is truly an assignment based on a Boolean and values I don't have a problem with it, but it can easily be abused.
Conditional expressions are in a completely different style, with no explicit if in the statement.
The syntax is:
boolean-expression ? expression1 : expression2;
The result of this conditional expression is
expression1 if boolean-expression is true;
otherwise the result is expression2.
Suppose you want to assign the larger number of variable num1 and num2 to max. You can simply write a statement using the conditional expression:
max = (num1 > num2) ? num1 : num2;
Note: The symbols ? and : appear together in a conditional expression. They form a conditional operator and also called a ternary operator because it uses three operands. It is the only ternary operator in Java.
cited from: Intro to Java Programming 10th edition by Y. Daniel Liang page 126 - 127