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.
Related
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.
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.
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!
In
int x = 5;
int answer = x++ * 6 + 4 * 10 / 2;
the output is 50, and but why the ++ operator doesn't evaluate the expression to 51?
The ++ is on the x not the result.
why the ++ operator doesn't evaluate the expression to 51?
Can you explain how or why that would work? If you wanted that just do
int answer = x * 6 + 4 * 10 / 2 + 1;
The assignment is using the postfix operator which increments after the statement is executed.
The JLS mentions this:
The value of the postfix increment expression is the value of the
variable before the new value is stored.
For more details see the full specification entry.
Postfix operator is evaluates after execution of statement.
According to java
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.
The defined effect of the ++ postfix operator is that the variable x gets incremented, as if you wrote x = x+1, but the value of the expression x++is the value before the increment. If you want to have th esame effect regarding how xchanges, but use the after avlue in the surrounding expression, you need to use ++x. And if you actually didn't want to increment the contents of x at all, use (x+1).
(It is however not defined, I think, when the assignment of the incremented value to x takes place - it might even be afer anwser obtains its value; on the other hand, usually x++ is almost atomic.)
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Incrementing in C++ - When to use x++ or ++x?
I've seen things like i++ commonly used in, say, for loops. But when people use -- instead of ++, for some reason some tend to write --i as opposed to i--.
Last time I checked, they both work (at least in JavaScript). Can someone tell me if this is so in other C-family languages, and if it is, why do some people prefer --i to i--?
++i is faster than i++. Why? See the simple explication.
i++
i++ will increment the value of i, but return the pre-incremented value.
temp = i
i is incremented
temp is returned
Example:
i = 1;
j = i++;
(i is 2, j is 1)
++i
++i will increment the value of i, and then return the incremented value.
Example:
i = 1;
j = ++i;
(i is 2, j is 2)
This is simillar for --i and i--.
I don't believe the preference for prefix (++i) vs. postfix (i++) varies depending on whether it's an increment or a decrement.
As for why, I prefer prefix where possible because my native language is English, which has mostly a verb-before-object structure ("eat dinner", "drive car"), so "increment i" or "decrement i" is more natural for me than "i decrement". Of course, I'll happily use postfix if I'm using the result and I need the value prior to the increment in an expression (rather than the incremented value).
Historically the increment/decrement operator were motivated by stack management. When you push an element on the stack:
*(stackptr++) = value
when you pop:
value = *(--stackptr)
(these were converted to single ASM instructions)
So one gets used to increment-after and decrement-before.
You can see another idiomatic example in filling in direct and reverse order:
for (p=begin;p!=end;)
*(p++) = 42;
for (p=end;p!=begin;)
*(--p) = 42;
It's pretty much a preference thing, that only comes into play if you're doing the pre- or post-increment on types that are more complicated than primitives.
Pre-increment ("++i") returns the value of i after it has been incremented, and post-increment ("i++") returns the value before increment. So, if i was of a complicated type that had overloaded the pre-increment and post-increment operators, the pre-increment operator can just return the object, whereas the post-increment would have to return a copy of the object, which could well be less efficient if the object is substantial. And in most cases (for loop increments, etc.), the value is ignored anyways.
Like I said, most of the time, not a problem, and just a preference thing.
In C and C++,++ and -- operators have both prefix form: ++i and --i, and suffix form: i++ and i--. Former means evaluate-then-use and latter means use-then-evaluate. The difference is only relevant when either form is used as part of an expression. Otherwise it's a matter of preference or style (or lack thereof).
F.ex., in int i = 0; int n = ++i;, i is first incremented and then its value, now 1, is assigned to n. In n = i++ value of i, still 1, is assigned to n and is then incremented, with i == 2 now.
When used as a statement, that is: i++; ++i; both forms are equivalent.
The difference is pre-incrementing or post-incrementing (and likewise with decrementing).
Quoting the Wikipedia article on the topic that shows up as the second Google result for "c decrement":
int x;
int y;
// Increment operators
x = 1;
y = ++x; // x is now 2, y is also 2
y = x++; // x is now 3, y is 2
// Decrement operators
x = 3;
y = x--; // x is now 2, y is 3
y = --x; // x is now 1, y is also 1
So, it's not so much a matter of preference as a matter of difference of results.