java内x++与++x的区别
理解x++和++x的区别
x++
x++是先取值后自增。
代码及结果
例如:
public class test {
public static void main(String[] args) {
int x=1;
int y = x++;
System.out.println(x);
System.out.println(y);
}
}
此时x的值为2,y的值为1。
解释
int x=1;// x=1
int y = x++;//先y=x=1,再x++=2(即x=x+1=2),所以x=2;y=1
++x
++x是先自增后取值。
代码及结果
例如:
public class test {
public static void main(String[] args) {
int x=1;
int y = ++x;
System.out.println(x);
System.out.println(y);
}
}
此时x的值为2,y的值为2。
解释
int x=1;// x=1
int y = ++x;//先x++=2(即x=x+1=2),再y=x=2,所以x=2;y=2
进阶
++x + ++x
先计算左边的++x,再计算右边的++x,最后加起来就是值
代码及结果
例如:
public class test {
public static void main(String[] args) {
int x=1;
int y=++x + ++x;
System.out.println(x);
System.out.println(y);
}
}
此时x的值为3,y的值为5。
解释
int x=1;// x=1
int y = ++x + ++x;
//注:++x和++x的运算见最上方【理解x++和++x的区别】
//第一步先运算左边++x,此时先x=x+1=2,再++x=2
//第二步运算右边的++x,此时先x=x+1=3,再++x=3
//第三步运算(++x) + (++x),此时x=3,++x + ++x=2+3=5
//所以x的值为3,y的值为5。
x++ + ++x
先计算左边的x++,再计算右边的++x,最后加起来就是值
代码及结果
例如:
public class test {
public static void main(String[] args) {
int x=1;
int y=x++ + ++x;
System.out.println(x);
System.out.println(y);
}
}
此时x的值为3,y的值为4。
解释
int x=1;// x=1
int y = x++ + ++x;
//注:x++和++x的运算见最上方【理解x++和++x的区别】
//第一步先运算左边x++,此时先x++=1,再x=x+1=2
//第二步运算右边的++x,此时先x=x+1=3,再++x=3
//第三步运算(x++) + (++x),此时x=3,x++ + ++x=1+3=4
//所以x的值为3,y的值为4。
x++ + x++
先计算左边的x++,再计算右边的x++,最后加起来就是值
代码及结果
例如:
public class test {
public static void main(String[] args) {
int x=1;
int y=x++ + x++;
System.out.println(x);
System.out.println(y);
}
}
此时x的值为3,y的值为3。
解释
int x=1;// x=1
int y = x++ + x++;
//注:x++和x++的运算见最上方【理解x++和++x的区别】
//第一步先运算左边x++,此时先x++=1,x=x+1=2
//第二步运算右边的x++,此时x++=2,x=x+1=3
//第三步运算(x++) + (x++),此时x=3,x++ + x++=1+2=3
//所以x的值为3,y的值为3。
++x + x++
先计算左边的++x,再计算右边的x++,最后加起来就是值
代码及结果
例如:
public class test {
public static void main(String[] args) {
int x=1;
int y=++x + x++;
System.out.println(x);
System.out.println(y);
}
}
此时x的值为3,y的值为4。
解释
int x=1;// x=1
int y = ++x + x++;
//注:++x和x++的运算见最上方【理解x++和++x的区别】
//第一步先运算左边++x,此时先x=x+1=2,++x=2
//第二步运算右边的x++,此时x++=2,x=x+1=3
//第三步运算(++x) + (x++),此时x=3,++x + x++=2+2=4
//所以x的值为3,y的值为4。