LOLWTFasdasd asdad LOLWTFasdasd asdad - 1 year ago 48
Java Question

In Java, is a while(true) behaving equally as an endless for-loop?

Do the following loops behave the same in terms of speed & CPU usage:

Loop 1


Loop 2

for(int i = 0; i != -1 ; i++) {}

Are there any differences or is it basically the same code in 2 different expressions?

Answer Source

These two loops are not the same:

  • The first loop will never stop
  • The second loop will run for a long time, until i overflows, at which point the loop will exit.

Given that these two loops are not the same, the byte code, CPU usage, and speed for each would be different as well.