++,–运算符的使用:
作用:就是对变量进行自增1或者自减1.
- 单独使用:放在操作数的前面或者后面,效果一样。(这种用法比较常见)
- 参与运算使用:
a:放在操作数的前面,先自增或者自减,然后再参与运算
b:放在操作数的后面,先参与运算,再自增或者自减
单独使用的案例:
public class OperatorDemo {
public static void main(String[] args) {
//定义两个变量
int x = 3;
int y = 4;
//System.out.println("x:"+x);
//System.out.println("y:"+y);
System.out.println("x:"+x+",y:"+y);
//单独使用
//x++;
//y++;
++x;
++y;
System.out.println("x:"+x+",y:"+y);
//意外的类型,常量是不可以这样做的
//System.out.println(10++);
}
}
运行结果:
x:3,y:4
x:4,y:5
而在参与运算的时候,示例代码如下:
public class OperatorDemo {
public static void main(String[] args) {
//定义两个变量
//参与运算使用
int a = 3;
int b = 4;
//int c = a++; //c = 3,a = 4
//int d = b--; //d = 4,b = 3
int c = ++a; //c = 4,a = 4;
int d = --b; //d = 3,b = 3;
System.out.println("a:"+a);//4 4
System.out.println("b:"+b);//3 3
System.out.println("c:"+c);//3 4
System.out.println("d:"+d);//4 3
}
}
注释内容即为运行结果。
案例分析:
/**
* @author 作者 :Xuzhonghua
* @date 创建时间:2019年7月22日 下午8:32:56
* @version 1.0
*/
public class OperatorTest {
public static void main(String[] args) {
int a = 10;
int b = 10;
int c = 10;
a = b++;//a:10 b:11 c:10
c = --a;//a:9 c:9 b:11
b = ++a;//a:10 b:10 c:9
a = c--;//a:9 c:8 b:10
System.out.println("a:" + a);
System.out.println("b:" + b);
System.out.println("c:" + c);
System.out.println("---------------");
int x = 4;
int y = (x++)+(++x)+(x*10);
//4+6+6*10
//x = 5,6
System.out.println("x:"+x);
System.out.println("y:"+y);
}
}
运行结果:
a:9
b:10
c:8
x:6
y:70
注释内容即为代码运行的过程。