Can somebody explain i+++x? - java

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

Related

Why is while loop treated true if condition is false?

I am trying to do in Java:
int i=5;
while(i-- >0) {
System.out.println(i);
}
When running this program the output is:
4
3
2
1
0
I am very surprised to see 0 in output. I am new in development. Can anyone justify this?
In your while condition i-- > 0, the variable i is evaluated first and then decremented.
When i reaches the value 1, it will pass the loop test and then get decremented to 0. This is why the print statement shows 0 in the output.
Here is a mnemonic you can use to keep track of how the decrement and increment operators work:
int i = 5;
System.out.println("When i = 5 then:");
System.out.println("i-- is " + i--);
i = 5;
System.out.println("--i is " + --i);
Output:
When i = 5 then:
i-- is 5
--i is 4
Simply, because you compare i>0 and decrement i afterwards.
// If I is 1, you compare 1>0 and decrement i afterwards.
// This is how the postdecrement operator works
while(i-- >0) {
System.out.println(i);
}
the loop will behave like the following.
is i=5 > 0?
decrement i to 4
output i = 4.
is i=4 > 0?
decrement i to 3
output i = 3.
...
and so on
As you can see the value you compare to 0 is allways higher then the one you are outputing. This happens due to how the -- operator works. If it´s preceding to the i as --i it will decrement the variable i first and return it´s value afterwards. If it´s not preceding as in your case i-- you will have the value of i returned first and i beeing decremented afterwards.
Postdecrement/Increment operator works on the principle "Use first and then Change"
Initially value of i=5, when it enters while loop it will compare value of i first and then it prints the decremented value. Here i will show you each iteration along with checks performed in each iteration,
Now value of i=5(in memory), inside while(5>0), it prints 4.
Now value of i=4(in memory), inside while(4>0), it prints 3.
Now value of i=3(in memory), inside while(3>0), it prints 2.
Now value of i=2(in memory), inside while(2>0), it prints 1.
Now value of i=1(in memory), inside while(1>0), it prints 0.
Hope now you are clear to go ahead. Gud Luck.
The post-decrement operator -- is like a post-paid service. Like a credit card, first you use, then you pay.
I thought I can give you a real-life idea of what really is occurring in this statement, when i == 1
while(i-- >0)
So, first you check if i(1)>0. 1>0 So, yes it is. Right after this statement is done, i becomes 0. Then, you print that value.
Alternatively, you might also get this intuition by noticing that although your loop started with i=5, the value 5 never got printed.
Since you are using the post-decrement operator in the while loop, when i is 1, i-- returns 1, and then inside the loop you get 0 when you print i for the last time.
Only because of post decrement operator (i--) will check the condition first then decrease the value of i. Output is giving such. Thank you
int i=5; //initialize with 5
while(i-- >0) { //post decrements operator so, check condition first then decrease the value.
System.out.println(i);
}
In first iteration of while loop will check 5 > 0 will be checked after that decrease the value of i and i will become 4 So, Print it 4 not 5.
When i = 5 conditional statement will be (5>0) (true) and print 4.
i = 4 conditional statement will be (4>0) (true) and print 3.
i = 3 conditional statement will be (3>0) (true) and print 2.
i = 2 conditional statement will be (2>0) (true) and print 1.
i = 1 conditional statement will be (1>0) (true) and print 0.
Now, i became 0 so conditional statement will be (0>0) (False).
So, loop exits.
To get desired output try this
while(--i >0) {
System.out.println(i);
}

using operators ++ and -- in java, confused

I am very new to Java (4 weeks, 4 days a week), with zero prior programming knowledge. Can someone explain how this prints 32?
int a = 10;
a = a++ + a + a-- - a-- + ++a;
System.out.println(a);
a++ > means use then change .. So value of a is used first = 10 and then incremented = 11
++a > means change then use. So value of a is first changed then used.
So a = a++ + a + a-- - a-- + ++a;
= (10)
+ (11 [since a is incremented after use])
+ 11 [since a-- = use then change = 11, after -- becomes 10]
- 10 [since value of a is now decremented, and then decremented again, so a = 9 at this point]
+ 10 [since ++a is change then use]
in summary
a = 10 + 11 + 11 - 10 + 10 = 32.
Hope it helps :)
Let's take this one step at a time.
a++ will increment a by one.
a++ +a will take the (11)+ the existing a(10), to give 21
Another iteration will set a to 30, with a decremented by 1 at the end.
- a-- will subtract 1 from a, and subtract this from the value. So -9,
This one is the real trick. a is incremented before any other operation starts. So a becomes 11, before everything else even calculates.
Bottom line, this simplifies to:
4*a-a-2+1= 3*a-1, where a=11 because it has been incremented before anything started (++a).
If instead you moved the ++ to the other side of the ++a, you'd have 29, which is much easier to understand where it comes from.
Easy:
a = 10 + 11 + 11 - 10 + 10 = 32.
It's clearer with parentheses added:
a = (a++) + (a) + (a--) - (a--) + (++a);
The ++ and -- are evaluated based on where they are in relation to the variable, if it is a++ then a is first evaluated, then it is incremented. If you have ++a, then a is incremented and then evaluated.
So a++ + b will take a and add it to be, and then increment it,
while,
++a + b will first increment a, and then add it to b.
In simple
public static int i = 10;
is indicating that the integer i has a value of 10.
then saying
i++;
will make i's value 11, so it just like saying 10 + 1
saying
i--;
will makes i's value 9, so its like saying 10 - 1.
then
i = i + 1;
will do the same as i++;
but its used like i = i + 20; in most cases to take its value and add 20 to it.
same for
i = i - 20;
but taking away instead of adding.
then
a + a;
that will double a.
Hope this helps, Luke.

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.

Increment operator ++ [duplicate]

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.

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