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的面試題?


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM