Home > Java > javaTutorial > How to use increment and decrement operators in Java

How to use increment and decrement operators in Java

王林
Release: 2023-04-21 09:52:07
forward
1445 people have browsed it

1. n adds 1 to the current value of variable n, n--decreases the value of variable n by 1.

2. These operators change the value of the variable and cannot be applied to the value itself.

3. In the expression, n means to increment first and then assign a value; n means to assign a value first and then increment.

Example

//与打印操作混合使用
int num2 = 20;
//混合使用,先++,变量立刻马上变成21,然后打印结果21
System.out.println(++num2);//21
System.out.println(num2);//21
System.out.println("===========");
int num3=30;
//混合使用,后++,首先使用变量本来的30,然后让变量+1得到31
System.out.println(num3++);//30
System.out.println(num3);//31
System.out.println("============");
int num4 =40;
//和赋值操作混合
int result1 = --num4;//混合使用,前--,变量立刻马上-1变成39,然后将结果39交给result1变量
System.out.println(result1);//39
System.out.println(num4);//39
System.out.println("============");
int num5 =50;
//混合使用,后--,首先把本来的数字50交给result2,然后我自己再-1变成49
int result2 = num5--;
System.out.println(result2); //50
System.out.println(num5);  //49
System.out.println("=============");
int x = 10;
int y = 20;
//11+20=31
int result3 = ++x + y--;
System.out.println(result3); //31
System.out.println(x);  //11
System.out.println(y);  //19
//30++;//错误写法! 常量不可以使用++或者--
}
Copy after login

The above is the detailed content of How to use increment and decrement operators in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template