Reputation: 176
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.
Upvotes: 5
Views: 542
Reputation: 3216
A For loop construct have three things Initialization
,Condition
and Increment/Decrements
these are not mandatory fields. Java will always execute the code and won't show an error because we not breaking any syntax rule.
In here for(i=0;;i++) System.out.println(i)
will still be executed and result into infinite loop because Condition are always treated as optional part so rest other two.
Therefore, we wont be able to reach code after System.out.println(i)
statement as we are stuck in an infinite loop.
Upvotes: 2
Reputation: 2279
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
Upvotes: 3
Reputation: 1876
After testing this in netbeans it goes like this:
While application is running: no output
When application is stopped: all the numbers are outputted in the console.
So it does work, look at references from other answers to know WHY it works.
Upvotes: 2
Reputation: 39457
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).
Upvotes: 2