Increment operator ++ [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
post increment operator java
What is x after “x = x++”?
Can somebody explain me the result of each one of the following small programs? :
public static void main(String[] args) {
int a = 10;
a = a++;
System.out.println(a);
}
The result is: 10
Why not 11 since a should have been increased after the assignment? Is that the fact that it comes to different variables left and right of the opeartor = ?
The next one:
public static void main(String[] args) {
int a = 10;
a = ++a;
System.out.println(a);
}
The result is: 11
Comprehensible, but the compiler presents the warning: "The assignment to variable a has no effect". The result dissents though.
Update:
I do not modify my original question but I add this comment to clarify that now I catch the meaning of the warning. That is, even without the assignment (by a plain statement ++a) the result would be the same (11).

The value of a++ is a. ++ has higher precedence than =. So:
The value of a is taken.
a is incremented.
The value as at (1) is stored into a.
So the value of a doesn't change.
You can figure out yourself what happens in the second case.

In first case assignment happens first and then increment. So you get value which was before increment. But in second case it gets incremented first and then gets assigned.

Lets analyze the Byte code produced in each way -
int a = 10;
a = a++;
System.out.println(a); //Output - 10
produced ByteCode -
0 bipush
2 istore_1
3 iload_1
4 iinc
7 istore_1
8 getstatic
11 iload_1
12 invokevirtual
15 return
and
int a = 10;
a = ++a;
System.out.println(a); //Output -11
Here compiler give warning - The assignment to variable a has no effect
Produced ByteCode -
0 bipush
2 istore_1
3 iinc
6 iload_1
7 istore_1
8 getstatic
11 iload_1
12 invokevirtual
15 return
Here we can see in 1st case variable load first then increment so it does not effect anything to variable a.
Where as 2nd case it first increment then load the variable so it got effect of increment.

This happens because a++ is more like a Method then a realistic Number.
you can splitt them into two seperat lines.
the first one would be
a = a;
return a + 1;
the seconde one would be
a = a+1;

a++ means increase the value of variable a, however a++ has the original value of a!
a = ?? means set the value of a to ??
So what you are doing is incrementing the value of a by one, and then setting it to the old value.
++a means increase the value of variable a, however ++a has the new value of a!
So in the second example you are incrementing the value of a, and then setting the value of a to that value (it has just gotten), so you are doing the same twice.

a++ is equivalent to a = a + 1 but increments after the value is used in expression (assignment here) ++a is same but increments before its used in expression. a = ++a; has no explicit assignment affect as it is equal to a = a = a + 1

When you write a++ it means a will increment AFTER the '=' operator has been processed. So
b = a++;
System.out.println(a);
System.out.println(b);
Should produce on your screen: 11, 10. Because a becomes 11 after b takes the value of 'a'. If you change the a++ to ++a you force the increment to happen before the '=' is processed so you will be giving b = a + 1 and on your screen you should be having 11,11.

Related

Final variable printing in java

final int a=5;
System.out.println(a+1)
prints 6 whereas System.out.println(a++) or a=a+1 and then s.o.p(a) would give error.
Why would it print 6 when final values cant be changed?
Both a++ and a=a+1 assign a new value to a.
a+1 does not: it just evaluates to 1 more than the value in a.
Evaluating the statements:
System.out.println(a);
System.out.println(a+1);
System.out.println(a);
will show that the value of a is the same before and after. Doing the same with a++ or a=a+1 in the middle statement (obviously making a non-final first) will show that a is changed.
This should be no more surprising than System.out.println(5+1) printing 6, whilst leaving the values of 5 and 1 unchanged.
Because you never modify a in your example. You print the result of a+1. If you print a afterwards you'll see that it is still 5.
It is basically
int a = 5;
int b = a+1;
System.out.println(b); // prints 6
System.out.println(a); // still prints 5

Java for loop output [duplicate]

This question already has answers here:
What is x after "x = x++"?
(18 answers)
Closed 6 years ago.
import java.io.*;
public class test {
public static void main(String args[]) {
int a=0, b=6, sum;
for(int i=0; i<=2; i++) {
System.out.println(i=i++);
}
}
}
Output: 0 | 1 | 2. But actually I think it should be 0 | 2. Please explain why I am wrong? Thank you in advance.
The difference is in this line of code:
System.out.println(i=i++);
i++ is a post increment, meaning it is only executed after the rest of the statement.
so, it goes a bit like this:
System.out.println(
int tempI = i;
i = tempI;
tempI = i + 1;
);
In the end, you print the value of i, while the value of tempI is not used after that, so considered lost.
Answer is in byte code generated for above code. It store back the old value of i into i. Therefore i=i++ statement make no impact logically.
iconst_0
istore_1
goto 11
getstatic java/lang/System/out Ljava/io/PrintStream;
iload_1
iinc 1 1
dup
istore_1
invokevirtual java/io/PrintStream/println(I)V
iinc 1 1
iload_1
iconst_2
if_icmple 4
return
It is easy to test it out by yourself actually even without using a debugger.
int a=0,b=6, sum;
for(int i=0;i<=2;i++)
{
System.out.println(i=i++);
System.out.println("Value of i:" + i);
}
OUTPUT:
0
Value of i:0
1
Value of i:1
2
Value of i:2
Question:
So why after System.out.println(i=i++);, value of i is not increasing?
Answer: This is because i++ means post-increment. The i at the right hand side will only increase by one after that line.
//Let say i is 0.
i = i++;
i++ means the right hand side i will still be 0 till it goes to next line. Hence 0 was assigned to the i at the left hand side.
In your code:
for(int i=0;i<=2;i++)
{
System.out.println(i=i++); //here the value of i is incremented after it is assigned to i.
}
When you are doing i=i++ then i is incremented after the assignment. And hence you are not getting as expected.
You can use pre-increment operator and see the difference.
for(int i=0;i<=2;i++)
{
System.out.println(i=++i);
}
Here is a related thread which will help you: What is x after “x = x++”?
Please see this snippet:
for (int i=0; i<=2;i+=2){
System.out.println("i= "+ i);
}
this should give you a short way to do it.
If this works:.
for(int i=0;i<=2;i++)
{
System.out.println(i=++i);
}
Because this does not work?:
for(int i=0;i<=2;i++)
{
System.out.println(i=i++);
}
Apparently the postincrement in the println method is treated differently.
It is an undefined behaviour in C or C++ if you write:
i = i++;
Reason being that the order of evaluation cannot be determined. Hence if you write this in C or C++, there is no guarantee what will be produced.
In Java, this kind of ambiguity is removed from the design. The order of evaluation is as follows:
i = i++; //value of i++ is stored (0 is stored in this case)
//i increased by 1, i is now 1
//The stored value assigned back to i (0 assigned to i)

Can somebody explain i+++x?

I was messing with i++ when I stumbled upon i+++[another expression]. I went and tested it in DrJava:
> int i;
> i++
0
> i+++1
2
> i+++1
3
> i+++2
5
> i+++1
5
> ++i+1
7
> ++i+1
8
> ++i+1
9
> ++i+2
11
Later, I did this:
> int i;
> i+++(++i);
> System.out.print(i);
2
> System.out.print(i);
2
> i+++(++i);
> System.out.print(i);
4
> i+++(++i);
> System.out.print(i);
6
I concluded that the value that was being returned was the addition of i++ and another variable. But what about i+++(++i)? What's going on there? And most importantly, why would I want (or not want) to use this in my code?
i+++(++i)
We can rewrite this as
(i++) + (++i)
Note that i++ increments i and returns i's initial value, whereas ++i increments i and returns i's new value.
So, for i = 3, i++ increments i to 4 and returns 3. ++i then increments i to 5 and returns 5. Hence, the result is 8. i will have a final value of 5, as it was incremented twice:
int i = 3;
System.out.println(i+++(++i));
System.out.println(i);
8
5
Sometimes it's helpful to view this as bytecode:
ILOAD 1 // load i
IINC 1 1 // increment i
IINC 1 1 // increment i
ILOAD 1 // load new i (i.e. initial i + 2)
IADD // add top two values on stack: i and (i + 2)
And most importantly, why would I want (or not want) to use this in my code?
Never do something convoluted like this in your own code. Break it up into smaller, intelligible, parts, instead of doing it all on one line.
i+++(++i) can be re-written to (i++) + (++i)
In other words, it is the addition of a pre and post-increment of i.
However, it is so confusing and strange that it should never be used. Just use i += 2 instead.
You would never want to use this in your code. It is so confusing and obfuscated that you had to come here and ask about it. Your sense of human empathy should lead you to conclude that you would not feel good about putting another developer through that.
As for how i+++(++i), it decomposes into (i++) + (++i). If i starts as zero, the evaluation is:
i++ i becomes 1 and this evaluates to 0.
++i i becomes 2 and this evaluates to 2.
0 + 2 evaluates to 2 (not shown in your output), i is 2.
Now if i is 2:
i++ i becomes 3 and this evaluates to 2.
++i i becomes 4 and this evaluates to 4.
2 + 4 evaluates to 6 (not shown in your output), i is 4.
And if i is 4:
i++ i becomes 5 and this evaluates to 4.
++i i becomes 6 and this evaluates to 6.
4 + 6 evaluates to 10 (not shown in your output), i is 6.
Now i is 6:
i++ i becomes 7 and this evaluates to 6.
++i i becomes 8 and this evaluates to 8.
6 + 8 evaluates to 14 (not shown in your output), i is 6.
It is worth noting that a + b; is not a valid Java statement, but Dr. Java evaluates it anyways and prints the results (which it looks like you removed in your second snippet). The side effect, though, is that i is incremented twice every time (first by i++ then by ++i), as you can see by the values of i derived above.
For i+++N the decomposition is similar: This is (i++) + N. Say i is 0 and N is 3:
i++ i becomes 1 and this evaluates to 0.
0 + 3 evaluates to 3, i is 1 (not shown in your output).
Now i is 1:
i++ i becomes 2 and this evaluates to 1.
1 + 3 evaluates to 4, i is 2 (not shown in your output).
And so on. Each time, i gets incremented by 1, and the expression as a whole evaluates to the previous value of i plus N.
i+++1 => i++ post increment +1 add one, so it means: return i+1 and then increment i.
i++++x => i++ post increment, ++x pre-increment x ==> (i++)+(++x) ==> increment x, add it to i and after returning the result increment i.
Lets simplify
int x = 0;
x++ // now 1
then
x+++1 -> (x++) + 1 -> 2

How is that x=20;x= ++x + ++x + x++ ;final value of x in java is 65 [duplicate]

This question already has answers here:
How do the post increment (i++) and pre increment (++i) operators work in Java?
(14 answers)
Closed 5 years ago.
How is this possible as post increment operator should increase x to 66?
When I did the same for y= ++x + ++x + x++; it gave a value 65 for y and 23 for x.
So let me know how is java compilers solving these expression.
Let Java show you. javap -c MyClass shows you bytecode:
public static void main(java.lang.String[]);
Code:
0: bipush 20
2: istore_1
3: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream;
6: iinc 1, 1
9: iload_1
10: iinc 1, 1
13: iload_1
14: iadd
15: iload_1
16: iinc 1, 1
19: iadd
20: dup
21: istore_1
22: invokevirtual #3 // Method java/io/PrintStream.println:(I)V
25: return
And the result is completely logical if you think about it: you have two preincrements and one postincrement. So, your code is in effect:
y = 0
x++ // 21
y += x
x++ // 22
y += x
y += x // (still 22!)
x++ // 23
x = y // (21 + 22 + 22 at this point)
++x is different from x++
++x increments x before any operations done in that same line.
x++ increments x after any operations done in the same line.
For it to calculate to 65, it must be doing a calculation like the following.
(1+20)+(1+21)+(22)= 65
Afterwards, x would be 23
I think that y= (++20) + (++21) + 22 = 21 + 22 +22 = 65
So let me know how is java compilers solving these expression.
Java compiler are simply implementing the Java Language Specification.
If you really need to understand how compiler evaluates horrible and bizarre statements like that, you need to understand the relevant parts of the spec:
15.7 Evaluation Order
15.14.2 Postfix Increment Operator ++
15.15.1 Prefix Increment Operator ++
and so on.
First, you should understand this:
++i increments i and returns i.
i++ returns i and then increments it.
Now that we have established this, let's break the program down.
At the start of your program, x = 20. So, ++x would return 21. Now when you increment x in this fashion again, you will be incrementing 21 and not 20. So, ++x + ++x will evaluate to 21 + 22 which equals 43. At this point in the program, x equals 22. So if you add x++ to 43, you will add the value of x to 43 and only then increment x. This ultimately results in y having a value of 65, and x having a value of 23.
don't use ++ and = on the same variable in the same expression, the increment will not take into effect. from Java™ Puzzlers: Traps, Pitfalls, and Corner Cases By Joshua Bloch, Neal Gafter
Puzzle #25:
As the puzzle's title suggests, the problem lies in the statement that does the increment:
j = j++;
Presumably, the author of the statement meant for it to add 1 to the
value of j, which is what the expression j++ does. Unfortunately, the
author inadvertently assigned the value of this expression back to j.
When placed after a variable, the ++ operator functions as the postfix
increment operator [JLS 15.14.2]: The value of the expression j++ is
the original value of j before it was incremented. Therefore, the
preceding assignment first saves the value of j, then sets j to its
value plus 1, and, finally, resets j back to its original value. In
other words, the assignment is equivalent to this sequence of
statements:
int tmp = j;
j = j + 1;
j = tmp;
as a result your doe looks like this when it evaluates:
int x=20
int sum;
x=x+1; //x=20=1
sum=x; //sum and x equal 21
x=x+1; //x=22
sum=sum+x; //sum=43
sum= sum+x; //sum=65
x= x+1; //x=23
x=sum; //x=65;
This is why x=65 and not 66
Overall this is bad programming and should never ever be used in actual code because it is easy to get lost in all the pre and post increments.
But here is the basic explanation.
simple enough:
x = 20
Here is where it gets messy:
y = ++(20) + ++(++(20)) + (++(++(20)))++
Pre increment --> ++x
Post increment --> x++
Pre increments happen inside the evaluation and post
increments happen after the evaluation.
So that statement can be reduced in the following steps.
y = 21 + ++(21) + (++(21))++
y = 21 + 22 + (22)++
y = 21 + 22 + 22
y = 65
After all these increments x = 23. In the statement above though, x equals multiple
numbers because of all the pre and post increments.
Moral of the story, don't ever do this and pre increments take place before the expression is evaluated and post increments take place after the expression is evaluated.
You should remember this C Operator Precedence
so post increment goes first ++X = 20
then x++=22 then
x++ = 23 so total 65.

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

Categories