| 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...
|
 |
 |
|
|
subject: Can you explain this ?
|
|
|