• 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
  • Liutauras Vilda
  • Tim Cooke
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Devaka Cooray
  • Ron McLeod
  • paul wheaton
Saloon Keepers:
  • Tim Moores
  • Piet Souris
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Frits Walraven
  • Scott Selikoff

doubt in labeld loops?

 
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi friends
look at this labeled loops:
------------------------------------------
outer:
for(int i=0;i<10;i++){
System.out.println("i"+i);
break outer;
System.out.println("i"+i);
}
ok unreachable code error
----------------------------
outer:
for(int i=0;i<10;i++){
System.out.println("i"+i);
while(true){
break outer;
}
System.out.println("i"+i);
}
again unreachalble code error
ok looking meaningfull
---------------------------------
outer:
for(int i=0;i<10;i++){
System.out.println("i"+i);
if(true){
break outer;
}
System.out.println("i"+i);
}
no error
but it is looking same as previous one. why this?
is there any more to know? if so please help me
regards
Mallik Avula
 
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Unlike the while() loop condition, the if() condition is not evaluated/optimized at compile time, so you don't get an "unreacheable code" error even if you use if(false) {...}

I think the Java team did this to allow programmers to use if() tests even with compile-time constants, to debug their code :

This code does compile even if you turn "debug" to false.

Back to your code :
In the second code sample, when the compiler sees "while(true)", it knows that the enclosed code will always be executed, that is, you will always get out of the loop before reaching the last line. That is why you get an Unreacheable Code exception.
In the third code sample, the compiler does not evaluate the if() condition, so does not know that the last line won't ever be reached. So, no compile-time error.
[ July 04, 2007: Message edited by: Olivier Croisier ]
 
The harder I work, the luckier I get. -Sam Goldwyn So tiny. - this ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic