Java基础知识(一) 自增、自减运算符
自增运算符++,将数值增加1;自减运算符--,将数值减少1
| 运算符 | 代码片段 | 区别 |
| ++ | x = 2 * m ++; | 先运行 x = 2 * m; 再运行 m = m + 1; |
| ++ | x = 2 * ++m | 先运行 m = m + 1; 再运行 x = 2 * m; |
| -- | y = 2 * m-- | 先运行 y = 2 * m; 再运行 m = m - 1; |
| -- | y = 2 * --m | 先运行 m = m - 1; 再运行 y = 2 * m; |
自增代码:
package com.scd.chapter1;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int m = 7;
int n = 7;
int x = 2 * m++;
int y = 2 * ++n;
System.out.println("m="+m);
System.out.println("n="+n);
System.out.println("x="+x);
System.out.println("y="+y);
}
}
输出结果:
m=8 n=8 x=14 y=16
自减代码:
package com.scd.chapter1;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int m = 7;
int n = 7;
int x = 2 * m--;
int y = 2 * --n;
System.out.println("m="+m);
System.out.println("n="+n);
System.out.println("x="+x);
System.out.println("y="+y);
}
}
输出结果:
m=6 n=6 x=14 y=12

浙公网安备 33010602011771号