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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP