File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

question( i++/++i )

 
Wei Lien Chun
Greenhorn
Posts: 5
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1258
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Swati Singhal
Ranch Hand
Posts: 31
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic