Discussion Threads
1
What happens to fields you don't initialize?
Field Initialization
▦
Field Initialization
Field initialization is optional in Java. When you declare an instance variable, you can assign a value immediately (e.g., int myInt = 25) or leave it uninitialized. Uninitialized fields receive default values from Java: int gets 0, double gets 0.0, boolean gets false, and reference types like String get null. This is different from local variables, which must be explicitly initialized before use. Common tasks like setting initial state are typically handled via constructors, giving you control and flexibility.
Key Ideas
1Field initialization at declaration is optional
2Java assigns default values: int→0, double→0.0, boolean→false, Object→null
3Each object gets its own copy of instance fields
4Modifying one object's field does not affect others
5Constructors provide controlled initialization
Strengths
- ✦Default values prevent NullPointerException on primitives
- ✦Explicit initialization documents intent clearly
- ✦Flexibility to initialize at declaration or in constructor
Weaknesses
- △Relying on defaults can hide bugs (was 0 intentional?)
- △Reference type default (null) can still cause NullPointerException
- △No compile-time warning for uninitialized instance fields
Used in:Counter starting at 0, boolean flags defaulting to false, game scores initialized per player
Field Initialization Quiz
Field Initialization Quiz
QUIZ 1/7What is the default value of an uninitialized boolean instance variable in Java?
Practice Exercises
Classify each statement: Does it describe a Constructor or a Regular Method?
EXERCISE 1/3No return type (not even void)
Can have a return type
Must have same name as class
Can have any valid name
Called automatically by "new"
Called via dot notation (obj.method())
Cannot be called again after creation
Can be called multiple times
Constructor
Regular Method
Sort each variable characteristic into Local Variable or Instance Variable.
EXERCISE 2/3Gets default values (0, null, false)
Must be initialized before use
Declared in class, outside methods
Declared inside a method or block
Exists as long as the object exists
Exists only during method execution
Instance Variable
Local Variable
Match each scenario to the correct fix or explanation.
EXERCISE 3/3value = value does nothing
new MyClass() won't compile
this(5) in a constructor
int... must be the last parameter
void MyClass() { }
Use this.value = value
Custom constructor removed default
Constructor chaining
Vararg rule
This is a method, not a constructor