• 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

while loop

 
Ranch Hand
Posts: 333
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Consider the following program:
class Char //1
{ //2
public static void main(String[] args) //3
{//4
while(false)//5
{ //6
System.out.println("Hello");//7
} //8
while(false) //9
{ //10
}
do;
while(false);
do
{
;
}
while(false);
}
}

When I tried to compile it, I got:
Char.java:6: unreachable statement
{
^
Char.java:10: unreachable statement
{
^
I can't understand why lines 6, 10 are unreachable. Plz explain.
Isn't the while loop altogether skipped considering that the while condition evaluates to false?
 
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It's because your program is explicitly indicating the compiler that it's passing 'false' to the while loop's condition, and therefore it'll never be entering the loop. It is therefore throwing the 'unreachable code' error.

If you pass a variable that has a 'false' value assigned to it, then your program should be ok. let's modify your example to do this:

class Char //1
{ //2
public static void main(String[] args) //3
{//4
boolean flag = false;
while(flag)//5
{ //6
System.out.println("Hello");//7
} //8
while(flag) //9
{ //10
}
do;
while(false);
do
{
;
}
while(false);
}
}

Cheers

Parimal
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic