infoholic_anonymous
infoholic_anonymous

Reputation: 999

Why does a String need to be initialized even if the assignment will happen later?

I get the "The local variable string may not have been initialized" error with the following code. The code itself doesn't make sense it was written just for the sake of exercise.

public class StringExercise
{
    public static void main(String[] args)
    {
        String string; // initializing here fixes the issue
        for (int i = 0; i < 10; ++i)
        {
            if( (i % 4) == 2 )
            {
                string = "Number: " + i;
            }
        }
        System.out.println(string); // this is marked as wrong by Eclipse
    }
}

To get it working it is sufficient to initialize String as expressed in the comment above.

My question is why is it needed? The method println will never be given null and initialization will happen the first time the condition in the loop returns true. Am I doing something wrong or is it just Java being overcautious over programmer's errors? If the latter, how is it justified from the theoretical point of view?

Upvotes: 1

Views: 547

Answers (2)

fge
fge

Reputation: 121712

My question is why is it needed?

Because even though your code is "logically" written so that string will indeed be initialized in the loop, the compiler doesn't know it. All it sees is:

for (loop; elements; here)
    if (someCondition)
        string = something;

In short: a compiler will not check the logic of your code; it it only smart enough as to check for syntax errors, but after that, the bytecode generation itself is "dumb".

And as Java requires that all variables be initialized before use, you get this compiler error.

Upvotes: 7

Steve Kuo
Steve Kuo

Reputation: 63064

The compiler can't guarantee that string = "Number: " + i; will be executed within your for and if.

Upvotes: 1

Related Questions