Why is the operator precedence not followed here? [duplicate] - java

This question already has answers here:
What are the rules for evaluation order in Java?
(5 answers)
If parenthesis has a higher precedence then why is increment operator solved first?
(5 answers)
Closed 7 years ago.
In this code:
int y = 10;
int z = (++y * (y++ + 5));
What I expected
First y++ + 5 will be executed because of the precedence of the innermost parentheses. So value of y will be 11 and the value of this expression will be 15. Then ++y * () will be executed. So 12 * 15 = 180. So z=180
What I got
z=176
This means that the VM is going from left to right not following operator precedence. So is my understanding of operator precedence wrong?

The expression (++y * (y++ + 5)); will be placed in a stack something like this:
1. [++y]
2. [operation: *]
3. [y++ + 5] // grouped because of the parenthesis
And it will be executed in that order, as result
1. 10+1 = [11] // y incremented
2. [operation: *]
3. 11+5 = [16] // y will only increment after this operation
The the expression is evaluated as
11 * 16 = 176

First y++ + 5 will be executed because of the precedence of the innermost parentheses
Precedence and evaluation order are not the same thing. All binary expressions except the assignment expression are evaluated left-to-right. Therefore y++ is evaluated before the parenthesized expression on the right.

The parentheses just describe how the sub-expressions will be grouped together. Parenthesizing doesn't mean it will be evaluated first. Rather, the rule in java is evaluate each sub-expression strictly from left to right.
Always remember that the order of evaluation has absolutely nothing to do with operator precedence and associativity.
Java Oracle documentation says that:
15.7. Evaluation Order
The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.
Therefore, the expression (++y * (y++ + 5)) will be evaluated as
temp1 = ++y = 11
temp2 = y++ + 5 = 11 + 5 = 16
z = temp1*temp2 = 11*16 = 176
Further reading: Eric Lippert's blog, Precedence vs Associativity vs Order, explained in detailed about precedence, associativity and order of evaluation. Though this blog addresses c# but equally valid for java too.

First will be executed ++y. y will be 11.
Then will be executed y + 5 (actually y++ + 5 can be written as 5 + y++ which is interpreted as (5 + y) and then y++). z will become 11 * 16 = 176.
y will be 12 after the calculation finishes.

The calculation is going on following order
z= (++10 * (10++ + 5))
z= (11 * (11 + 5))//++ (prefix or postfix) has higher precedence than + or *
z= (11 * 16)
z= 176

Related

Postfix and Prefix operators in Java behave differently [duplicate]

This question already has answers here:
What are the rules for evaluation order in Java?
(5 answers)
Closed 5 years ago.
Based on the Oracle: Operator Doc Oracle
The preference of postfix incr and decr operator is higher than prefix operators.
But when I try this example:
int x = 1;
System.out.println(++x * x++); // prints 4
x=1;
System.out.println(x++ * ++x); // prints 3
If we go as the operators precedence, the output should be : 3 and 3 instead of 4 and 3.
Any help is appreciated.
This is only post/pre increment element :
(++x * x++);
++x = 1 becomes 2 and use 2 for value
x++ = use 2 for value, and then 2 becomes 3
2*2 = 4
(x++ * ++x);
x++ = use 1 for value, and then 1 becomes 2
++x = 2 becomes 3 and use 3 for value
1*3 = 3
pre-increment : increment the value and use the new one for compute
post-increment : remember the old value, used for this calculation, and then increment

Value of y = x + x++ in Java [duplicate]

