Reputation: 353
Is there a reason why I can't initialize the start value of a variable outside of a for loop? When I do this:
public static void main(String[] args) {
int userInt = 1;
int ender = 10;
for (userInt; userInt < ender; userInt++) {
System.out.println(userInt);
I receive a syntax error stating that userInt needs to be assigned a value, even though I've already assigned it a value of 1. When I do this instead:
public static void main(String[] args) {
int userInt;
int ender = 10;
for (userInt = 1; userInt < ender; userInt++) {
System.out.println(userInt);
The error goes away. What is the reason for this?
Upvotes: 1
Views: 244
Reputation: 3749
The generic syntax for a Java for loop
is as follows:
for ( {initialization}; {exit condition}; {incrementor} ) code_block;
This mean you can not just write down a variable name in the inizalization block. If you want to use an already defined variable, you just let it emtpy.
This should work for you:
for (; userInt < ender; userInt++) {
System.out.println(userInt);
}
Upvotes: 7
Reputation: 13749
The problem is that the for
statement expects an expression.
According to the language spec:
ForStatement:
BasicForStatement
EnhancedForStatement
And then:
BasicForStatement:
for ( ForInitopt ; Expressionopt ; ForUpdateopt ) Statement
ForStatementNoShortIf:
for ( ForInitopt ; Expressionopt ; ForUpdateopt ) StatementNoShortIf
ForInit:
StatementExpressionList
LocalVariableDeclaration
ForUpdate:
StatementExpressionList
StatementExpressionList:
StatementExpression
StatementExpressionList , StatementExpression
As you see the basic for statement, first element is optional initialization, which is either statement or local variable declaration.
The statement is one of :
StatementExpression:
Assignment
PreIncrementExpression
PreDecrementExpression
PostIncrementExpression
PostDecrementExpression
MethodInvocation
ClassInstanceCreationExpression
In your example userInt = 1
is an Assignment
, while just userInt
doesn't match any of elements on the StatementExpression
list, which causes compilation error.
Upvotes: 3