increment - Java Incremental operator query (++i and i++) -
this question has answer here:
i have following code:
public class book { private static int sample1(int i) { return i++; } private static int sample2(int j) { return ++j; } public static void main(string[] arguments){ int = 0; int j = 0; system.out.println(sample1(i++)); //0 system.out.println(sample1(++i)); //1 system.out.println(sample2(j++));//1 system.out.println(sample2(++j));//2 system.out.println(i);//2 system.out.println(j);//2 } }
my expected output in comments. actual output below:
0 2 1 3 2 2
i'm getting confused function calls , incemental operator. can kindly explain actual result?
first of need know difference between x++
, ++x
;
in case of x++
:
first current value used , incremented next. means present value of x
operation , if use x next time incremented value;
in case of ++x
:
first current value incremented , used (the incremented value) next, means incremented value @ operation , other after operation.
now lets split code , discuss them separately
method: sample1() :
private static int sample1(int i) { return i++; }
this method take int , return first , try increment after returning variable i
go out of scope never incremented @ all. exp in: 10-> out 10
method: sample2() :
private static int sample2(int j) { return ++j; }
this method take int , increment first , return it. exp in: 10-> out 11
in both case variables change locally, means if call main method variables of main method remain unaffected change (as sample1() , sample2() making copy of variables)
now code of main method
system.out.println(sample1(i++)); // it's giving sample1() `i=0` making `i=1` // sample1() return 0 too; system.out.println(sample1(++i)); // it's making `i=2` , giving sample1() `i=2` // sample1() return 2; system.out.println(sample2(j++)); // it's giving sample2() `j=0` making `j=1` // sample2() return 1; system.out.println(sample2(++j)); // it's making `j=2` giving sample2() `j=2` // sample2() return 3;
Comments
Post a Comment