Field Initialization: Default Values
You'll learn: What happens when you declare a field in a class but don't assign it a starting value.
The Automatic Safety Net
When you create a field in a class without explicitly giving it a value, Java doesn't leave it undefined or random—it automatically initializes it to a default value based on its type. This is Java's safety mechanism to ensure your fields always have some predictable value, even if you forget to set one.
Think of it like moving into a new apartment: even if you haven't brought any furniture yet, the lights still work and the temperature is set to a reasonable default. Java ensures your fields have sensible "factory settings."
Default Values by Type
Here's what Java assigns automatically:
- Numeric primitives (
int,long,double, etc.) →0(or0.0for decimals) - boolean →
false - Reference types (objects, arrays, Strings) →
null - char →
'\u0000'(the null character, essentially "no character")
class Person {
int age; // automatically 0
double salary; // automatically 0.0
boolean isActive; // automatically false
String name; // automatically null
}
When you create a Person object with new Person(), all these fields immediately have their default values—you don't need to worry about uninitialized data causing unpredictable behavior.
Why This Matters
Default initialization prevents the dangerous "garbage values" you might encounter in languages like C. However, remember that null references can cause NullPointerException if you try using them, so it's often wise to explicitly initialize reference-type fields yourself.
Key Takeaway: Java automatically initializes fields to sensible defaults—0 for numbers, false for booleans, and null for reference types—ensuring predictable behavior even when you don't explicitly set values.