This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes question( i++/++i ) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "question( i++/++i )" Watch "question( i++/++i )" New topic
Author

question( i++/++i )

Wei Lien Chun
Greenhorn

Joined: Mar 18, 2004
Posts: 5
What is the result of attempting to compile and run the above program?
class F {
public static void main (String []s) {
int i = 1;
i += ~i - -i * ++i + i-- % ++i * i++;
System.out.print(i);
}
}

Ans Prints: 1
Why?
Thanks!
[ March 22, 2004: Message edited by: Wei Lien Chun ]
[ March 23, 2004: Message edited by: Wei Lien Chun ]
Nathaniel Stoddard
Ranch Hand

Joined: May 29, 2003
Posts: 1258
Wow. Um, I'm not going to attempt to take you through the whole thing, but rest assured that it all has to do with the evaluation order, and order of preference.
Basically, all those suckers are evaluated from left to right. Both operands are evaluted before the binary operation is invoked, and repeat.
Unless there's something specific in that braincruncher that you don't understand, I'm going to feel just fine leaving my answer as is.
P.S. Language Spec section of interest


Nathaniel Stodard<br />SCJP, SCJD, SCWCD, SCBCD, SCDJWS, ICAD, ICSD, ICED
Swati Singhal
Ranch Hand

Joined: Dec 08, 2003
Posts: 31
The answer indeed is 1.
This is because, the precedence rules are followed. The precedence goes as follows:
Pre/Post increment operators
Unary Operator
Multiplicative/Modulo operator
Arithmetic operator
If you evaluate the expression, by first evaluating the pre/post increment operators, then using the value of i after that and applying unary operator, then multiplicative/modulo and arithmetic operator, you will get the answer as 1.
Jason chen
Greenhorn

Joined: Mar 23, 2004
Posts: 1
Hi! I think:
i += ~i - -i * ++i + i-- % ++i * i++;
A- += is changed to implicit cast and i + the right hand side:
i = (int) (i + ~i - -i * ++i + i-- % ++i * i++);
B- Precedence is made:
i = (int) (i + ~i - (-i * ++i) + (i-- % ++i * i++));
C- Evaluation of operands: (not sure if this happens before precedence or after)
i = (int) (1 + -2 - (-1 * 2) + (2 % 2 * 2));
D- Calculations:
i = (int) (1 + -2 - (-2) + (0 * 2));
E- More calculations:
i = (int) (1 + -2 - -2 + 0);
then i is assigned the result which is 1
 
 
subject: question( i++/++i )
 
Similar Threads
cast null to interface and class
Taiwanese Eelection 2004
NX:my design,any opinion is appreciated
passed scea, but no certification
Garbage Collection