what will be the output when compiling and running this code?
the answer is "fail to compile", it made sense for me since the condition in the for loop will be false from the begining and that makes the block of the for loop unreachable, but when i compiled and run the code it gives "o" as output. can somone emphaisis that?
Joined: Dec 20, 2001
Even though we know that i will be greater than 0 at the start of the loop and, hence, the loop will never execute, the compiler doesn't know that. It sees a conditional test on a variable and thinks "hmmm...it could pass, so I'll let it be." Therefore, you do not get an "unreachable statement" error when compiling this. If you change the loop to this:
You will get an "unreachable statement" error when you try to compile. In this case, the compiler knows that the loop can never execute and issues an error message to you. I hope that helps, Corey
In the "for (int i=10; i<0; i++)" statement, the condition i<0 is false so the for loop is never executed. The System.out.println(counter); statement is outside of the for loop if you observe closely. Since the counter is initialized to 0 the print statement prints this out.