关于 i++ 和 ++ i

先看一下代码,猜想一下输出值

@Test
public void test() {
int i =1;
int a,b=0;
i++;
a=(i++);
System.out.println(a);
System.out.println(i);
System.out.println(b++);
System.out.println(++b);

for(int k=0;k<5;k++){
System.out.println(k);
}
for(int s=0;s<5;++s){
System.out.println(s);
}
}

下面我加一下注释,最后再贴一下输出结果
@Test
public void test() {
int i =1;//定义变量i ,只有初始化后才能进行 ++操作,否则会编译错误
int a,b=0; //定义a 和 b ,a 不做初始化
i++; //i自行执行+1
a=(i++);//i赋值给a , 这个地方与上个地方是有区别的,a得到的赋值是在 ++ 之前的,并不因为加了括号就先执行+1后执行赋值
System.out.println(a);
System.out.println(i);
System.out.println(b++);
System.out.println(++b);

for(int k=0;k<5;k++){
System.out.println(k);
}
for(int s=0;s<5;++s){
System.out.println(s);
}
}

结果,你算对了吗

1
2
0
2
0
1
2
3
4
0
1
2
3
4

Process finished with exit code 0

猜你喜欢

转载自www.cnblogs.com/shej123/p/12028733.html