JAVA【i++和++i】

总结:

i++或++就是一个先加和后加的问题,当i++或++i是独立执行的时候没有区别,

当i++或++i不是是独立执行的时候:i++ 先执行当前语句再加1,++i先加1再执行当前语句。

 

示例1:独立执行没区别

 1 public static void main(String[] var0) {
 2         int i = 0;
 3         for (; i < 5; i++) {
 4             System.out.println(i);//打印0-4
 5         }
 6 
 7         int j = 0;
 8         for (; j < 5; ++j) {
 9             System.out.println(j);//打印0-4
10  } 11 }

 

示例2:i++ 先执行当前语句再加1,++i先加1再执行当前语句

 1     public static void main(String[] var0) {
 2         int i = 0;
 3         for (; i < 5;) {
 4             System.out.println(i++);//输出0-4
 5         }
 6 
 7         int j = 0;
 8         for (; j < 5; ) {
 9             System.out.println(++j);//输出1-5
10         }
11     }

 

示例3:

 1     private static Test test = new Test();//打印1,0
 2     static int i;
 3     static int j=0;
 4 //    private static Test test = new Test();//打印1,1
 5     public Test() {
 6         i++;
 7         j++;
 8     }
 9 
10     public static Test getInstance() {
11         return test;
12     }
13 
14     public static void main(String[] args) {
15         Test.getInstance();
16         System.out.println("i=" + Test.i + ",j=" + Test.j);
17     }

 

示例4:

1  int a = 0;
2         for (int i = 0; i < 99; i++) {
3             a = a ++;
4         }
5         System.out.println(a);//0,循环中a的值没有改变过

 

 

 

示例5:

1 int b = 0;
2         for (int i = 0; i < 99; i++) {
3             b = ++ b;
4         }
5         System.out.println(b);//99,循环中值一直变化,i=4,b=5;

 

 

 

示例6:

1 Integer a = 0;
2         int b = 0;
3         for (int i = 0; i < 99; i++) {
4             a = a ++;//a没有变化
5             b = a ++;//a+1,b+1;
6         }
7         System.out.println(a);//i=0,a=1,b=0;i=1,a=2,b=1;
8         System.out.println(b);//打印99,98

posted @ 2020-01-07 14:34  fangyanr  阅读(1123)  评论(0编辑  收藏  举报