• 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

Do-while loop?

 
Ranch Hand
Posts: 509
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Source: K&B Book.

1. public class Test {
2. public static void main(String [] args) {
3. int I = 1;
4. do while ( I < 1 )
5. System.out.print("I is " + I);
6. while ( I > 1 ) ;
7. }
8. }

The answer is no output is produce.
But isnt there a compilation error???
 
Sheriff
Posts: 22783
131
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

I've added better indentation (which was left out on purpose in the book) so you can see the real flow.

The trick is, this is a while loop inside a do-while loop, which is perfectly fine.

Now as to why there is no output.
The inner loop itself is executed at least one. However, it's guard yields false immediately, so its body (the print) is not executed. Next the outer loop's guard is evaluated, and it too is false, thereby ending this loop too.
 
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
That's what I thought because there is no semicolon after the first while() but I tried it and it compiled and ran very boringly.

That is peculiar since the do-while there doesn't appear to fit into the form in the JLS.

Anybody else got any ideas?
 
Campbell Ritchie
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes, Rob is right.
 
Abhi vijay
Ranch Hand
Posts: 509
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks,Rob.
 
reply
    Bookmark Topic Watch Topic
  • New Topic