增量运算符 用于将值递增1。增量运算符有两种:
null
- 增薪后: 值首先用于计算结果,然后递增。
- 增量前: 值先递增,然后计算结果。
减量运算符 用于将值递减1。减量运算符有两种。
- 减量后: 值首先用于计算结果,然后递减。
- 预减量: 值先递减,然后计算结果。
现在让我们做一些关于递增和递减运算符的有趣的事情:
- 只能应用于变量
- 不允许两个操作员嵌套
- 它们不会在最终变量上运行
- 递增和递减运算符不能应用于布尔值。
让我们讨论上述4个事实,并按如下方式实施:
事实1: 只能应用于变量
我们只能对变量应用++和-运算符,但不能对常量值应用++和-运算符。如果我们试图对常量值应用++和-运算符,那么我们将得到一个编译时错误,我们将在下面的示例后的示例1B中看到,如下所示:
例1:
JAVA
// Java program to illustrate Increment // and Decrement Operators // Can be Applied to Variables Only // Main class public class GFG { // main driver method public static void main(String[] args) { int a = 10 ; int b = ++a; // Printing value inside variable System.out.println(b); } } |
输出
11
例2:
JAVA
// Java program to Illustrate Increment and Decrement // operators Can be applied to variables only // Main class public class GFG { // main driver method public static void main(String[] args) { // Declaring and initializing variable int a = 10 ; int b = ++a; // This is change made in above program // which reflects error during compilation b = 10 ++; // Printing its value System.out.println(b); } } |
输出:
事实2: 不允许同时嵌套++和-运算符
实例
JAVA
// Java program to Illustrate Nesting Can Not be Applied // to Increment and Decrement Operators // Main class public class GFG { // Main driver method public static void main(String[] args) { int a = 10 ; int b = ++(++a); // Printing the value inside variable System.out.println(b); } } |
输出:
事实3: 最终变量 无法应用递增和递减运算符
增量和减量运算符不能应用于最终变量,原因很简单,它们的值不能更改。
实例
JAVA
// Java Program to Illustrate Increment and Decrement // Operators Can not be applied to final variables // Main class public class GFG { // MAin driver method public static void main(String[] args) { // Declaring and initializing final variable final int a = 10 ; int b = ++a; // Trying to print the updated value inside variable System.out.println(b); } } |
输出:
事实4: 递增和递减运算符不能应用于布尔值
我们可以将++和-运算符应用于所有 基本数据类型 除了布尔类型,因为它只有true和false,这听起来甚至不切实际。
实例
JAVA
// Java program to Illustrate Increment and Decrement // Operators Can not be applied boolean data type // Main class public class GFG { // Main driver method public static void main(String[] args) { // Initially declaring boolean as false boolean b = false ; b++; // Trying printing the bool value System.out.println(b); } } |
输出:
本文由 比沙尔·库马尔·杜比 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END