| Author |
for loop not compiling
|
mvPrasad Regula
Ranch Hand
Joined: Sep 14, 2009
Posts: 42
|
|
public class Temp
{
public static void main(String[] args)
{
int i = 0;
for ( ; i<10; i++) ; // (1)
System.out.println("1= "+i);
for (i=0; ; i++) break; // (2)
System.out.println("2= "+i);
for (i=0; i<10; ) i++; // (3)
System.out.println("3= "+i);
for ( ; ; ) ; // (4)
System.out.println("4= ");
}
}
When I compile javac Temp.java, I get an error For the fourth System.out.println as "statement unreachable". Has it been at runtime I can consider that the fourth for loop is an infinite so the System.out.println is unreachable. This is compile time error.
|
Prasad Regula
|
 |
mvPrasad Regula
Ranch Hand
Joined: Sep 14, 2009
Posts: 42
|
|
|
It has been changed
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16809
|
|
Has it been at runtime I can consider that the fourth for loop is an infinite so the System.out.println is unreachable. This is compile time error.
The compiler has logic to detect, under certain conditions, if code is unreachable. In this case, it can detect that the fourth for-loop is an infinite loop.
Henry
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
Atwal Usha
Ranch Hand
Joined: Sep 10, 2009
Posts: 137
|
|
Hi,
As the for loop at line no. 4 is an endless loop so compiler will never be able to reach any statement after that for the compilation purpose and therefore an error is thrown stating it to be an unreachable statement.
|
Java Certification Exam Mock Tests: SCJA SCJP 5 SCJP 6 SCJP 6 (Online Training) SCJP 6 (Instructor Led Training) SCWCD 5 SCBCD 5 SCEA 5
|
 |
Harsh Pensi
Ranch Hand
Joined: Aug 05, 2009
Posts: 67
|
|
Can you give some more examples of such non-trivial issues where the compiler IMO behaves over-smart??? Got my exam on Monday and still new things coming up
|
SCJP6 - 93% SCWCD5 - 97%
|
 |
Ankit Garg
Saloon Keeper
Joined: Aug 03, 2008
Posts: 9191
|
|
I think that in some cases the compiler is not smart enough to detect something leaving aside being oversmart.
Here the compiler detects that i is initialized but doesn't give an error that the else part is unreachable...
|
SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
|
 |
Harsh Pensi
Ranch Hand
Joined: Aug 05, 2009
Posts: 67
|
|
|
Also, compiler gives Unreachable code error with while(false){}, but not with if(false){}.
|
 |
KrishnaPrasad raghavan
Ranch Hand
Joined: Oct 28, 2008
Posts: 46
|
|
Just Remove the ; after the for( ; ; ) ;. I am sure the compiler won't complain.
|
 |
Siva Masilamani
Ranch Hand
Joined: Sep 19, 2008
Posts: 377
|
|
Visit this link to get some idea about compile time resolution
Compile time constant
|
SCJP 6,SCWCD 5,SCBCD 5
Failure is not an option.
|
 |
 |
|
|
subject: for loop not compiling
|
|
|