Increment operator value(java)? - java

Why does the following not execute to 5?
int i = 5;
System.out.println(i-- + (5 - i--));
Output:
6
Since i-- is decremented after the statement is executed and (5 - i--(which should be 5)) = 0 then shouldn't the value simply equal 5? What concept am I missing here?

For kicks
i-- + (5 - i--)
5 (i value is 4) + (5 - 4 (i value is 3))
5 + 1
The result of a i-- postfix decrement operation is the value of the variable before the --. The variable is still decremented after it is evaluated however.
From the Java Language Specification
The result of the postfix decrement expression is not a variable, but
a value.
and
the value 1 is subtracted from the value of the variable and the
difference is stored back into the variable.

Evaluation of equations is done From Left to Right
when the left most (i-- is encountered because of post decrement the
value 5 will be used and then decremented by 1.
similarly,
when the next i-- is encountered the value was 4..
hence,
(5+(5-4)=6

Evaluating from left to right, we have:
a = i--
b = 5 - i--
c = a + b
a = 5 because -- is postdecrement.
b = 5 - 4 (already decremented, after this operation will follow another decrement)
a + b = 6

i-- operation comes before all the others, see the order here.
so what happens is i decrement first, each time you get to i--, then all the other stuff is happening as you know it.
If you want to explore it more : look for answers for these:
i++ + ++i
--i++
i-- - (i-- + i--)
It's very interesting!

Related

In Java,operator precedence, increment and decrement, why isn't the first println statement executed? [duplicate]

This question already has answers here:
How increment and decrement with if condition
(2 answers)
Closed 5 months ago.
class Example{
public static void main(String args[]){
int x=99;
if(x++==x){
System.out.println("x++==x : "+x); //Why this code line is not run?
}
if(++x==x ){
System.out.println("++x==x : "+x);
}
}
}
Why isn't the first println statement executed?
The operands of an expression are evaluated left to right.
In the expression x++ == x, first x++ is evaluated. It increments x by 1, but returns the original value of x. So x++ returns 99.
Then x is evaluated, which returns 100 (since it was incremented by x++).
Since 99 is not equal to 100, this condition evaluates to false.
If you change the expression to x==x++, you'll get true.
The differece between i++ and ++i is very simple.
i++ - means exactly first get the value and then increment it for the further usage
++i - means exactly first increment the value and use the incremented value
Following the shippet x++ == x means following:
Analyze expression from left to the right
Get x = 99 as the left operand and use it in the expression
Increment x and thus x == 100
Get x = 100 as the right operand (note it is already incremented)
99 != 100
Following the shippet ++x == x means following:
Analyze expression from left to the right
Get x = 99 as the left operand
Increment x and thus x == 100 and use it in the expression
Get x = 100 as the right operand (note it is already incremented)
100 == 100
You can see all these logic. E.g. not experienced developer cannot know these details. Therefore the best practice is to avoid such increments in the expression. Just do it before the expression in the single line. In this case the logic will be straight forward and you get much less problems.

How to evaluate the java operators evaluation

I am java newbie and trying to understand how calculation steps are performed to achieve final result. The final answer is coming as 49. Looking at precedence operators hierarchy my calculation is not coming to 49.
Following is my code with expression:
class Test
{
public static void main(String args[])
{
int a = 6, b = 5;
a = a + a++ % b++ *a + b++ * --b;
System.out.print(a)
}
}
Modulo has same precedence as division and multiplication. The next precedence goes to addition and subtraction.Operations happen left to right.
Adding brackets for better clarity:
( a ) + ( a++ % b++ *a ) + ( b++ * --b )
group I II III
a++ % b++ *a evaluated as :a. (6 % 5) = 1
b. 1 * 6 till now, a = 6, b = 5
Having completed this operation, the value of a & b are incremented to 7 & 6 respectively. i.e the post fix increment happens only after the modulo/multiplication/division during a step or group as shown above.
b++ * --b => 6 * 6. gives value of 36
Having completed this operation the ++ operation is performed but -- is also performed, effectively leaving the value of b at 6.
next operation is addition. i.e 7 + 6 + 36 = 49
Reference: https://www.programiz.com/java-programming/operator-precedence
Operators have priorities. There is a table of these here.
Also, you can use round brackets (parentheses) for forcing the right sequence of calculations.

Java Arithmetic expression

The following expression evaluates to 14.
int a=4;
int b=6;
int c=1;
int ans= ++c + b % a - (c - b * c);
System.out.print(ans);
This is how i calculate this
1. (c - b * c) // since bracket has highest preference
ans : -5
2. ++c //since unary operator has next highest preference
ans : 2
3. b%a // % has higher preference than + and -
ans : 2
Therefore, 2 + 2 - (-5) = 9
As you can see I'm getting 9 as the value. Not sure what's wrong in my way of calculation (pretty sure I'm gonna end up looking stupid)
Edit : I refered to the below link for precedence and association.
https://introcs.cs.princeton.edu/java/11precedence/
Can someone explain the difference between level 16 and level 13 parentheses? I thought level 13 parentheses is used only for typecasting. That is why i considered level 16 parenthesis for evaluating the expression.
Evaluation order is not the same as precedence. Java always evaluates left-to-right (with a minor caveat around array accesses).
Effectively, you are evaluating the following expression, because the very first thing that happens is the pre-increment of c:
2 + 6 % 4 - (2 - 6 * 2)
Precedence then describes how the values are combined.
As you are using pre-increment operator on c. So, after applying increment on c the value of c will be 2. Now :
(c - b * c) will be evaluated to (2 - 6 * 2)= -10
So, the final expression will be 2 + 2 - (-10) = 14

Result of function that includes pre- and post-increment differs

I had to understand some code which mixes pre- and post-increments in functions. There was one thing that confused me.
So I tried to test some smaller function. But I could not explain following behaviour:
int i = 1;
i = i++ * ++i * 2;
System.out.println("i = " + i);
int x = 1;
x = ++x * x++ * 2;
System.out.println("x = " + x);
The expected output was:
i = 8
x = 8
But actually is:
i = 6
x = 8
Can someone tell me why?
i++ * ++i * 2 --> 1 * 3 * 2 --> 6
++x * x++ * 2 --> 2 * 2 * 2 --> 8
Important values in bold.
The difference between the prefix and postfix increment when returning values in Java can be better summarized by Oracle themselves (my bold again for highlighting purposes):
The increment/decrement operators can be applied before (prefix) or after (postfix) the operand. The code result++; and ++result; will both end in result being incremented by one. The only difference is that the prefix version (++result) evaluates to the incremented value, whereas the postfix version (result++) evaluates to the original value. If you are just performing a simple increment/decrement, it doesn't really matter which version you choose. But if you use this operator in part of a larger expression, the one that you choose may make a significant difference.
Source here.
In your specific case, as the postfix evaluates to the original value and the order of operations is left to right for same arithmetic operator - here, only multiplier applies - your operations are translated as above.
Post-increment increases the value of i but does not immediately assign the new value of i.
Pre-increment increases the value of i and is immediately assigned the new value.
Thus, in your example for y, after i++,
i has become 2 but it is still holding on to the previous value of 1.
When ++i occurs, i with the value of 2 will be increased by 1 and simultaneously, assigned the new value of 3. Therefore, 1 * 3 * 2 gives us the value 6 for y.
The same goes for x,
when ++x occurs, x is immediately assigned the new value of 2.
However, when x++ occurs, x is increased by 1 but is still assigned the previous value of 2. Therefore, 2 * 2 * 2 gives us 8.

Increment Operator [duplicate]

This question already has answers here:
How do the post increment (i++) and pre increment (++i) operators work in Java?
(14 answers)
Closed 7 years ago.
I missed this question three times on a test. I just can't seem to grasp how to solve this. Any help is much appreciated.
public class Test {
public static void main(String[] args) {
int j = 0;
int i = ++j + j * 5;
System.out.println("What is i? " + i);
}
}
For:
int i = ++j + j * 5;
The variable j is per-incremented by 1 with the expression ++j, that is equal to j+1, changing the value of j to 1. Then following the rules for the order of operations in java, the multiplication is executed (j * 5) or (1 * 5) at this stage, so currently i = 5. Finally to the product of the multiplication j is added (j + 5) or (1 + 5) = 6.
You can check this page where this is explain in a simple way:
http://introcs.cs.princeton.edu/java/11precedence/
As per Java's operator precedence and evaluation order, i is equal to 6. i is set equal to j which is pre-incremented to 1, and added to the product of itself and 5, which is 6.
The thing to note here is the difference between j++ and ++j. See this: The difference between ++Var and Var++
Keeping this in mind, ++j will return 1, and change j's value to 1. So the next part, j*5 is equal to 1*5, which is 5. So overall ++j + j*5 gives you 6.
if ++j appears in the statement, the value of j is first incremented and then the statement is executed. But if j++ appears in the statement, first statement is executed and then the value is incremented.
To simply solve execution part, you can ignore ++ sign and simplify it. But don't forget the order of increment and simplification.
Java has an operator precedence rule which means for any mathematical expression in Java which contains operators, postfixes(j++) and prefixes(++j) are evaluated first. There is also left and right associativity which is how your statement is parsed. Mathematical operators such as +,-,/,* have left to right associativity. Postfixes and Prefixes have right to left associativity.
Looking at the Java Grammar File one finds that
The value of the prefix increment expression is the value of the
variable after the new value is stored
So, ++j is 1 for the current statement.
The value of the postfix increment expression is the value of the
variable before the new value is stored.
So, j++ is 0 for the current statement.
So, (++j) + j * 5 after prefix evaluation becomes (1 + (1 * 5)) = 6.
[Edit]
Thus, statement such as j++ + j * 5 will give you 5 as an answer because j becomes 1 after j++(postfix increment) but j++ itself remains 0.
According to java operator precedence, ++ operator has higher precedence than + and * operators. Here's what happens, step by step:
First ++j happens. Since j is 0, ++j increments j to 1.
Now the expression ++j + 5 * j has become 1 + 5 * 1.
Now we have two operators, + and *. Which one is applied first? See the operator precedence chart and you will find out that * has higher precedence than + . So first 5 * 1 takes place first. After multiplication the expression looks like 1 + 5.
Adding 1 to 5, we get 6. So....i = 6 is the result.
If u want to know more about ++ operator, there are some decent videos on youtube.

Categories

Resources