This question already has answers here:
Is there a difference between x++ and ++x in java?
(18 answers)
Java: pre-,postfix operator precedences
(5 answers)
Closed 6 years ago.
Say we have Java code below:
int x = 1;
int y = x + x++;
'Cause the precedence of "postfix-increment" operator is higher than "add" operator. I think x++ should be calculate and evaluated first. Then it comes to x + (x++). So the y should be "new_x(2) + 1 = 3".
Though it turns out "2" instead of "3". Any ideas? Thanks.
This question is greatly different from Is there a difference between x++ and ++x in java?. That question mentions nothing about the operator precedence.
Someone has explained that expression is read from left to right. Does it conflict with the precedence of those operators?
Just as I mentioned before, I think x++ should be calculated first. It seems that I mess up with the "evaluation" and "calculation".
The difference between x++ and ++x is quite evident and known. ++ can be used as preadd (Add 1 and then use x ) or postadd (use x and add 1).
Check this out.
As tested and seen
1. x + x++ will give 2
2. x + ++x will give 3
3. x++ + x will give 3
4. ++x + x will give 4
Now the interesting case here is 2nd and 4th which basically explains pre-add operator.
In these cases, the value of x is incremented first and then used in both the places.
However in case of test 2 the first operand i.e. x is already used up for addition so the answer is 3
while in the test 4 the operand x is first incremented and used in both the operands. This happens because the expressions are evaluated from left to right.
x++ would first return x then increment x.
++x would increment x first then return x.
Therefore :
int y = x + x++; //y (2) = x(1) + x(1, then becomes 2 right after)
int y = x + ++x; //y (3) = x(1) + x(becomes 2 before being returned)

Java post-increment and pre increment behaviour

I have a simple Java expression depicted below. Based on Operator Precedence table, I expect that this expression would return division by zero exception (since post-fix increment operator has highest priority) and expect that resulting expression would look like:
2 + 2 + 5 / 0
But result is 7, why ? (By little bit of experimentation I found that all operators are assigned value of 1 for some reason, but this does not make sense to me in case priority table is correct)
int intCountOperator = 0;
unaryOperand = ++intCountOperator + intCountOperator + 5 / intCountOperator++;
System.out.println(unaryOperand); // Prints 7
The operator precedence does not control the evaluation order. It controls only how the expression is to be read. For example, since multiplication has a higher precedence than addition, x + y * z is read as x + (y * z), not (x + y) * z. However, it does not change that first x is evaluated, then y and finally z.
Giving a good example with ++ and -- is more difficult, because there is usually only one reading which makes sense. However, you might notice that y - x++ compiles without error (if x and y are numerical variables). If ++ would have had a lower precedence than - it would be evaluated as (x - y)++ which would not compile.
Because of operator precedence, your expression is evaluated as:
(++intCountOperator) + (intCountOperator + (5 / (intCountOperator++)));
but the evaluation order is not changed by it.
The expression is evaluated from left to right :
unaryOperand = ++intCountOperator + intCountOperator + 5 / intCountOperator++;
1 + 1 + 5 / 1 = 7
Note that the operators are evaluated in the order you expect, i.e. 1 + 1 + (5/1) = 1 + 1 + 5 = 7, but the operands of all those expressions are evaluated from left to right.
The order of evaluation is from left to right and not right to left. So the result 7 which you are getting is correct.
unaryOperand = ++intCountOperator + intCountOperator + 5 / intCountOperator++;
is actually
unaryOperand = 1 + 1 + 5 / 1; = 7

Use of postfix/prefix expressions

