• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

loop

 
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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?
 
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 72
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanks Corey , thanks Param
 
reply
    Bookmark Topic Watch Topic
  • New Topic