A variable of the boolean type in Java is automatically initialized to false â but only when it is a member variable (instance or static variable).
đĄ Detailed Explanation:
1. Class-level (Instance or Static) Boolean Variables
When a boolean variable is declared as a member of a class, it is automatically initialized to false.
class Example {
boolean flag; // instance variable
void show() {
System.out.println(flag); // Output: false
}
}
public class Main {
public static void main(String[] args) {
Example obj = new Example();
obj.show();
}
}
đĸ Output:
2. Local Boolean Variables
When a boolean variable is declared inside a method, it is not automatically initialized.
You must assign a value before using it, otherwise youâll get a compile-time error.
public class Main {
public static void main(String[] args) {
boolean flag;
System.out.println(flag); // â Compile-time error: variable flag might not have been initialized
}
}
đ§ Summary Table:
| Variable Type |
Automatically Initialized? |
Default Value |
| Instance variable |
â
Yes |
false |
| Static variable |
â
Yes |
false |
| Local variable |
â No |
Must be initialized manually |