LoginSignup
1
0

More than 5 years have passed since last update.

演算子の前置き後置きの違い

Last updated at Posted at 2018-05-31

加算、減算演算子には前置きか後置きかの2種類あり、それぞれ動作が異なる。

  • 後置きの場合 何かしてから演算
b = a++;
// b = a;
// a = a + 1;
// と同じ
  • 前置きの場合 演算してから何かする
b = ++a;
// a = a + 1;
// b = a;
// と同じ

例えばprint( )の中で使った場合、

  • 後 :出力してから演算
  • 前 :演算してから出力

になる。

operator.java
public class operator{
   public static void main(String[], args){

      i = 5;
      countdown1(i); // 54321

      System.out.println();
      i = 5;
      countdown2(i); // 43210
   }


   void countdown1(int i){
      for(i > 0){
         System.out.print(i--); // 出力してから減算
         countdown1(i);
      }
   }


   void countdown2(int i){
      for(i > 0){
         System.out.print(--i); // 減算してから出力
         countdown2(i);
      }
   }
}
1
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0