Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java not printing default unitialized value

Tags:

java

I understand that Java objects that are only declared but not initialized are defaulted to the null value, but then why doesn't the following compile and print out null?

String a;
System.out.println(a);

1 Answers

From section 16 of the JLS:

Each local variable (§14.4) and every blank final field (§4.12.4, §8.3.1.2) must have a definitely assigned value when any access of its value occurs.

Your code will work for non-final fields (instance or static variables) as they are initialized as per section 4.12.5) but will cause a compile-time error for local variables due to this.

The same would be true if a were a primitive variable. Here's a short but complete program showing all of this:

class Test {

    static int x;
    static String y;

    public static void main(String[] args) {
        System.out.println(x);
        System.out.println(y);

        int lx;
        String ly;
        System.out.println(lx); // Compile-time error
        System.out.println(ly); // Compile-time error
    }
}

Output of the first two lines once the non-compiling lines have been removed:

0
null
like image 175
Jon Skeet Avatar answered Mar 13 '26 07:03

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!