my dog learned polymorphism*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Can you explain this ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Can you explain this ?" Watch "Can you explain this ?" New topic
Author

Can you explain this ?

Karthik Gurunathan
Greenhorn

Joined: Jan 26, 2004
Posts: 19
class test {
public static void main(String args[]) { //line1
int i,j,k,l=0; //line2
k = l++; //line3
j = ++k; //line4
i = j++; //line5
System.out.println(i);
}
}
In the above program how come the result of i=1 ...can somene please explain to me . What really happens...in lines 3,4,5.
Thanks
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
Ok, let's go through this line by line.

l originally equals 0 and we are doing a post-increment. Therefore, we assign the original value of l, 0, to k and then increment l to be 1.

k is now 0 and we are performing a pre-increment on it. Therefore, we add 1 to k, making it 1, and then assign that value to j.

j is 1 and we are doing a post-increment on it. Therefore, we assign the original value of j, 1, to i and then add 1 to j, making it 2.

Finally, we spit out the value of i, which we just saw was 1.
I hope that helps,
Corey


SCJP Tipline, etc.
Vicken Karaoghlanian
Ranch Hand

Joined: Jul 21, 2003
Posts: 522
line 2 : All variables are initialized to 0
line 3 : 'l' is incremented by one, but it returns its old value which is 0 and assigns it to 'k'.
line 4 : 'k' is incremented by one, and return its new value which is 1 and it is assigned to 'j'
line 5 : 'j' is incremented by one thus becoming 2, but it returns its old value which is 1.
The values for each variable after each line is finished executing are:
line 2 : k=0, l=1
line 3 : j=1, k=1
line 4 : i=1, j=2


- Do not try and bend the spoon. That's impossible. Instead, only try to realize the truth. <br />- What truth? <br />- That there is no spoon!!!
Vicken Karaoghlanian
Ranch Hand

Joined: Jul 21, 2003
Posts: 522
Corey-
You beat me on this one, well explained though.
Karthik Gurunathan
Greenhorn

Joined: Jan 26, 2004
Posts: 19
Thank you all..I got the point...
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Can you explain this ?
 
Similar Threads
Question on constructors
Need Help for word game
Assignment operator
Increment Test
doubt about boxing conversions