aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt on  a sample question from sun Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt on  a sample question from sun" Watch "Doubt on  a sample question from sun" New topic
Author

Doubt on a sample question from sun

Archana Annamaneni
Ranch Hand

Joined: Jan 29, 2003
Posts: 147
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

Joined: Jan 22, 2003
Posts: 5
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


Regards
Nico
John Zoetebier
Ranch Hand

Joined: Mar 28, 2003
Posts: 76
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Doubt on a sample question from sun