Skip to content

OCP exam prep: creating objects

☕ Java 17 · 🎓 OCP 1Z0-829 · Bringing Your Class to Life: Creating Objects

Optional page

This page is for readers preparing the Oracle Certified Professional Java SE 17 Developer exam (1Z0-829). The concepts are all you need otherwise.

Exam objective: Create classes and records, and define and use constructors and instance initializers.

Four traps to watch for

Trap 1 — A return type means it's not a constructor

public void Movie() { } is a method named Movie. new Movie() uses the compiler's default constructor instead.

Trap 2 — Any constructor removes the default one

After public Movie(String t) { }, new Movie() doesn't compile unless you write a no-argument constructor too.

Trap 3 — Initialization order

Field initializers and instance initializer blocks run top to bottom, all before the constructor body.

Trap 4 — Locals have no default value

Fields get defaults (0, false, null). Local variables don't: reading one before assigning it is a compiler error.

Practice questions

1. What is the output?

public class Series {
    int seasons = 3;
    public void Series() { seasons = 5; }

    public static void main(String[] args) {
        Series s = new Series();
        System.out.println(s.seasons);
    }
}

A. 3
B. 5
C. Compilation error
D. Runtime exception

Answer

A. void Series() has a return type, so it's a regular method, never called here. The default constructor runs and seasons keeps 3. A method may share the class name, so it compiles.

2. What happens when this code is compiled?

public class Subscription {
    String plan;
    public Subscription(String plan) { this.plan = plan; }

    public static void main(String[] args) {
        Subscription s = new Subscription();
    }
}

A. Prints null
B. Prints an empty string
C. Compilation error
D. NullPointerException

Answer

C. The class declares a constructor, so there is no default one: new Subscription() matches nothing. Fix: pass an argument, or add a no-argument constructor.

← Back to the series · All 1Z0-829 pages