Java 中的增量和減量運算子有哪些限制?


增量運算子將運算元的值增加 1,減量運算子將運算元的值減少 1。我們使用這些運算子在對值執行語句後遞增或遞減迴圈的值。

示例

 線上演示

public class ForLoopExample {
   public static void main(String args[]) {
      //Printing the numbers 1 to 10
      for(int i = 1; i<=10; i++) {
         System.out.print(" "+i);
      }
      System.out.println(" ");
      //Printing the numbers 10 to 1
      for(int i = 10; i>=1; i--) {
         System.out.print(" "+i);
      }
   }
}

輸出

1 2 3 4 5 6 7 8 9 10
10 9 8 7 6 5 4 3 2 1

增量和減量運算子的限制

  • 不能將增量和減量運算子與常量一起使用,否則會產生編譯時錯誤。

示例

public class ForLoopExample {
   public static void main(String args[]) {
      int num = 20;
      System.out.println(num++);
      System.out.println(20--);
   }
}

輸出

ForLoopExample.java:5: error: unexpected type
      System.out.println(20--);
                        ^
   required: variable
   found: value
1 error
  • 在 Java 中不能巢狀兩個增量或減量運算子,否則會產生編譯時錯誤:

示例

public class ForLoopExample {
   public static void main(String args[]) {
      int num = 20;
      System.out.println(--(num++));
   }
}

輸出

ForLoopExample.java:4: error: unexpected type
      System.out.println(--(num++));
                               ^
required: variable
found: value
1 error
  • 宣告為 final 的變數,其值不能被修改。由於增量或減量運算子會更改運算元的值,因此不允許將這些運算子與 final 變數一起使用。

示例

public class ForLoopExample {
   public static void main(String args[]) {
      final int num = 20;
      System.out.println(num++);
   }
}

輸出

ForLoopExample.java:4: error: cannot assign a value to final variable num
   System.out.println(num++);
                      ^
1 error
  • 不允許將增量和減量運算子與布林變數一起使用。如果仍然嘗試遞增或遞減布林值,則會產生編譯時錯誤。

示例

public class ForLoopExample {
   public static void main(String args[]) {
      boolean bool = true;
      System.out.println(bool++);
   }
}

輸出

ForLoopExample.java:4: error: bad operand type boolean for unary operator '++'
      System.out.println(bool++);
                            ^
1 error

更新於:2019年7月30日

1K+ 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.