What does "Higher Precedence" mean? - java

According to wiki the precedence level of AND is higher than OR.
I was wondering, if i have a clause stated as a || b && c
How it should be computed first? (a||b) or (b && c)?

Due to precedence, it evaluates as
(a || ( b && c))
And if you add parentheses (manually), parentheses are evaluated before anything else and changes everything.
if you write
((a || b) && c)
That matters!

AND has a higher precedence over OR in JAVA. So (b && c) should be computed before (a||b) in expression a || b && c
Check this for complete list:
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
Snapshot taken from the link:

You should just try it out in a test script, but if the wiki says AND has higher precedence then I would assume b&&c is called first.

Because AND has a higher order precendence, (b && c) would be evaluated first, then the result of that would be ORed with a. In other words this is equivalent to a || (b && c)

This has very straight forward answer, it evaluate b&&c first simply because AND operation has higher precedence in the order than OR operation.
Let me explain with a more known example about precedence,
Let's take 5+2*2
We all know 2*2 is the first to evaluate and then the 5 will be added to the 4(2*2). Likewise there is order of evaluation in logic's too and that's a standard you have to follow. :)

Related

The precedence of java boolean

&& is supposed to have higher precedence than ||:
int a = 10;
System.out.println(a==10 || --a==9 && a==8);
System.out.println(a);
this prints true, and 10. It seems that it checks only the first part and if its true the second never executes.
If I do a==9 then the second part seems to evaluate and prints 9. Can someone explain why this is happening? Isn't && supposed to evaluate first?
Edit: I see it. a==10 || --a==9 && a==8 transforms into (a==10) || (a==9 && a==8) So if the first one evaluates to true it short circuits. Thank you for your help guys.
System.out.println(a==10 || --a==9 && a==8);
equal to
System.out.println((a==10) || (((--a)==9) && (a==8)));
Java evaluates || first. Find out that left part (a==10) is true and derive that no mater what is in right part result anyway will be true
PS: it is common trick to write
if(obj != null && obj.isSomething) { ... }
to prevent NPE
It's useful to look at expressions as trees.
a==10 || --a==9 && a==8
In this example, the top of the tree is an OR. The left branch is an EQUALS, and the right branch is an AND whose left and right branch are both EQUALS.
Since I'm awful at graphics, it would look something like:
OR
/ \-----
= \
/ \ AND
a 10 / \
= =
/ \ / \
--a 9 a 8
The "precedence" that you're talking about, orders this tree. But it doesn't necessarily change execution order. Because in this case, this is true if the first branch is true, so no need to check the second branch.
If you evaluate (a==10) || (b == 9) (which is an OR operation),
if the first clause is true, then the entire expression must be true (because it's OR) and the second clause will not be executed for reasons of optimization.
Code is executed from left to right, so you'll hit the first TRUE therefore your entire statement will be TRUE, and the remainder of your statement will not be executed
If your first clause is false, then only will the second clause be evaluated.
If you use (a==10) | (b == 9) both clauses will be evaluated.
If you want to be certain of the precedence of your operators, you should use brackets
It doesn't have anything to do with higher precedence in this case. Look up lazy evaluation. The operation will be evaluated from left to right and will find that a==10 is true and stop there.
Look at the comments in http://introcs.cs.princeton.edu/java/11precedence/ under order of evaluation
|| and && are short circuit operators they don't evaluate the right hand side expression
if the left hand side is true.
So (--a) is never executed as (a==10) left hand side is true
Therefore the value of a remains same.
**& and | operators that always evaluate both sides.

java short circuit operators

My doubt is about the precedence of short circuit operators.
Classic example of short circuit operator is below.
if(denom != 0 && num/denom > 10 )
Here usage of shorthand operator allows us to prevent division by zero error because num/denom is never executed.
Now My question is Java says '/' operator has higher precedence than '&&' , then how come left side of '&&' is evaluated before '/'.?
/ has higher precedence than >, which has a higher precedence than &&. So, the expression
a && b / c > 0
is the same as
a && (b / c) > 0
which is the same as
a && ((b / c) > 0)
The expression is then evaluated from left to right.
If a is false, then the entire expression is false, without even evaluating the second term.
If a is true, then b / c is first evaluated, and the result is compared to 0.

Why does the "or" go before the "and"?

int it=9, at=9;
if(it>4 || ++at>10 && it>0)
{
System.out.print("stuff");
}
System.out.print(at);
prints out stuff9 and I want to know why as I thought ++at>10 && it>0 would be evaluated first and thus make at = 10.
Operator precedence only controls argument grouping; it has no effect on execution order. In almost all cases, the rules of Java say that statements are executed from left to right. The precedence of || and && causes the if control expression to be evaluated as
it>4 || (++at>10 && it>0)
but the higher precedence of && does not mean that the && gets evaluated first. Instead,
it>4
is evaluated, and since it's true, the short-circuit behavior of || means the right-hand side isn't evaluated at all.
Your compound expression is equivalent to
if(it>4 || (++at>10 && it>0))
due to Java operator precedence rules. The operands of || are evaluated left to right, so it>4 is evaluated first, which is true, so the rest of it (the entire && subexpression) doesn't need to be evaluated at all (and so at does not change).
I feel I should add how to actually get your expected output.
Brief explanation: the || operator short-circuits the entire expression, thus the right side not even being evaluated.
But, to not short-circuit and get your expected output, instead of the || operator, just use |, like so:
int a = 9, b = 9;
if(a>4 | ++b>10 && a>0)
{
System.out.print("stuff");
}
System.out.print(b);
The output to that is stuff10
This way, regardless of one side being true or not, they're both still evaluated.
The same thing goes for && and &

Why Logical operators, when there is Bitwise operators in java

I know that the Bitwise operators &, | and ^ are EITHER bitwise operators OR logical operators ... depending on the types of the operands.
If the operands are integers, the operators are bitwise. If they are
booleans, then the operators are logical.
Then why there are Logical operators &&,|| and! ? I believe there will be some situations where we can use only logical operator, and so they are.
So, can anyone explain such a situation? Or any advantage over bitwise ops.
Operators && and || evaluates lazily. This means that only one side might be evaluated.
Operators & and | evaluates eagerly, this means that always both sides are evaluated.
It is very important when you expressions have side effects.
Examples
x = 0;
(x++ == 0) || (x++ == 1); // x is 1
x = 0;
(x++ == 0) | (x++ == 1); // x is 2
Logical operators &&,|| etc let you short circuit the logic.
1==1 || complexMethod(/*param*/)
complexMethod() will not execute.
1==1 | complexMethod(/*param*/)
complexMethod() will execute.
Short circuiting basically means the condition will be evaluated only up to where it is necessary and not beyond that.
Uses in Short-circuit evaluation like
Ex:
see &&
if(Condition1 && condition2){
}
and ||
if(Condition1 || condition2){
}
in these cases
in which the second argument is only executed or evaluated if the first argument does not suffice to determine the value of the expression:

What is the difference between & and && in if statement in java? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Difference in & and &&
if (true && true) {
System.out.println("test if");
}
if (true & true) {
System.out.println("test if");
}
both are give same output.why ?
&& short-circuits, wheras & doesn't. Example:
if (methodA() && methodB()) {
...
}
In that case, if methodA already returns false, methodB is not called. Formally, if you have an expression a && b, b is only evaluated if a evaluated to true.
Apart from the obvious performance benefit, this is particularly useful for null checks:
if (x != null && x.getSomeValue()) {
...
}
If you used a s single & here, x.getSomeValue() would be evaluated even if x were null, resulting in an exception.
& is a bit operation
&& logically links two booleans
Please see:
http://www.jguru.com/faq/view.jsp?EID=16530
It depends on the type of the arguments...
For integer arguments, the single ampersand ("&")is the "bit-wise AND"
operator. The double ampersand ("&&") is not defined for anything but
two boolean arguments.
For boolean arguments, the single ampersand constitutes the
(unconditional) "logical AND" operator while the double ampersand
("&&") is the "conditional logical AND" operator. That is to say that
the single ampersand always evaluates both arguments whereas the
double ampersand will only evaluate the second argument if the first
argument is true.
For all other argument types and combinations, a compile-time error
should occur.
In the first case, you don't test the second part of the if : the && operator executes from left to right and stops at the first false value.
This may be useful in this case :
if (a!=null && a.doSomething()==23) {
because it prevents a nullPointerException.
When you test boolean conditions, always use &&.
In & statetment it will check both left side and right side statements.in && will check only one side of statement(if one side is true it will not check other side)
&& is the logical AND
so you want to make sure BOTH statements become true.
& is the bitwise AND operator
Have a look here:
http://www.javaforstudents.co.uk/TrueFalse
&& is logical and.
true && true is true and everything else is false.
& is bitwise and.
(10 & 8) = 8

Categories

Resources