dock_side_tough
dock_side_tough

Reputation: 353

Java - Why can't I initialize the start value of a variable outside of a for loop?

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

Answers (2)

Dennis Kriechel
Dennis Kriechel

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

lpiepiora
lpiepiora

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

Related Questions