0

Why this code runs normal

static boolean bool;

    public static void main() {
        System.out.println(bool);
    }

While here

public static void main() {
        boolean bool;
        System.out.println(bool);
    }

I have error: Variable 'bool' might not have been initialized

Aren't both of them have default value false?

aetrnm
  • 402
  • 3
  • 13
  • 1
    See also [Definite Assignment in the JLS, Ch. 16](https://docs.oracle.com/javase/specs/jls/se7/html/jls-16.html): "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." – KevinO Mar 25 '21 at 21:41
  • *Aren't both of them have default value false?* -- No. Class and instance variables are implicitly initialized, local variables are not. – user15187356 Mar 26 '21 at 02:02

1 Answers1

0

That's exactly how Java works. All "static" and "instance" class members of primitive types are initialized by the compiler. In particular, boolean are always initialize to false (that is your first piece of code).
Instead, local variable (second piece of code) "must" be manually initialized, otherwise you get a compilation error.

Marco Tizzano
  • 1,726
  • 1
  • 11
  • 18