• Post Reply Bookmark Topic Watch Topic
  • New Topic

loops  RSS feed

 
Charlie Swanson
Ranch Hand
Posts: 213
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anyone explain why the "while" statement gives a compile time error but the "if" statement doesn't.
while(false) { x = 3;}
if(false) {x = 3; }
Also, in the below for one creates an error and the other does not. Can you explain why?
for (int i = 0; i < 0; i++) x = 3;
for (int i = 0; false; i++) x = 3; //this one gives an error
Thank you
 
shankar vembu
Ranch Hand
Posts: 309
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
java compiler will give u an error when a statement is unreachable.for if block its okay because its a conditional block.
shanks.
 
Samith Nambiar
Ranch Hand
Posts: 147
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi charlie
just to add to what shankar has said ..... the following code would not give a compilation error
do {
System.out.println("samith");
}while(false);
hope that helps
Samith.P.Nambiar
---------------------------------------------
the harder you try the luckier you get
---------------------------------------------
 
kriti sharma
Ranch Hand
Posts: 160
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi charlie,
both the ques have the same concept behind them.when u initialize a loop to a "false" the next statement in the loop would never be executed.hence u'll get the error of 'statement not reached'.but whenever u give a condition which may or maynot evaluate to a false, there is no error.u may say that logically
this for loop can be evaluated to a false at the first sight.for (int i = 0; i < 0; i++) x = 3;
but even then at compile time the compiler does not know whether it is true or not.hence only and only when u give the word "false" there would be error.definitely if the loop body is empty then there would be no problem
hope this helps.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!