Back
Activity 4.6 Object References and Default Values
Introduction
Activity 4.6
Object References and Default Values
Topics
- Default initialization of instance variables
- Primitive vs object defaults
-
What
null means
- Object references
- Why NullPointerException occurs
Default Initialization
Instance variables are automatically assigned default values
before the constructor runs.
private Product featuredProduct;
Default Values
- int → 0
- double → 0.0
- boolean → false
- char → '\u0000'
- Any object → null
Constructors Run After Defaults
Default values are assigned before the constructor executes.
// Constructor runs AFTER default initialization
What Does null Mean?
null means a variable does not reference any object.
- null is not an object
- null is only used with object variables
- null is different from an empty String
null vs Empty String
System.out.println(b.length());
NullPointerException
If a variable is null,
there is no object to use.
p.applyDiscount(10); // NullPointerException
Preventing NullPointerException
Object References
Object variables store references to objects, not the
objects themselves.
Dog dog1 = new Dog("Fido", "Greyhound", 3, "gray");
Why This Matters
- Many fields start as null by default
- Constructors often prevent null problems
-
Composition (next lesson) relies heavily on object references
-
Data structures (next module) are also reference types
'F' → Fullscreen
Objectives
- Explain default values of instance variables
- Describe what null represents
- Identify object reference behavior
- Prevent NullPointerException using null checks
Activity Tasks
Task 1: Predict the Defaults
Examine the class below. Write down the default value for each
instance variable before the constructor runs.
Task 2: Safe Use of null
Run the program below and explain why it does not crash.
public static void main(String[] args) {
System.out.println(name.length());
System.out.println("Name is null");
Reflection Questions
-
Why do object variables default to
null?
-
What is the difference between a variable being null and an object
being empty?
- Why can two variables refer to the same object?
- What causes a NullPointerException?
-
Why do constructors often explicitly initialize object fields?
Submission
Submit your activity responses and reflection answers to the
appropriate dropbox.
Activity Complete