Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop blank condition

Tags:

java

The condition in the for loop is left blank and the code compiles and runs.

 for(int i=0; ; i++)
    System.out.print(i);  //this code does not execute
 //code after this does not execute

But, I don't understand how and why this is possible.

like image 254
Mladen P Avatar asked Apr 12 '14 10:04

Mladen P


2 Answers

Just change below line, although its not an issue.

System.out.print(i);  //this code does not seems execute by checking o/p on console but in reals it works as well.

To

System.out.println(i);  //this code works and you will be able to see o/p on console.

OR

System.out.print(i+" "); // this will show you some momentary action on Eclipse console.

It seems to me as some Eclipse IDE console printing issue. With the first version as you mentioned in your question, I can't see any output. As print() keeps on printing on the same line may be its not visible to us.

However, if you run your code in Debug mode and place a breakpoint on the above line. Breakpoint will hit and you can see the output being printed as well.

But for the second version, I can see it printing all number starting from 0,1...

This is a similar discussion as shared by @PakkuDon

like image 198
sakura Avatar answered Oct 10 '22 14:10

sakura


If it prints nothing, it means you're not reaching this for loop at all.
If you're reaching it, it should print all numbers from 0 going up.
This is an endless loop printing 0, 1, 2, ...
Your problem is elsewhere (probably before the for loop).

like image 39
peter.petrov Avatar answered Oct 10 '22 14:10

peter.petrov