Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile Error: “Not a statement”

Tags:

java

public class Hello
{
   public static void main(String args[])
   {
     int i = 1;
     for(i; ;i++ )
     {
        System.out.println(i);
     }      
}

}

I would like to understand why above code is giving error as:

not a statement for(i ; ; i++)

like image 280
Indrajeet Avatar asked Sep 15 '25 02:09

Indrajeet


2 Answers

Because the raw i in the first position of your for is not a statement. You can declare and initialize variables in a for loop in Java. So, I think you wanted something like

// int i = 1;
for(int i = 1; ;i++ )
{
    System.out.println(i);
}      

If you need to access i after your loop you could also use

int i;
for(i = 1; ; i++)
{
    System.out.println(i);
}      

Or even

int i = 1;
for(; ; i++)
{
    System.out.println(i);
}      

This is covered by JLS-14.4. The for Statement which says (in part)

A for statement is executed by first executing the ForInit code:

If the ForInit code is a list of statement expressions (§14.8), the expressions are evaluated in sequence from left to right; their values, if any, are discarded.

like image 185
Elliott Frisch Avatar answered Sep 17 '25 17:09

Elliott Frisch


The lone i at the start of the for statement doesn't make any sense - it's not a statement. Typically the variable of the for loop is initialized in the for statement as such:

for(int i = 1;; i++) {
    System.out.println(i);
}

This will loop forever though, as there is no test to break out of the for loop.

like image 21
Mathias R Avatar answered Sep 17 '25 17:09

Mathias R