public static void main(String[] args) {
int a = 1;
int b = a++;
System.out.println(b);
}
上記のコードで 1 が出力されるのはなぜですか? a++ は a の値を取得することを意味すると言われました。その後、それを増やします。しかし、上記のコードは a をインクリメントせず、1 を出力しただけです。ここで何が起こっているのか説明してもらえますか?
public static void main(String[] args) {
int a = 1;
int b = a++;
System.out.println(b);
}
上記のコードで 1 が出力されるのはなぜですか? a++ は a の値を取得することを意味すると言われました。その後、それを増やします。しかし、上記のコードは a をインクリメントせず、1 を出力しただけです。ここで何が起こっているのか説明してもらえますか?
期待どおりに動作します。説明したコードは次のとおりです。
public static void main(String[] args) {
// a is assigned the value 1
int a = 1;
// b is assigned the value of a (1) and THEN a is incremented.
// b is now 1 and a is 2.
int b = a++;
System.out.println(b);
// if you had printed a here it would have been 2
}
これは同じコードですが、次のプリインクリメントがあります。
public static void main(String[] args) {
// a is assigned the value 1
int a = 1;
// a is incremented (now 2) and THEN b is assigned the value of a (2)
// b is now 2 and so is a.
int b = ++a;
System.out.println(b);
// if you had printed a here it would have been 2 so is b.
}
Post Increment 意味 = 最初に割り当てを完了し、次にインクリメントします。プリインクリメント 意味 = 最初にインクリメントしてから割り当てる。
元:
int a=0,b;
b=a++; // ie. Step1(First complete assignment): b=0, then a++ ie a=a+1; so a=1 now.
System.out.println(b); // prints 0
System.out.println(a); // prints 1
もしも
int a=0,b;
b=++a; // ie. Step1(First Increment ): a++ ie a=a+1; so a=1 now, b=a , ie b=1.
System.out.println(b); // prints 1
System.out.println(a); // prints 1
int b = a++
と同等int b = a; a += 1
です。印刷するb
と、a==2 && b==1
a++
a
-then increment a
by 1と言っb = a++
て いるようなものです。b = 1
a = 2
preincrement を使用b = ++a
すると、b = 2
値が割り当てられる前に Preincrement が増加します。
結論
a++ 値をインクリメントする前に
++a をインクリメントしてから、値を割り当てます。
The reason is is as follow.
If it is i++, then equalent code is like this.
result = i;
i = i+1;
return result
If it is ++i. then the equlent code is like this.
i=i+1;
result =i;
return i
So considering your case, even though the value of i is incremented, the returned value is old value. (Post increment)