I understand in prefix/postfix, there is no need to bother about precedence of operators.
But where do we use prefix/postfix expressions?
Are they internally converted by the compiler?
Is there a way I could write expression in prefix/postfix and the compiler evaluates it for me?
EDIT: Ff you're actually talking about postfix (RPN) notation, then no, the compiler uses infix notation for expressions. You could write an algorithm that converts an RPN expression into an infix expression, try this
Postfix and prefix operators are just like a binary operator, but they work on only one operand.
Postfix increment (the increment occurs after the variable is evaluated):
int x = 1;
int y = x++; // y = 1 but after the assignment occurs x = 2
int z = x; // z = 2
Prefix increment:
int x = 1;
int y = ++x; // y = 2 and before the assignment occurs x = 2
int z = x; // z = 2
The rules that apply to the increment operator also apply to the decrement operator.
Prefix NOT (inverts a boolean expression):
boolean a = true;
boolean b = !a; // b = false, a = true
I think I have understood the question correctly, but I'm not sure what you mean about the compiler "evaluating" them "for you".
I suspect that prefix and postfix operations and notations are mostly useful for theories these days, but they have been used "for real". See e.g. https://en.wikipedia.org/wiki/Stack_machine, https://en.wikipedia.org/wiki/Forth_%28programming_language%29, http://linux.about.com/library/cmd/blcmdl1_dc.htm, and https://en.wikipedia.org/wiki/Reverse_Polish_notation#Hewlett-Packard
Few languages use postfix notation (the only one I know of would be PostScript), but the resulting CPU instructions would be the same as for infix notation:
a = (3 + 4) * 5
or
a = * + 3 4 5
Would be converted (in an imaginary, very simple, instruction sets):
add r0 3 4 # r0 = 3 + 4
mul r1 r0 5 # r1 = r0 * 5
Your CPU does not care about the initial notation, all it accepts is a set of « basic » instructions, so the compiler has to convert the notation you use to instructions understandable by your CPU.

operation on post++ and --pre operator

I am wondering with post and pre increment and decrement operation.
what I know in Java precedence of post operator is high and associativity is left-to-right.while associativity of pre operator is right-to-left
Oracle Java Tutorial
but my code showing me undesired result-
public class Bunnies {
static int count = 3;
public static void main(String[] args) {
System.out.println(--count*count++*count++);//out put is 12 expected 48
//associativity of post is higher so should be evaluated like this-
//--count*3**count++ count is 4 now
//--count*3*4 count is 5 now
//4*3*4=48
count = 3;
System.out.println(--count*++count*++count); //out put is 24 expected 120
//associativity of pre is right to left so should be evaluated like this-
//--count*++count*4 count is 4 now
//--count*5*4 count is 5 now
//4*5*4=120
count = 3;
System.out.println(-- count*count++);// out put is 4 expected 9
//--count*3 count is 4 now
//3*3=9
}
}
Order of evaluation of subexpressions is independent of both associativity and precedence.
The subexpression of the multiplication are evaluated from left to right, so when doing --count*count++*count++, you evaluate --count then count++ and finally count++.
And as the pre operator is evaluated first, --count will be decremented before its evaluation. In the same way, as the post operator is evaluated lately, count++ will be incremented after its evaluation.
The precedence only help the compiler to create a correct abstract syntactic tree.
For example, when doing ++count*2, the compiler use the precedence to know the expression is (++count)*2 and not ++(count*2). In the same way, when doing ++count*count--, the expression is (++count)*(count--) and not (++(count * count))-- or whatever. But then, during the evaluation of the multiplication ++count is evaluated before count--.
Hope this help you :)
I just found a great answer about expression evaluation in C# and Java here, enjoy :)
System.out.println(--count*count++*count++);
= 2 * 2 * 3 = 12
count = 3;
System.out.println(--count*++count*++count)
= 2*3*4 = 24
count = 3;
System.out.println(-- count*count++);
= 2 * 2 = 4
Pre increment/decrement
++/-- X first increments/decrements then does the operation.
Post increment/decrement
X ++/-- first the operation is done, then increment / decrement.
I take the first one.
System.out.println(--count*count++*count++);//out put is 12 expected 48
2 * 2 * 3 = 12
pre * post * post
count = 3:
Example 1:
--count*count++*count++ equals (--count)*(count++)*(count++)
(--count) = 2
(count++) = 2 (you increment it AFTER you do something with it)
(count++) = 3 ... count was incremented from before
2*2*3 = 12
Example 2:
--count*++count*++count equals (--count)*(++count)*(++count)
--count = 2
++count = 3
2 * 3 * 3 = 24
Example 3:
(--count)*(count++)
--count = 2
2 * 2 (the count++ gets changed afterwards)
Keep in mind that you have to watch the multiplicaton operator

Categories