Increment Decrement operator use [duplicate] - java

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.
In the below programs , post increment operator is used just after completion of expression evaluation. Now for the first program shouldn't the answer be 40 n then value of a be incremented to 41.N likewise for program 2 answer should be 41 instead of 42?
class IncrementDemo{
public static void main(String [] args){
int a=20;
a= a++ + a++;
System.out.println(a); //Answer given is 41
}
class IncrementDemo{
public static void main(String [] args){
int a=20;
a= a++ + ++a;
System.out.println(a);
}
Answer given is 42 for second program.

You can understand the behaviour if you analyze how the statement is executed and the state of a in the meanwhile.
a = 20
a++ is executed, 20 is the result of the evaluation, a = 21
the second a++ is executed, 21 is the result, a = 22
the two results are added, 20 + 21 = 41, a = 41
on the other side, in the second case:
a = 20
a++ is executed, 20 is the result of the evaluation, a = 21
++a is executed, a = 22, 22 is the result
the two results are added, 20 + 22 = 42, a = 42
This is because the two increment operators are evaluated sequentially, so the second sees the effect of the first one.

The difference between those two is, that ++a will increment the value of a and return the incremented value. On the other hand a++ will increment the value, but return the original value that a had before being incremented.

The results are correct.
First case
int a=20;
a= a++ + a++;
This results in the following evaluation steps:
a = a++ + a++ (with a=20)
a = 20 + a++ (with a=21)
a = 20 + 21 (with a=22)
Second case
int a=20;
a= a++ + ++a;
This results in the following evaluation steps:
a = a++ + ++a (with a=20)
a = 20 + ++a (with a=21)
a = 20 + 22 (with a=22)

When operator used in prefix mode, it increments the operand and
evaluates to the incremented value of that operand. When used in
postfix mode, it increments its operand, but evaluates to the value of
that operand before it was incremented.
a= a++ + a++;
so first a++ will yield 20, now a value become 21
second a++ will yield 21, so final operation return 20+21 = 41
similar for second program
int a=20;
a= a++ + ++a;
First a++ will yield 20, now a value become 21
second ++a will yield value 22
combining both will return result 20+22 = 42

a = a++ + a++
For the first a++, the value of a being used for the calculation is its actual value: 20, and after that it is incremented to 21.
So, for the second a++, the value used for the calculation, is also the actual value of a, but this time it is 21 because it has been incremented in the first a++.
So you have 20 + 21, hence 41.
a = a++ + ++a
Same thing for a++, the actual value of a, 20 is used for the calculation, and then it is incremented to 21.
Then ++a, the value is incremented before it is used, so it becomes 22, and then it is used for the calculation.
So you have 20 + 22, hence 42.

Related

Pre and Postfix Increment

a = 1;
int a2 = a++;
System.out.println("----------Test 3 ----------");
System.out.println("The value of a is " + a);
System.out.println("The value of a2 is " + a2);
System.out.println("The value of a2 is " + a2);
The result is :
----------Test 3 ----------
The value of a is 3
The value of a2 is 2
The value of a2 is 2
I don't understand why the value of a2 does not increase after the second output. Even a is increased using postfix increment and assigned to a2. Please explain it to me.
I don't understand why the value of a2 does not increase after the
second output even a is increased using postfix increment and assigned
to a2.
Let us go step by step:
a = 1
set the variable a to 1; Now:
int a2 = a++;
will be equivalent to:
int a2 = a;
a++;
first assigned and only then increment, hence the output:
The value of a is 2
The value of a2 is 1
The value of a2 is 1
and the name postfix increment.
For the behavior that you want use ++a instead, namely:
int a = 1;
int a2 = ++a;
System.out.println("The value of a is " + a);
System.out.println("The value of a2 is " + a2);
System.out.println("The value of a2 is " + a2);
Output:
The value of a is 2
The value of a2 is 2
The value of a2 is 2
In this case :
int a2 = ++a; is equivalent to :
a++;
int a2 = a;
The prefix and postfix increment only matter within the statement you are executing. Try adding prefix and postfix increments in the print statement.
that is how the post increment operator is designed to work...
doing
int a2 = a++;
is equivalent to doing
int a2 = a;
a = a + 1;
so your code is producing this output:
----------Test 3 ----------
The value of a is 2
The value of a2 is 1
The value of a2 is 1

Why post increment opertor failed to increment 'a' in this code?

package com;
public class Test {
public static void main(String[] args)
{
int a= 11, b = 10;
a = a++ + ++b; //why? output is "22 11" and not "23 11"
System.out.println(a+" "+b);
}
}
Here's how the expression gets evaluated (roughly, I didn't check the JLS for evaluation order but I think it's from left to right):
a = a++ + ++b; // a is 11, b is 10
a = 11 + ++b; // a is 12 but its previous value 11 was returned by a++, b is 10
a = 11 + 11; // a is 12, b is 11 and its updated value was returned by ++b
a = 22; // a is 12, b is 11 and its updated value was returned by ++b
Therefore, it's the expected result, you just have to apply the definition of those operators.
a++ means that "a" has old value in place where you write it and change it after. ++a means that "a" at fist change value and than will be calculate.
So:
a = 5;
b = 5;
So:
a++ + ++b = (5 (and a + 1 later) + (at first b + 1) 6.
I hope you understand me) My English is in the same level with your Java=)

Does Incrementing In Java Change its Immediate Value? [duplicate]

Can you explain to me the output of this Java code?
int a=5,i;
i=++a + ++a + a++;
i=a++ + ++a + ++a;
a=++a + ++a + a++;
System.out.println(a);
System.out.println(i);
The output is 20 in both cases
++a increments and then uses the variable.
a++ uses and then increments the variable.
If you have
a = 1;
and you do
System.out.println(a++); //You will see 1
//Now a is 2
System.out.println(++a); //You will see 3
codaddict explains your particular snippet.
Does this help?
a = 5;
i=++a + ++a + a++; =>
i=6 + 7 + 7; (a=8)
a = 5;
i=a++ + ++a + ++a; =>
i=5 + 7 + 8; (a=8)
The main point is that ++a increments the value and immediately returns it.
a++ also increments the value (in the background) but returns unchanged value of the variable - what looks like it is executed later.
In both cases it first calculates value, but in post-increment it holds old value and after calculating returns it
++a
a = a + 1;
return a;
a++
temp = a;
a = a + 1;
return temp;
i = ++a + ++a + a++;
is
i = 6 + 7 + 7
Working: increment a to 6 (current value 6) + increment a to 7 (current value 7). Sum is 13 now add it to current value of a (=7) and then increment a to 8. Sum is 20 and value of a after the assignment completes is 8.
i = a++ + ++a + ++a;
is
i = 5 + 7 + 8
Working: At the start value of a is 5. Use it in the addition and then increment it to 6 (current value 6). Increment a from current value 6 to 7 to get other operand of +. Sum is 12 and current value of a is 7. Next increment a from 7 to 8 (current value = 8) and add it to previous sum 12 to get 20.
++a increments a before it is evaluated.
a++ evaluates a and then increments it.
Related to your expression given:
i = ((++a) + (++a) + (a++)) == ((6) + (7) + (7)); // a is 8 at the end
i = ((a++) + (++a) + (++a)) == ((5) + (7) + (8)); // a is 8 at the end
The parenteses I used above are implicitly used by Java. If you look at the terms this way you can easily see, that they are both the same as they are commutative.
In the above example
int a = 5,i;
i=++a + ++a + a++; //Ans: i = 6 + 7 + 7 = 20 then a = 8
i=a++ + ++a + ++a; //Ans: i = 8 + 10 + 11 = 29 then a = 11
a=++a + ++a + a++; //Ans: a = 12 + 13 + 13 = 38
System.out.println(a); //Ans: a = 38
System.out.println(i); //Ans: i = 29
I believe however if you combine all of your statements and run it in Java 8.1 you will get a different answer, at least that's what my experience says.
The code will work like this:
int a=5,i;
i=++a + ++a + a++; /*a = 5;
i=++a + ++a + a++; =>
i=6 + 7 + 7; (a=8); i=20;*/
i=a++ + ++a + ++a; /*a = 5;
i=a++ + ++a + ++a; =>
i=8 + 10 + 11; (a=11); i=29;*/
a=++a + ++a + a++; /*a=5;
a=++a + ++a + a++; =>
a=12 + 13 + 13; a=38;*/
System.out.println(a); //output: 38
System.out.println(i); //output: 29
++a is prefix increment operator:
the result is calculated and stored first,
then the variable is used.
a++ is postfix increment operator:
the variable is used first,
then the result is calculated and stored.
Once you remember the rules, EZ for ya to calculate everything!
Presuming that you meant
int a=5; int i;
i=++a + ++a + a++;
System.out.println(i);
a=5;
i=a++ + ++a + ++a;
System.out.println(i);
a=5;
a=++a + ++a + a++;
System.out.println(a);
This evaluates to:
i = (6, a is now 6) + (7, a is now 7) + (7, a is now 8)
so i is 6 + 7 + 7 = 20 and so 20 is printed.
i = (5, a is now 6) + (7, a is now 7) + (8, a is now 8)
so i is 5 + 7 + 8 = 20 and so 20 is printed again.
a = (6, a is now 6) + (7, a is now 7) + (7, a is now 8)
and after all of the right hand side is evaluated (including setting a to 8) THEN a is set to 6 + 7 + 7 = 20 and so 20 is printed a final time.
when a is 5, then a++ gives a 5 to the expression and increments a afterwards, while ++a increments a before passing the number to the expression (which gives a 6 to the expression in this case).
So you calculate
i = 6 + 7 + 7
i = 5 + 7 + 8
Pre-increment means that the variable is incremented BEFORE it's evaluated in the expression. Post-increment means that the variable is incremented AFTER it has been evaluated for use in the expression.
Therefore, look carefully and you'll see that all three assignments are arithmetically equivalent.
pre-increment and post increment are equivalent if not in an expression
int j =0;
int r=0
for(int v = 0; v<10; ++v) {
++r;
j++;
System.out.println(j+" "+r);
}
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 10
I believe you are executing all these statements differently
executing together will result => 38 ,29
int a=5,i;
i=++a + ++a + a++;
//this means i= 6+7+7=20 and when this result is stored in i,
//then last *a* will be incremented <br>
i=a++ + ++a + ++a;
//this means i= 5+7+8=20 (this could be complicated,
//but its working like this),<br>
a=++a + ++a + a++;
//as a is 6+7+7=20 (this is incremented like this)
a=5; i=++a + ++a + a++;
is
i = 7 + 6 + 7
Working: pre/post increment has "right to left" Associativity , and pre has precedence over post , so first of all pre increment will be solve as (++a + ++a) => 7 + 6 . then a=7 is provided to post increment => 7 + 6 + 7 =20 and a =8.
a=5; i=a++ + ++a + ++a;
is
i=7 + 7 + 6
Working: pre/post increment has "right to left" Associativity , and pre has precedence over post , so first of all pre increment will be solve as (++a + ++a) => 7 + 6.then a=7 is provided to post increment => 7 + 7 + 6 =20 and a =8.

getting confusion on this explain this loop result in java

int a = 0, b = 0;
for (int i = 0; i < 5; i++) {
if (++a > 2 || ++b > 2) {
a++;
}
}
System.out.println("a= " + a + " b=" + b);
can you explain the logic please?
i=0 a=1 (1st condition is false so 2nd is check) b=1
i=1 a=2 (1st condition is false so 2nd is check) b=2
i=2 ++a increment a , a=3 condition is true enter in if condition and a become 4 and b remain 2
similarly i=3 a=6 b=2 and i=4 a=8 b=2;
In case of or(||) condition whenever compiler encounter true condition it stop checking other statement
These are the five iteration and result of a & b finally. Every row is the result of every single iteration in loop.
a b
--------
1 1
2 2
4 2
6 2
8 2
++a > 2 means increment a (by 1) first than compare with 2
++b > 2 means increment b (by 1) first than compare with 2
a++ means a=a+1; means increment a by 1.
I think your confusion may come from ++a vs a++. So basicly, both of them increment the value carried by a by 1, this mean a = a + 1.
The difference is ++a will do the increment first, then do the comparison, while a++ will do the comparison first then increment.
So look at your code:
1st line: just declaring variables a and b, and instantiating
3rd line: for loop will iterate 5 times
First iteration:
- 4th line: ++a ---> a == 1, then compare it to 2, so on for b, here the expression returns false, so skip line 5.
9th line: here it prints out a= 1 b=1
Second iteration:
- 4th line: ++a ---> a == 2, then compare it to 2, so on for b, here the expression returns false, so skip line 5.
9th line: here it prints out a= 2 b=2
Third iteration: (later iterations are similar)
- 4th line: ++a ---> a == 3, then compare it to 2, so on for b, here the expression returns true, so line 5 is reached now.
5th line: a++ ---> a == 4
9th line: here it prints out a= 4 b=3
Hope that helps.
++a means the current value of a is increased by 1 before the operations.(in this case, it increase value of a by 1 before compare a > 2)
a++ means the current value of a is increased by 1 after the operations. (in this case, increase value of a, although there is no operations.)
For loop is not interrupted by anything..... So, it loops for 5 times(i = 0,1,2,3,4).
for i = 0 ->
current value of a = 0, current value of b = 0
if ( ++a > 2 || ++b > 2 )
in this statement, a is increase by 1 before compare with 2. So the current value is 0 and the increased by 1. new value is 1.
now compare a (1) with 2.... and same thing happens with the b.
if ( 1 > 2 || 1 > 2 )
the statement is false. so go to the end of the end statement.
for i = 1 -> current value of a = 1, current value of b = 1
same as before value of a is increased by 1 before compare 'a > 2' and also with the b.( new a = 2, b = 2 )
if (2 > 2 || 2 > 2 )
statement is false. to the end of the if statement.
for i = 2 -> current value of a = 2, b = 2
increase a by 1 -> a = 3 and also b = 3 before compare.
if ( 3 > 2 || 3 > 2 )
if condition becomes true. then
a++
statement executes.
new value of a = 4. value of b stays the same (3).
for i =3 -> current values a = 4, b = 3
increase a and b by 1 new values (a= 4, b =4 )
if ( 5 > 2 || 4 > 2 )
true. then
a++
new value of a = 6, b stays the same (4).
for i = 4 -> current values a = 6, b = 4.
increase a and b ( 7, 5 )
if ( 7 > 2 || 5 > 2 )
true. then
a++
new value of a = 8. and b stays the same (5).
end of the for loop ( i < 5 condition fails)
next statement
System.out.println("a= " + a + " b=" + b)
displays "a= 8 b=5"

In Java, why does an assignment in parentheses not occur before the rest of the expression is evaluated?

Consider
int a = 20;
a = a + (a = 5); // a == 25, why not 10?
Don't parentheses trump all precedence rules? Are some variables on the RHS prepopulated before evaluation of certain expressions?
Because a is loaded first in the example you have, and then the bit in parenthesis is evaluated. If you reversed the order:
int a = 20;
a = (a = 5) + a;
System.out.println(a);
10
... you do indeed get 10. Expressions are evaluated from left to right.
Consider this:
f() + g()
f will be called before g. Imagine how unintuitive it would be, in
f() + (g())
to have g be called before f.
This is all detailed in JLS ยง15.7.1 (thanks to #paisanco for bringing it up in the comments).
From the JLS
The Java programming language guarantees that the operands of
operators appear to be evaluated in a specific evaluation order,
namely, from left to right.
and
The left-hand operand of a binary operator appears to be fully
evaluated before any part of the right-hand operand is evaluated.
Wrapping an expression in parentheses just helps grouping (and associativity), it doesn't force its evaluation to happen before anything to its left.
Generated bytecode:
BIPUSH 20
ISTORE 1
ILOAD 1
ICONST_5
DUP
ISTORE 1
IADD
ISTORE 1
RETURN
LOCALVARIABLE a I
First, you assign 20 to the first variable (a):
BIPUSH 20
ISTORE 1
Then, you load the contents of the first variable to stack (20 is put on stack):
ILOAD 1
Then, you push the constant '5' to the stack twice (20 5 5):
ICONST_5
DUP
Then, you store the top of the stack to the first variable (a):
ISTORE 1
a is now 5, stack is now (20 5). We add both operands and put their sum to the first variable (a):
IADD
ISTORE 1
As a consequence, a is now 20 + 5 = 25. We end:
RETURN
You asked why and the latest JLS provides a clearer explanation of what is happening in JLS 17:
In particular, the presence or absence of parentheses around an
expression does not affect whether a variable is definitely assigned,
definitely assigned when true, definitely assigned when false,
definitely unassigned, definitely unassigned when true, or definitely
unassigned when false.
In effect they are saying that parentheses do not prompt assignment, which explains why assignment occurs left-to-right, unlike evaluation, which occurs in innermost-to-outermost order.
But that still does not answer why.
It's not because of compatibility with Java's predecessor, at least not in its present form, because the behavior does not match C:
Java 17:
int j = 3, k = 4, l = 5, m = 6, n = 7;
System.out.println(((j = 3) + j) + j); // 3 + 3 + 3 = 9
System.out.println(k + (k + (k = 3))); // 4 + 4 + 3 = 11
System.out.println(l + ((l = 3) + l)); // 5 + 3 + 3 = 11
System.out.println((m + (m += 3)) + m); // 6 + 9 + 9 = 24
System.out.println(n + (n += n / 2) + ++n); // 7 + 11 + 12 = 28
GCC 7.5.0:
printf("%d\n",((j = 3) + j) + j); // 3 + 3 + 3 = 9
printf("%d\n",k + (k + (k = 3))); // 3 + 3 + 3 = 9
printf("%d\n",l + ((l = 3) + l)); // 3 + 3 + 3 = 9
printf("%d\n",(m + (m += 3)) + m); // 9 + 9 + 9 = 27
printf("%d\n",n + (n += n / 2) + ++n); // 10 + 10 + 11 = 31
This leaves us with the explanation used elsewhere for Java awkwardness: upgradeability. Java happened to do it this way at the time it was written; changing it to work in alignment with C would potentially break existing code. I'd be curious to know of any discussion that might have taken place when the initial design was decided.

Categories