• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt on a sample question from sun

 
Archana Annamaneni
Ranch Hand
Posts: 147
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
Given:
10. int i=3, j=0, result=1;
11. result += i-- * --j ;
12. System.out.println( result );
What is the result?

A 0
B -1
C -2
D -3
E Compilation fails
F An exception is thrown at runtime

The answer is C , I thought it is D.
The explanation says
Option C is the correct answer. Resolves to (i * (j-1) ) + 1
I thought it resolves to ((i-1)*(j-1))+1
My doubt is how i-- become i , when we are not assigning to any variable I thought there is no difference in post decrement or pre decrement
I will appreciate any help in clearing my doubt
 
Nico Schlebusch
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Archana,
The pre-decrement operator is executed before the rest of the expression is calculated. But the post-decrement operator is executed after the result of the expression is calculated. In other words the variable j's value would be decremented before it takes part in the calculation for result. The variable i's value is decremented after taking part in the calculation for result.
Hope it helps!
Nico
 
John Zoetebier
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This little program shows what happens:

Please have a look at Operator precedence thread about operator precedence.
There is a program that shows how precedence is handled.
Once you understand this program operator precedence is peace of a cake.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic