java异常循环知道没有异常,JAVA:为什么以下无限循环终止而没有任何错误/异常...

I was messing around with stuff in my eclipse when, to my surprise, I found that this piece of code when run gets terminated without any error / exception

public class Test {

public static void main(String[] args) {

for(int i = 2; i > 0; i++){

int c = 0;

}

}

}

while his piece of code keeps on executing

public class Test {

public static void main(String[] args) {

for(int i = 2; i > 0; i++){

int c = 0;

System.out.println(c);

}

}

}

Even though both ought to be infinite loops running for ever. Is there something I'm missing as to why the first code snippet is terminated?

解决方案

First of all, both snippets are not infinite loops, since i will become negative once it passes Integer.MAX_VALUE. They just take a long time to run.

The first snippet takes much less time to run, since it doesn't have to print anything, and it's possible the compiler is smart enough to just optimize the code and eliminate the loop, since it does nothing.

Testing your first snippet, adding System.out.println (System.currentTimeMillis ()); before and after the loop, I got :

1486539220248

1486539221124

i.e. it ran in less than 1 second.

Changing the loop slightly :

System.out.println (System.currentTimeMillis ());

for(int i = 2; i > 0; i++){

int c = 0;

if (i==Integer.MAX_VALUE)

System.out.println (i);

}

System.out.println (System.currentTimeMillis ());

I got

1486539319309

2147483647

1486539319344

As you can see, it takes i less than 1 second to increment from 0 to Integer.MAX_VALUE, and then overflow, at which point the loop terminates.

The more prints you add to the loop, the more time it will take to terminate. For example :

System.out.println (System.currentTimeMillis ());

for(int i = 2; i > 0; i++){

int c = 0;

if (i % 100000000 == 0)

System.out.println (i);

}

System.out.println (System.currentTimeMillis ());

Output :

1486539560318

100000000

200000000

300000000

400000000

500000000

600000000

700000000

800000000

900000000

1000000000

1100000000

1200000000

1300000000

1400000000

1500000000

1600000000

1700000000

1800000000

1900000000

2000000000

2100000000

1486539563232

Now it took 3 seconds.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值