4
class returntest
{
    public static void main(String...args)
    {
        int a;
        System.out.println(a); //Line 1

        int b[] = new int[10];
        System.out.println(b[1]); //Line 2
    }
}

I get a compiler error (obviously) at Line 1 stating that the variable may not have been initialized.

I know all int array elements are initialized to 0 by default (so Line 2 compiles successfully) but my question is why cant compiler apply the same logic (of setting to 0 for all ints) to regular (non-array) int variables.

Is there any limitation that prohibits the compiler from doing that ?

2

4 Answers 4

4

Local variables defined in a block of statements always must be initialized before use.

But member variables, those defined directly in the body of a class, are automatically initialized to 0 when the object is created.

Useful thread here.

Sign up to request clarification or add additional context in comments.

Comments

2

From here:-

Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.

Comments

0

This was a language design decision.

Having a default initialisation for local variables could hide errors. The usage of a local variable implies you want to set it first. Simple cases of forgetting to set it, or setting it only in if then are captured.

Comments

0

When variable scope is local then you must initialized local variable.

When you declare any local/block variable, they didn’t get the default values. They must assigned some value before accessing it other wise compiler will throw an error.

As you see in your code

int a; //Gives error because not assigned any value

When you allocate resources for a local variable, Java doesn't write a value into the memory. The reason you get an error is because Java makes sure you give it a value before you use it. Sun realized that this can be a difficult problem to diagnose in C code, because you don't get help from the compiler, so they decided to check it at compile time.

Refer this link

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.