Default field values
A class is a blueprint that describes what data a kind of thing holds and what it can do. An object is one real thing built from that blueprint with new, living on the heap, reached through a reference.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write a class Book with fields title (String) and pages (int) and a method describe() that prints <title> has <pages> pages. Create two books and call describe() on both.
Write a class Counter with an int value field and a method increment(). Create two counters, increment the first three times and the second once, and print both values.
Create one Book, store it in two variables x and y, change pages through y, and print x.pages and x == y.
Explain it without notes
What is the difference between a class and an object? Use an analogy and then the precise Java terms.
What exactly happens, step by step, when the JVM executes Dog d = new Dog();?
Dog a = new Dog(); Dog b = a; b.name = "Max"; What is a.name and why?
Why do fields get default values while local variables must be assigned before use?
Expected output
int: 0
double: 0.0
boolean: false
char is zero: true
String: null
array: null