Get your CodeRanch badge!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes loop Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "loop" Watch "loop" New topic
Author

loop

mohamed hamdy
Ranch Hand

Joined: Feb 13, 2003
Posts: 72
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?
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
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


SCJP Tipline, etc.
param kiran
Greenhorn

Joined: May 02, 2003
Posts: 3
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.
mohamed hamdy
Ranch Hand

Joined: Feb 13, 2003
Posts: 72
thanks Corey , thanks Param
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: loop
 
Similar Threads
Khalid's Mock Test.
For loop
Labeeled Problem
Error while Running Code
loops & labels