Lab: choosing the right types for Movie¶
☕ Java 17 · Two Kinds of Data: Primitives and References · 3/3
Goal: design the fields of our Movie class, choosing a type for each piece of data and explaining why.
Setup: create com/netflix/model/Movie.java under your source folder.
Step 1 — Reference fields¶
package com.netflix.model;
public class Movie {
// Reference types (default: null)
private String title;
private String genre;
}
Text is an object in Java, so String is a reference type. A movie whose genre isn't set yet simply has genre == null.
Step 2 — Primitive fields¶
// Primitive types (default: 0 / false)
private int releaseYear;
private double rating;
private float storageSizeGB;
private long totalViews;
private boolean isAvailable;
| Field | Type | Why |
|---|---|---|
releaseYear |
int |
a whole number, far below 2 billion |
rating |
double |
needs decimals (9.3) |
storageSizeGB |
float |
decimals, but little precision needed |
totalViews |
long |
a hit show passes 2 billion views: an int would overflow |
isAvailable |
boolean |
available or not, nothing in between |
Step 3 — A summary method¶
public void printSummary() {
var label = title + " (" + releaseYear + ")";
var stars = rating >= 8.0 ? "Top Rated" : "Standard";
System.out.println(label + " — " + stars);
System.out.println("Views: " + totalViews);
}
var lets the compiler infer a local variable's type from its value: both label and stars are String. (condition ? a : b picks a if the condition is true, b otherwise.) Next section covers var in detail.
Step 4 — Run it¶
public static void main(String[] args) {
Movie movie = new Movie();
movie.title = "Stranger Things";
movie.genre = "Sci-Fi";
movie.releaseYear = 2016;
movie.rating = 9.3;
movie.storageSizeGB = 4.2f;
movie.totalViews = 1_500_000_000L;
movie.isAvailable = true;
movie.printSummary();
}
Remove the f from 4.2f and it no longer compiles: 4.2 is a double.
$ javac com/netflix/model/Movie.java
$ java com.netflix.model.Movie
Stranger Things (2016) — Top Rated
Views: 1500000000
← Reference types · Back to the series
🎓 Preparing the OCP Java 17 exam? Exam traps and practice questions for this section → (optional)