Home / Questions / Variable of the boolean type is automatically initialized as?
Explanatory Question

Variable of the boolean type is automatically initialized as?

👁 1,344 Views
📘 Detailed Answer
🕒 Easy to Read
Read the answer carefully and go through the related questions on the right side to improve your understanding of this topic.

Answer with Explanation

A variable of the boolean type in Java is automatically initialized to falsebut 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:

false

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