operation on post++ and --pre operator - java

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

Related

How can I wrap an Ascii value back to "A" if it's gone past "Z", without using If statements?

I can't figure out a proper solution without using an If Statement. My assignment explicitly says I cannot use an If Statement, so I am currently at a standstill.
I'm not going to answer your question exactly, but point you to the concept...
Most languages offer a modulus operator. (%) This is the equivalent of doing a division, but instead of returning the quotient, it returns you the remainder.
int n = 26%12; // 26 divided by 12 = 2 remainder 4. n = 4
One use for the modulus operator is to efficiently do a wrap around. For example, if you wanted to print out the numbers 1 to 7 repeatedly...
int n = 0;
for(int i = 0; i < 10; ++i) {
Console.log(n+1);
n = (n+1)%7;
}
This would output
1
2
3
4
5
6
7
1
2
3

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.

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

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

a = (a++) * (a++) gives strange results in Java [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
I'm studying for the OCPJP exam, and so I have to understand every little strange detail of Java. This includes the order in which the pre- and post-increment operators apply to variables. The following code is giving me strange results:
int a = 3;
a = (a++) * (a++);
System.out.println(a); // 12
Shouldn't the answer be 11? Or maybe 13? But not 12!
FOLLOW UP:
What is the result of the following code?
int a = 3;
a += (a++) * (a++);
System.out.println(a);
After the first a++ a becomes 4. So you have 3 * 4 = 12.
(a becomes 5 after the 2nd a++, but that is discarded, because the assignment a = overrides it)
Your statement:
a += (a++) * (a++);
is equivalent to any of those:
a = a*a + 2*a
a = a*(a+2)
a += a*(a+1)
Use any of those instead.
a++ means 'the value of a, and a is then incremented by 1'. So when you run
(a++) * (a++)
the first a++ is evaluated first, and produces the value 3. a is then incremented by 1. The second a++ is then evaluated. a produces the value of 4, and is then incremented again (but this doesn't matter now)
So this turns into
a = 3 * 4
which equals 12.
int a = 3;
a += (a++) * (a++);
First build the syntax tree:
+=
a
*
a++
a++
To evaluate it start with the outer most element and descent recursively. For each element do:
Evaluate children from left to right
Evaluate the element itself
The += operator is special: It gets expanded to something like left = left + right, but only evaluating the expression left once. Still the left side gets evaluated to a value(and not just a variable) before the right side gets evaluated to a value.
This leads to:
Start evaluating +=
Evaluate left side of assignment to the variable a.
Evaluate the variable a to the value 3 which will be used in the addition.
Start evaluating *
Evaluate the first a++. This returns the current value of a 3 and sets a to 4
Evaluate the second a++. This returns the current value of a 4 and sets a to 5
Calculate the product: 3*4 = 12
Execute +=. The left side had been evaluated to 3 in the third step and the right side is 12. So it assigns 3+12=15 to a.
Final value of a is 15.
One thing to note here is that operator precedence has no direct influence on evaluation order. It only affects the form of the tree, and thus indirectly the order. But among siblings in the tree the evaluation is always left-to right, regardless of operator precedence.
(a++) is a post increment, so value of expression is 3.
(a++) is post increment, so value of expression is now 4.
Expression evaluation is happening from left to right.
3 * 4 = 12
Each time the you use a++, you're post-incrementing a. That means the first a++ evaluates to 3 and the second evaluates to 4. 3 * 4 = 12.
There is a general lack of understanding about how operators work. Honestly, every operator is syntactic sugar.
All you have to do is understand what is actually happening behind every operator. Assume the following:
a = b -> Operators.set(a, b) //don't forget this returns b
a + b -> Operators.add(a, b)
a - b -> Operators.subtract(a, b)
a * b -> Operators.multiply(a, b)
a / b -> Operators.divide(a, b)
Compound operators can then be rewritten using these generalizations (please ignore the return types for the sake of simplicity):
Operators.addTo(a, b) { //a += b
return Operators.set(a, Operators.add(a, b));
}
Operators.preIncrement(a) { //++a
return Operators.addTo(a, 1);
}
Operators.postIncrement(a) { //a++
Operators.set(b, a);
Operators.addTo(a, 1);
return b;
}
You can rewrite your example:
int a = 3;
a = (a++) * (a++);
as
Operators.set(a, 3)
Operators.set(a, Operators.multiply(Operators.postIncrement(a), Operators.postIncrement(a)));
Which can be split out using multiple variables:
Operators.set(a, 3)
Operators.set(b, Operators.postIncrement(a))
Operators.set(c, Operators.postIncrement(a))
Operators.set(a, Operators.multiply(b, c))
It's certainly more verbose that way, but it immediately becomes apparent that you never want to perform more than two operations on a single line.
In case of :
int a = 3;
a = (a++) * (a++);
a = 3 * a++; now a is 4 because of post increment
a = 3 * 4; now a is 5 because of second post increment
a = 12; value of 5 is overwritten with 3*4 i.e. 12
hence we get output as 12.
In case of :
a += (a++) * (a++);
a = a + (a++) * (a++);
a = 3 + (a++) * (a++); // a is 3
a = 3 + 3 * (a++); //a is 4
a = 3 + 3 * 4; //a is 5
a = 15
Main point to note here is that in this case compiler is solving from left to right and
in case of post increment, value before increment is used in calculation and as we move from left to right incremented value is used.
(a++) means return a and increment, so
(a++) * (a++) means 3 * 4
Here is the java code:
int a = 3;
a = (a++)*(a++);
Here is the bytecode:
0 iconst_3
1 istore_1 [a]
2 iload_1 [a]
3 iinc 1 1 [a]
6 iload_1 [a]
7 iinc 1 1 [a]
10 imul
11 istore_1 [a]
Here is what happens:
Pushes 3 into the stack then pops 3 from the stack and stores it at a.
Now a = 3 and the stack is empty.
0 iconst_3
1 istore_1 a
Now it pushes the value from "a" (3) into the stack, and then increments a(3 -> 4).
2 iload_1 [a]
3 iinc 1 1 [a]
So now "a" equals "4" the stack equals {3}.
Then it loads "a" again (4), pushes into the stack and increments "a".
6 iload_1 [a]
7 iinc 1 1 [a]
Now "a" equals 5 and the stack equals {4,3}
So it finally pops the fisrt two values from the stack (4 and 3), multiplies and stores it back into the stack (12).
10 imul
Now "a" equals 5 and the stack equals 12.
Finally is pops 12 from the stack and stores at a.
11 istore_1 [a]
TADA!
It is 12.
The expression starts evaluating from left. So it does:
a = (3++) * (4++);
Once the first part (3++) is evaluated, a is 4, so in the next part, it does a = 3*4 = 12.
Note that the last post-increment (4++) is executed but has no effect since a is assigned with the value 12 after this.
Example 1
int a = 3;
a = (++a) * (a++);
System.out.println(a); // 16
Example 2
int a = 3;
a = (++a) * (++a);
System.out.println(a); // 20
Just to make sure where to put ++ expression which changes the value based on the location.
Everyone has clearly explained the first expression, and why the value of a is 12.
For the follow on question, the answer is totally obvious to the casual observer:
17
Pre & post-prefix increments have a higher precedence than the multiplication operator. hence the expression is evaluated as 3*4.
If you use a++ the next time you use a it is incremented by one. So your doing
a = 3 * (3 + 1) = 3 * 4 = 12

Strange behaviour of the increment operators in Java?

I have to pieces of code:
int m = 4;
int result = 3 * (++m);
and
int m = 4;
int result = 3 * (m++);
After the execution m is 5 and result is 15 in the first case, but in the second case, m is also 5 but result is 12. Why is this the case? Shouldn't it be at least the same behaviour?
I'm specifically talking about the rules of precedence. I always thought that these rules state that parantheses have a higher precedence than unary operators. So why isn't the expression in the parantheses evaluated first?
No - because in the first case the result is 3 multiplied by "the value of m after it's incremented" whereas in the second case the result is 3 multiplied by "the initial value of m before it's incremented".
This is the normal difference between pre-increment ("increment, and the value of the expression is the value after the increment") and post-increment ("remember the original value, then increment; the value of the expression is the original one").
The difference is when the result is assigned to m.
In the first case you have basically (not what it really does, but helps to understand)...
int result = 3 * (m=m+1);
In the second case you have
int result = 3 * m; m = m +1;
This is the definition of the operators: m++ evaluates to m, then increments m. It's a "post-increment". Parentheses around it don't change the fact that the operator evaluates to the variable, and also increments it afterward.
Think of it as "increment and get" and "get and increment." For instance, see AtomicInteger, which has the methods incrementAndGet() and getAndIncrement().

Categories