• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Doubt on a sample question from sun

 
Ranch Hand
Posts: 147
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic