File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes While Loop Mystery... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "While Loop Mystery..." Watch "While Loop Mystery..." New topic
Author

While Loop Mystery...

Shah Chunky
Ranch Hand

Joined: Dec 27, 2000
Posts: 116
Hello all...
While Loop Mystery...
I have 2 doubts
Case 1:-
int i = 3;
while (i==3)// line 2
int k = 23;// line 3
The above case will not work & is giving Compile time error.
But if i insert a {} between line 2 & line 3 i.e. if i put int k =23; in {}
then it will work. Can someone tell me why ?
Case 2:-
public class Numeric
{
final static boolean b = true;
public static void main(String[] args)
{
while (true)
{
System.out.println("AS");
}
System.out.println("ASAS");
}
}
The above prog gives Compile time error :- "Statement not Reached
but if i replace the while (true) with while (b) then it works Ok.
What i don't understand is that since the value of b is final & final values
r Optimized by compiler at compile time then why come it does not produce
any Compile time Errors.(Since b = true)
Let me take other E.x:-
Say final int i = 34;
byte b = i; // will not give Compile error since value of i is final & is optimized during Compile time , so should'nt the compiler give error in above Case 2 where i m making while (b) // where b = final.
Can someone tell me where i m wrong.
Thanks.

Shah Chunky - Sun Certified Java2 Programmer.
Micah Holroyd
Greenhorn

Joined: Jan 22, 2001
Posts: 20
Hey Shah, great questions!
Your first question has me a little puzzled too. You'll get the same results with "do-while" loops and "for" loops, if you don't use brackets.
Perhaps the people who wrote the compiler realized that having a declaration as the only line in a loop is kind of pointless, since that variable can't be used outside the loop.
As for your second question, I typed out your code and got the same compiler error message as you when I have "while(true)". But when I switched it to read "while(b)", I still got the same compiler error message, but it worked for you.
I'm using jdk1.3, what version are you using?
Vanitha Sugumaran
Ranch Hand

Joined: Apr 11, 2001
Posts: 356
Hi,
These are tricky questions. I compiled your second code, I got compile time error with while(b). I am using 1.3 version.
Vanitha
[This message has been edited by Vanitha Sugumaran (edited May 30, 2001).]
randy arvizu
Greenhorn

Joined: May 12, 2001
Posts: 7
As far as question 1, I wonder if it has to do with scoping (much along the same lines as Micah points out). Without {}, the compiler does not know what the scope of the variable k should be (i.e., does it exist only for a brief moment, or is it local to main()?) It's interesting that any non-assignment statement is legal.
As far as question 2, that's a real stumper! Again, since the second println() is unreachable, a compiler error makes sense. Perhaps the compiler doesn't "get" that the final variable b is const and therefore allows the possiblity of it to change (in its own little compiler mind). Is a final variable created on the stack or on the heap? Maybe that is a clue?
My ramblings are just guesses. I sure hope someone in the know chimes in on this mystery.
cheers,
randya
js yang
Ranch Hand

Joined: May 09, 2001
Posts: 40
Regarding case #2:

For a while loop, the compiler checks to see if unreachable statements are created. Thus, the above code will cause a compiler error( in other words, the compiler knows that the statements after a "while(true)" statement will never be reached.
However, if a boolean flag is used( instead of the value "true" ), then a compiler error will not be thrown. Why? Because the compiler knows that in certain conditions the flag might be set to false and the while loop will be broken. For example, the following code will not throw a compiler error:


As for case #1--I am also clueless. I ran the code and the compiler gave this error: not a statement regarding "int k = 23".
Interestingly, the following code compiles correctly:

I hope someone can clarify this matter.
sona gold
Ranch Hand

Joined: Feb 14, 2001
Posts: 234

public class B{
public static void main(String[] args){
int i = 3;
int k = 0;
while(i==3)
k = 23;
}
}

in this the scope of k is clearly defined as being the main method
but in other case the scope of k is undecided for the compiler

sona<br />SCJP
Scott Appleton
Ranch Hand

Joined: May 07, 2001
Posts: 195
For case #2, I am unable to compile if boolean b is declared final, but get no compiler errors if b is not final. It appears (for 1.3, anyway) that the compiler knows whether the boolean flag variable has any chance of becoming false or not.
Shah Chunky
Ranch Hand

Joined: Dec 27, 2000
Posts: 116
Dear friends
I have JDK 1.2.1 & it is not giving any error when i use
final boolean b;
Can someone tell me what's wrong with the version that i m using.
Thanks
Farhan Tariq
Ranch Hand

Joined: May 14, 2001
Posts: 54
Hi Ranchers!!
I think u all r confused. Tell me how many times u declare any variable with same name e.g
int k = 10;
int k = 10;
will always give compiler error so in this program:
Case 1:-
int i = 3;
while (i==3) // line 2
int k = 23; // line 3
First of all make clear that "while" loop boundary maintained through braces {}. But if we don't give it braces then the very next statement becomes a part of while loop. So in that case:
int k=23;
gives error because it compiled in while loop so many times. I hope it makes u clear. By the way if you want the above code works taking "int k = 23;" in main not in while then give terminator at end of while as:
Case 1:-
int i = 3;
while (i==3); // line 2
int k = 23; // line 3
Now statement completed at while loop, however it entered into infinite loop.
Regards
Farhan


Micah Holroyd
Greenhorn

Joined: Jan 22, 2001
Posts: 20
I have to disagree with you, Farhan.
Just because the declaration is in a loop, does not mean that it will generate a compiler error. The variable only has scope for each instance of the loop and then can be re-declared the next time through the loop.
That's why the code:

doesn't generate a compiler error.
js yang
Ranch Hand

Joined: May 09, 2001
Posts: 40
I agree with Micah--you can declare the same variable so long as it is within another scope. Thus, it is okay if the same variable is redeclared with each pass of the while loop.
I don't think that anyone has satisfactorily explained this puzzled.
Sona Nagee wrote that: "in this the scope of k is clearly defined as being the main method but in other case the scope of k is undecided for the compiler." My question is why is the scope of k undecided in the following code:

Isn't the scope of k defined? The scope of k lasts with each pass of the while loop.
Anyway, I hope that someone can shed some light on this puzzle.
Shah Chunky
Ranch Hand

Joined: Dec 27, 2000
Posts: 116
But friends does the below give Compile time error.
I don't get any error in JDK 1.2.1
public class Numeric
{
final static boolean b = true;
public static void main(String[] args)
{
while (true)
{
System.out.println("AS");
}
System.out.println("ASAS");
}
}
Thanks
js yang
Ranch Hand

Joined: May 09, 2001
Posts: 40
Shah, running your exact code on JDK 1.3, my compiler gave an error, stating that there is an unreachable statement in my code.
Anyway, were you intending to use the final static boolean b in the while loop? The following code gave me a compiler error about the unreachable statement:

However, the following code( where the boolean is not final ) did not give a compiler error:

lusha tak
Ranch Hand

Joined: Dec 30, 2000
Posts: 185
hi all!!
even the following code throughs error. it's not the case only with while....
public class Numeric
{
public static void main(String[] args)
{
int i = 3;
if(i==3)
//line 1
int p = 3;
//line 2
}
}
but gets complied nicely if i put braces in line 1 & 2 respectively
Lusha
Prosenjit Banerjee
Greenhorn

Joined: May 04, 2001
Posts: 20
Dear all,
This thread is really interesting. Thanks Mr. Shah Chunky. Everybody tried to solve the problem, but I think none of them had a real satisfactory answer.
Even I can't solve the problems. But I can guess and want share it with others and check whether I am right.
The first problem is the compiler shouts when I write the following :
while(...)
int i = ...;
The same problem arises when I replace while with if. The compiler smiles if I include the statement with braces like the following :
while(...)
{
int i = ...;
}
The question is why or whether the compiler should behave like this. According to me the compiler behaves like this, because it does not want to confuse the developers. But where is the question of confusion? Look at the following :
int i = 3 ;
if(i == 3)
int j = 4 ;
We know that here j j can't be accessed outside the if statement. But the code seems to be that j is defined in the outer scope and it gets defined only if the value of i is equal to 3. There is a confusion because later we may want to refer j in the outer scope and it will fail failing us to quickly debug that where the problem is. (You may shout "Oh boy, why are not you getting compiled? Be steady and look there that i equals 3 and thus j is defined and has got a value of 4" .)
Actually such a loop or if construct that contains merely a statement which does nothing but defines a variable has NO PRACTICAL USAGE (of course, according to my limited knowledge). If we still want to write such a statement (just for fun, isn't so!) we have to write it more clearly and more specifically so that the statement can tell "Hey, now you see I am in the inner room, you can't get me outside this room".
If it is the real fact, I would thank JAVA.
But i don't know what about the second problem. I am using Java 2 and get the problem. Since many of the responders faced no problem with Java 3, I can conclude that the complier creators have realised that "there is no harm with determining the value of the final variable (because it gurantees to be never changed) and then to decide whether to allow the developer to compile the code.
But I (we) still wait for some more better and confident answer. Hey, William Brogden, Cindy Glass, Paul Anil, Junilu Lacar and all, can you here me (us)? Where are you? Please help me (us).
Prosenjit Banerjee.
I LOVE JAVARANCH.COM
V Srinivasan
Ranch Hand

Joined: Aug 16, 2000
Posts: 99
Hi Friends,
I would like to express my views on while loop (wild loop)
While loop expression may be of
(a) boolean variable
(b) evaluation which returns boolean value [i.e.(i==3), (i.equals(a)), etc.]
(c) boolean literal [true and false]
At compile time (a) and (b)'s boolean value not known, it comes to know only at loading of class. (c) is something like final static (you cann't change while(true) in while loop to false) which is determined at compile time itself.
While loop with curly brace and without curly brace has differences in execution.
- with curly brace, in case of
(a) if the variable value inversed within the loop the loop ends otherwise infinite.
(b) within while loop there should be any element which should change the evaluation so that it returns the inverse expression, then loop ends otherwise infinite.
(c) if true, it is infinite. if false compile time error "statement not reached".
- without curly brace, in case of
(a) if the variable true, first statement executed, infinitely
if the variable false, skips while loop
(b) if it is true, first statement executed, infinitely
if it is false, skips while loop
(c) if true, first statement, infinite
if false, compile time error "statement not reached".
Note:
(1) Without curly braces, while loop consists only one statement,
second statement is not part of while loop at all.
(2) No while loop or for loop takes variable declaration both at
declaring and inside the loop i.e.
while(int i=1)// not acceptable
while(true) int i=1 // not acceptable, only in case of without curly brace
it gives error message as "illegal declaration".
Hope this clears the behaviour of while loop and the arrived the
result. Please do work out with the above permutation and combinations, Mystrery vanishes.
Please clarify me if I am wrong.
Thanks and regards,
V. Srinivasan
[This message has been edited by V Srinivasan (edited June 16, 2001).]
Prosenjit Banerjee
Greenhorn

Joined: May 04, 2001
Posts: 20
Hi Srinivasan so many thanks to you.
But THE MYSTRY STILL PERSISTS
Please try to understand what I want to say.
1. It is good that

gives error.
But why

has no error?
2. Why it is a different case if I omit braces of any kind of loops or if constructs. If you say that it is the rule then I would ask for the specifications of such a rule and the reason behind such a rule.
3. What about the final variable? Why Java2 does not complain if I write

while Java claims that it is so friendly? Is it a bug?
You only stated the behavours you experienced but did not solve the problem. I tried to state the possible solutions but don't know whether I am correct. I know the behavour but don't know the reason behind it.
I am confused . Please help me.
I LOVE JAVARANCH.COM
V Srinivasan
Ranch Hand

Joined: Aug 16, 2000
Posts: 99
Hi Prosenjit,
What JLS says
if
The if statement allows conditional execution of a statement or a conditional choice of two statements, executing one or the other but not both.
While
The while statement executes an Expression and a Statement repeatedly until the value of the Expression is false.
Though both IF and WHILE takes boolean expression, a MAJOR DIFFERENCE between IF and WHILE is WHILE is a loop and IF is not a loop, if performs a conditional operation.
Hope the above gives answer to your query (1).
Only in case of Switch JLS says - The body of a switch statement must be a block. It implies that block of statement is optional in other cases.
Hope the above gives answer to your query (2).
Though it is final variable we can initialise it at later stage too, not only final any variable we can declare and initialise it at later stage before we use them actually(is it?). Since it is final it must be assigned a value before use. In this case, it gives error because it has not yet initialised.
Hope the above gives answer to your query (3).
Now coming to the actual post of Shah Chunky
Question 1
What JLS says - If execution of the Statement completes abruptly for any other reason, the while statement completes abruptly for the same reason.
It says invalid declaration. In while loop you are trying to declare and assign int k=23 infinitely(repeatedly), is that you want to do?, I think that is the possible reason for error.
Question 2
In case of while(true) at compile time itself compiler detects it contains an infinite while loop with an argument type of boolean literal and it finds one more line "System.out.println("ASAS");" hence, compiler says if I compile this program I will not reach this statement. That is the reason "Statement not reached" error at compile time.
In case of while(b) compiler satisfies that the while loop has an argument type of boolean variable and checks whether it has been assigned with boolean value or not. If it is assigned checks whether it is correct boolean literal or not, if it is correct satisfies and compiles otherwise gives error stating variable not initialised (irrespective of assiged value i.e. true or false). Actually at run time, the program has to perform a infinite loop. There is only possible way to prevent the infinite loop, inverse the boolean variable in the body of the loop.
Oofh, I think it clarifies your doubts.
Please clarify me if I am wrong.
Thanks and regards
V.Srinivasan
[This message has been edited by V Srinivasan (edited June 21, 2001).]
[This message has been edited by V Srinivasan (edited June 21, 2001).]
Anshul Manisha
Ranch Hand

Joined: Apr 17, 2001
Posts: 74
Originally posted by V Srinivasan:
What JLS says - If execution of the Statement completes abruptly for any other reason, the while statement completes abruptly for the same reason.
It says invalid declaration. In while loop you are trying to declare and assign int k=23 infinitely(repeatedly), is that you want to do?, I think that is the possible reason for error.
[/B]

Hi V, I think you are wrong here. I tried to compile the code and it gave me a somewhat explanatory error.(i compiled under JVM 1.3)

"JTest12.java": Error #: 222 : no declaration allowed here, use '{' at line 16, column 7

Seems that Java compiler doesn't allow a declaration to be the only part of loop and that is why it compiles nicely when we put braces around int k = 23
ie.
while

does not compile

compiles and executes.
any thoughts...

AM<BR> <A HREF="mailto:anshulmohan@rediffmail.com" rel="nofollow">anshulmohan@rediffmail.com</A>
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: While Loop Mystery...