i++和++i的作用和区别

作用:都是给变量 i 加 1,相当于 i = i + 1; 

区别:

  • i++ 先运算后家 1
  • ++i 先加 1 再运算
package constxiong.interview;

/**
 * 测试 ++i 和 i++
 * @author ConstXiong
 * @date 2019-10-17 13:44:05
 */
public class TestAdd {

    public static void main(String[] args) {
        int a = 3;
        int b = a++;
        System.out.println("a=" + a);
        System.out.println("b=" + b);
        
        int x = 3;
        int y = ++x;
        System.out.println("x=" + x);
        System.out.println("y=" + y);
    }
    
}

打印

a=4
b=3
x=4
y=4



  

来一道刷了进BAT的面试题?

原文地址:https://www.cnblogs.com/ConstXiong/p/11839548.html