Java Boolean Default Value: What You Need to Know

In Java, the default value for the primitive data type boolean is false. This means that if you declare an instance variable of type boolean (class member variable), but do not explicitly initialize it, the variable will automatically be assigned false as the default value. For example:

public class Example {
    boolean flag; // 没有显式初始化,默认为false

    public static void main(String[] args) {
        Example example = new Example();
        System.out.println(example.flag); // 输出为false
    }
}

Local variables declared within a method do not automatically initialize, so if a boolean variable is declared within a method without initializing it, a compilation error will occur.

bannerAds