✏️ Explanatory Question
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).
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:
false
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
}
}
| Variable Type | Automatically Initialized? | Default Value |
|---|---|---|
| Instance variable | ✅ Yes | false |
| Static variable | ✅ Yes | false |
| Local variable | ❌ No | Must be initialized manually |