This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can you explain this ?

 
Karthik Gurunathan
Greenhorn
Posts: 19
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3271
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Vicken Karaoghlanian
Ranch Hand
Posts: 522
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Vicken Karaoghlanian
Ranch Hand
Posts: 522
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Corey-
You beat me on this one, well explained though.
 
Karthik Gurunathan
Greenhorn
Posts: 19
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you all..I got the point...
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic