Lab: watching the defaults¶
☕ Java 17 · Giving Variables Their First Value · 3/3
Goal: print the default values Java gives to fields, and see why a local variable needs a value from you.
Setup: create com/netflix/model/Movie.java under your source folder.
Step 1 — Four fields, no values¶
package com.netflix.model;
public class Movie {
String title; // → null
double rating; // → 0.0
int views; // → 0
boolean available; // → false
}
No = anywhere: Java fills them in when an object is created.
Step 2 — A method with a local variable¶
public void displayInfo() {
String label = "Now Showing";
System.out.println(label + ": " + title);
}
Try writing String label; without a value: the next line no longer compiles, with variable label might not have been initialized. Put the value back.
Step 3 — A main to print everything¶
public static void main(String[] args) {
Movie movie = new Movie();
System.out.println("--- Default Instance Variable Values ---");
System.out.println("Title : " + movie.title);
System.out.println("Rating : " + movie.rating);
System.out.println("Views : " + movie.views);
System.out.println("Available: " + movie.available);
System.out.println("--- Calling displayInfo ---");
movie.displayInfo();
}
Step 4 — Run¶
$ javac com/netflix/model/Movie.java
$ java com.netflix.model.Movie
--- Default Instance Variable Values ---
Title : null
Rating : 0.0
Views : 0
Available: false
--- Calling displayInfo ---
Now Showing: null
Every field shows its default. displayInfo() prints its local label, which you initialized, and the still-null title.
← final fields · Back to the series
🎓 Preparing the OCP Java 17 exam? Exam traps and practice questions for this section → (optional)