Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# What is the value of ( ++i + --i)?

satya mamillapalli
Ranch Hand
Posts: 63
int i =10;
Khalid book shows value of (++i + --i) as 21.How?

Should ++ and -- have right to left associativity?Then

(++i + --i) = (++i + 9) = (10 + 9) = 19

Thanks
Satya
[ August 18, 2005: Message edited by: satya mamillapalli ]

Joe Borderi
Ranch Hand
Posts: 151
Why don't you write a driver program? The JVM should give you the definitive answer.

Bob Nedwor
hangman
Ranch Hand
Posts: 215
Here it is:

C:\J2Class>type test.java
class test {
public static void main (String [] args) {
int i = 10;
System.out.println(++i + --i);
}
}

C:\J2Class>javac test.java

C:\J2Class>java test
21

C:\J2Class>

Any of you experts correct me if I am wrong, but what is happening here is the first operation is that we are incrementing i from 10 to 11, then adding it to i again which would otherwise still be 11, but since the decremenation occurs first, i then becomes 10 again. Thus 11 + 10 = 21. I hope that helps.
--Bob

Joe Borderi
Ranch Hand
Posts: 151
I apologize. Your topic read "What is the value...?" Your post, in essence, asked, "Why is the value...?" For "what is the value?" questions, the best answer always comes from your Java compliant JVM. This forum is good for "Why is the value...?" questions.

In short, I believe you have misunderstood "associativity" and "order of operation."

Try the following:

sayan nmn bhattacharya
Greenhorn
Posts: 2
Here is how it works

++ or -- operator takes more precedence over + operator
So
the sequence of operation would be like this
int i =10;
"++i + --i" piece will be
step 1
++i (so i becomes 11)
step 2
--i(so then i becomes 10)
11+10=21
Hope this helps

Sayan

satya mamillapalli
Ranch Hand
Posts: 63
I know the answer is 21. But WHy..

Do the Unary Prefix operators(++a,--a) associate from right to Left?

In the example ++,-- has higher precedence than '+'.

Then between ++,-- , they have right to left associativity..

Please let me know if I am missing any here?

Satya

Ranch Hand
Posts: 245
Prefix operators associate from right to left so in

a is first incremented, then decremented.

There is a binary + operator in

a that evaluates from left to rigth so ++i is done before --i.
[ August 19, 2005: Message edited by: Vlado Zajac ]

Arvind Giri
Ranch Hand
Posts: 91
dear satya,
there is a difference in associativity and evaluation order. Here the problem is related to evaluation order and not associativity.
every operand is evaluated from L to R;
so it would be
--> ++i + --i
--> 11 + --i
--> 11 + 10;
--> 21