Search code examples
javainitializationlocal-variablesmain-method

Uninitialized local variable - No error : Java


Here are two uninitialized local variables. Still this does not give compile time or runtime error and executes completely. Is this thing permissible in Java and How (explanation will be welcome).

class A2{ }

public class A {
public static void main(String[] args) {
    int x;
    A2 a2;

    System.out.println("Main");
}

}

Solution

  • There's nothing incorrect about that code. You don't actually use those variables so there's no issue. If you did try to use them it would then become a problem. For example,

    System.out.println(a2);
    System.out.println(x);
    

    would bring about "Variable 'x'/'a2' might not have been intitialized" errors. There will be no default values or ability to run the code. It will be a compile time error and your code won't run. If the variables were class fields they would get default values for certain types or null otherwise.