Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Can you explain this ?

Karthik Gurunathan
Greenhorn
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
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

Vicken Karaoghlanian
Ranch Hand
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

Vicken Karaoghlanian
Ranch Hand
Posts: 522
Corey-
You beat me on this one, well explained though.

Karthik Gurunathan
Greenhorn
Posts: 19
Thank you all..I got the point...