🔹 Default Values of Variables in Java
In Java, the default value of a variable depends on its data type and where it’s declared (instance variable, static variable, or local variable).
1️⃣ Instance and Static Variables
(i.e., fields of a class)
These automatically get default values if not explicitly initialized.
Data Type | Default Value |
---|---|
byte | 0 |
short | 0 |
int | 0 |
long | 0L |
float | 0.0f |
double | 0.0d |
char | '\u0000' (null character) |
boolean | false |
Reference types (String , objects, arrays) | null |
Example:
class Example {
int num; // Default: 0
double price; // Default: 0.0
boolean flag; // Default: false
String text; // Default: null
static int staticNum; // Default: 0 (static fields also get default values)
}
2️⃣ Local Variables (Inside Methods)
⚠️ Local variables do NOT get default values!
You must initialize them before use, otherwise compilation fails.
Example:
void test() {
int x;
System.out.println(x); // ❌ Compilation Error: "variable x might not have been initialized"
}
3️⃣ Array Elements
Array elements do get default values based on their type.
Example:
int[] numbers = new int[5]; // All elements are initialized to 0
String[] texts = new String[3]; // All elements are initialized to null
🔹 Summary
Variable Type | Gets Default Value? |
---|---|
Instance Variables (fields) | ✅ Yes |
Static Variables | ✅ Yes |
Local Variables | ❌ No (must initialize before use) |
Array Elements | ✅ Yes |