File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Simple looking but tough Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Simple looking but tough" Watch "Simple looking but tough" New topic
Author

Simple looking but tough

Shailendra Guggali
Ranch Hand

Joined: Feb 01, 2001
Posts: 86
look at the foll code :
public class TestClass
{
public static void main (String args[ ] )
{
int k = 1;
int i = ++k + k++ + + k ;
System.out.print(i+ " "+ k) ;
}
}
what is the result??
i thought ++k makes it 2 then k++ keeps it at 2 and +k doesn't change its value( just makes it positive). so the result should be 2+2+2 = 6
i = 6; k = 2
But it is wrong!!!
Udayan Naik
Ranch Hand

Joined: Oct 18, 2000
Posts: 135
Hi Shailendra.The answer will be 7,not 6.If we go over it...
1)Initially k=1;
2)++k will make k=2 since we are using a prefix operator.(as said by you).So currently the value of the expression is 2.
3)Now since there is a postfix operator in k++,the SAME VALUE of k will be used at that point in evaluating the expression.Thus now value is 2+2;
4)NOW k WILL BE INCREMENTED,because of the postfix operator.Thus now k=3;
5)Now to this expression,we are adding +k.Hence now we have value of expression as 2+2+3=7.This is assigned to i,hence i=7;
Remember,at every point the CURRENT VALUE of the variable will be used when evaluating the expression.
I hope i have been clear enough.


Udayan Naik<BR>Sun Certified Programmer for the Java 2 Platform
Shailendra Guggali
Ranch Hand

Joined: Feb 01, 2001
Posts: 86
Thanx uday
 
jQuery in Action, 2nd edition
 
subject: Simple looking but tough
 
Similar Threads
Ambiguous Reference to method
A static class ?
deal with loops.....
Alone I do not obtain.....
Operator mock exam question