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++)
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With