java的自增和自减

 1 class Untitled {
 2     public static void main(String[] args) {
 3         int a = 3;
 4         int b = a++;   //a先赋值给b,然后a再自己加1
 5         System.out.println("a="+a);  //输出a=4
 6         System.out.println("b="+b);    //输出b=3
 7         
 8         System.out.println("
");
 9         
10         a = 3;
11         int c = ++a;   //a先加1,然后再赋值给c
12         System.out.println("a="+a);    //输出a=4
13         System.out.println("c="+c);    //输出c=4
14         
15         
16         System.out.println("
");
17         
18         
19         c++;
20         System.out.println(c);  //输出5
21         
22         ++c;
23         System.out.println(c);  //输出6
24     }
25 }

自减跟自增一样。

总结:

  如果只是a++;或者++a;这样不参与赋值操作,那结果都是一样,都是加1; 

  如果是有参与赋值运算,比如:int c = a++;或int c = ++a;那么c的值是有区别的。

  如果参与了赋值运算那么就要看赋值自增的运算符在变量的左边还是右边:

                          如果自增运算符在左边:++a;那么就是a先自增,再赋值给c;

                          如果自增运算符在右边:a++;那么就是a先赋值给c,再自增;

  (也可以有自己的记忆理解方法)

【水平有限,不对之处,还请指出】

内容
原文地址:https://www.cnblogs.com/eyjdbk/p/10962827.html