Skip to lesson

Find and fix OOP bugs

Every OOP bug falls into one of three kinds: javac refuses the code (a compile error), the program stops with an exception (a crash), or it runs and prints the wrong thing (a silent bug). Each kind gives you different clues, and a fixed routine finds the cause.

Read the message before the code

A crash prints the exception, a message, then a stack trace: the methods that were running, newest on top, as in What are exceptions? (opens in a new tab). Read it from the top and stop at the first row from your own code.

Example 1 · A crash and its stack trace

LabelDemo.javaJava
class Customer {    String name;    String city;
    Customer(String name, String city) {        this.name = name;        this.city = city;    }}
class Order {    Customer customer;
    Order(Customer customer) {        customer = customer;    }
    String label() {        return "Deliver to " + customer.city;    }}
public class LabelDemo {    static void printLabel(Order o) {        System.out.println(o.label());    }
    public static void main(String[] args) {        Order o = new Order(new Customer("Priya", "Kochi"));        System.out.println("Order placed");        printLabel(o);    }}
Sample output
Order placed
Exception in thread "main" java.lang.NullPointerException: Cannot read field "city" because "this.customer" is null
	at Order.label(LabelDemo.java:19)
	at LabelDemo.printLabel(LabelDemo.java:25)
	at LabelDemo.main(LabelDemo.java:31)

What this code does

  • Top row: the crash is in Order.label, line 19. The rows below show who called it: printLabel, called by main.
  • The message says this.customer is null. Tracing back to the constructor shows the cause: customer = customer; assigns the parameter to itself.
  • The crash happens far from the bug: the constructor ran without error long before label() was called.

Example 2 · The fix: set the field, and reject null early

LabelFixDemo.javaJava
class Customer {    String name;    String city;
    Customer(String name, String city) {        this.name = name;        this.city = city;    }}
class Order {    private final Customer customer;
    Order(Customer customer) {        if (customer == null) {            throw new IllegalArgumentException("Order needs a customer");        }        this.customer = customer;    }
    String label() {        return "Deliver to " + customer.city;    }}
public class LabelFixDemo {    public static void main(String[] args) {        Order o = new Order(new Customer("Priya", "Kochi"));        System.out.println(o.label());        try {            new Order(null);        } catch (IllegalArgumentException e) {            System.out.println("Rejected: " + e.getMessage());        }    }}
Output
Deliver to Kochi
Rejected: Order needs a customer

What this code does

  • this.customer = customer; sets the field. Making it private final means javac complains if a constructor forgets it.
  • Checking for null in the constructor fails at once, with a clear message, instead of crashing later in another method.

Modern Java also explains null crashes in words, such as because "this.customer" is null: that names the field to trace back.

A compile error looks different: File.java:12: error:, the message, then the line with a ^ under the exact spot. Fix the first error first, because one mistake often causes several messages.

A debugging routine

Changing random lines and hoping wastes time. Follow the same steps for every bug, then watch them find a silent bug below.

  1. Run it and copy the exact error, or write the wrong output next to the expected one.
  2. Go to the line the message names. Read the message in plain words.
  3. Ask which value is wrong there: which variable is null, or which object has the wrong type or value.
  4. Trace back to where that value was set. The cause is often in another class, such as a constructor.
  5. Make the smallest fix, then run again and test one more case.

Trace the code

Find where the value goes wrong

Expected output: Rohit: 5 and Virat: 6. Step through and find the first wrong value.

class Player {
String name;
static int score;
Player(String name) {
this.name = name;
}
void hit(int runs) {
score += runs;
}
}
public class ScoreBug {
public static void main(String[] args) {
Player a = new Player("Rohit");
Player b = new Player("Virat");
a.hit(4);
b.hit(6);
a.hit(1);
System.out.println(a.name + ": " + a.score);
System.out.println(b.name + ": " + b.score);
}
}

Variables

a
Rohit
score
0

Output

(nothing printed yet)

Line 16Object #1 for Rohit. score is static: one copy for the whole class, not one per player.

Step 1 of 7
When there is no error, add a System.out.println of the key values at a few points, or use your IDE's debugger to stop at a line and look at every field.

Silent bugs: wrong output, no error

These are the hardest bugs, because Java does not complain. Suspect one whenever the output is null, 0, or a value that never changes.

Example 3 · Silent bug: equals that does not override

EqualsBugDemo.javaJava
class Student {    String roll;    String name;
    Student(String roll, String name) {        this.roll = roll;        this.name = name;    }
    public boolean equals(Student other) {        return roll.equals(other.roll);    }}
public class EqualsBugDemo {    public static void main(String[] args) {        Student a = new Student("21CS07", "Aarav");        Student b = new Student("21CS07", "Aarav K");        Object o = b;        System.out.println(a.equals(b));        System.out.println(a.equals(o));        System.out.println(a.hashCode() == b.hashCode());    }}
Output
true
false
false

What this code does

  • equals(Student) is a new overload, not an override. With an Object argument, javac picks the inherited Object.equals, which compares addresses.
  • hashCode was never overridden, so two equal students get different hash codes. No error, just wrong answers.

Example 4 · The fix: equals(Object) with @Override, plus hashCode

EqualsFixDemo.javaJava
class Student {    String roll;    String name;
    Student(String roll, String name) {        this.roll = roll;        this.name = name;    }
    @Override    public boolean equals(Object o) {        if (this == o) {            return true;        }        if (!(o instanceof Student other)) {            return false;        }        return roll.equals(other.roll);    }
    @Override    public int hashCode() {        return roll.hashCode();    }}
public class EqualsFixDemo {    public static void main(String[] args) {        Student a = new Student("21CS07", "Aarav");        Student b = new Student("21CS07", "Aarav K");        Object o = b;        System.out.println(a.equals(b));        System.out.println(a.equals(o));        System.out.println(a.hashCode() == b.hashCode());    }}
Output
true
true
true

What this code does

  • equals(Object o) with @Override really overrides, so every caller gets the roll-number comparison.
  • hashCode uses the same field as equals (roll), so equal students always get equal hash codes.

Four silent bugs come up again and again:

  • Shadowing: customer = customer; or int price = newPrice; sets a parameter or a new local, not the field. Use this. and do not re-declare.
  • equals overload: equals(Student s) does not override equals(Object), so code that holds an Object uses the wrong method. @Override catches it.
  • equals without hashCode: two equal objects get different hash codes, which breaks hash-based storage. Always override both, as in hashCode() and the equals/hashCode contract (opens in a new tab).
  • Shared by mistake: a static field holds data that should belong to each object.

Find the bug

Spot the silent bug

Select the line that is wrong.

Every hostel prints its warden as null. Which line is wrong?

Round 1 of 2

Crashes: NullPointerException and ClassCastException

A NullPointerException comes from using . on a reference that is null; in OOP code, usually a field nobody set. A ClassCastException comes from a downcast that meets the wrong object.

Example 5 · ClassCastException from a blind downcast

CastBugDemo.javaJava
class Payment {    int amount;
    Payment(int amount) {        this.amount = amount;    }}
class CardPayment extends Payment {    CardPayment(int amount) {        super(amount);    }
    int cashback() {        return amount / 100;    }}
class UpiPayment extends Payment {    UpiPayment(int amount) {        super(amount);    }}
public class CastBugDemo {    public static void main(String[] args) {        Payment[] list = { new CardPayment(5000), new UpiPayment(800) };        for (Payment p : list) {            CardPayment c = (CardPayment) p;            System.out.println("Cashback: Rs. " + c.cashback());        }    }}
Sample output
Cashback: Rs. 50
Exception in thread "main" java.lang.ClassCastException: class UpiPayment cannot be cast to class CardPayment (UpiPayment and CardPayment are in unnamed module of loader 'app')
	at CastBugDemo.main(CastBugDemo.java:29)

What this code does

  • The first element is a card, so the cast works. The second is a UpiPayment, and the cast fails at run time.
  • The message names both classes: the real object (UpiPayment) and the type you cast to (CardPayment).
  • Fix: if (p instanceof CardPayment c) { ... c.cashback() ... }, so only real card payments are cast.

For an NPE, fix the cause, not the crash: set the field in every constructor, reject null early, or handle the missing case on purpose.

For a CCE, remember that javac allowed the cast, so it fails only at run time, as in Downcasting and ClassCastException (opens in a new tab). Check first with if (p instanceof CardPayment c), or better, move the behaviour into an overridden method.

Fix the error

Fix the crash

Read the error, then pick the line that fixes it.

Round 1 of 2

main calls new Laptop().power(). Fix the cause of the crash.

class Charger {
int watts = 65;
}
class Laptop {
Charger charger;
Laptop() {
System.out.println("Laptop ready");
}
int power() {
return charger.watts;
}
}

Error

Exception in thread "main" java.lang.NullPointerException: Cannot read field "watts" because "this.charger" is null

Compile errors in class hierarchies

These four messages appear again and again in OOP code. Each one names the rule you broke, so read the message, then look at the line and the class it names.

Example 6 · Two hierarchy compile errors at once

HierarchyErrors.javaJava
interface Payable {    int amountDue();}
class Person {    String name;
    Person(String name) {        this.name = name;    }}
class Tenant extends Person implements Payable {    int rent;
    Tenant(String name, int rent) {        this.rent = rent;    }
    int amountDue() {        return rent;    }}
public class HierarchyErrors {    public static void main(String[] args) {        Payable p = new Tenant("Rohan", 9000);        System.out.println(p.amountDue());    }}
Sample compiler output
HierarchyErrors.java:20: error: amountDue() in Tenant cannot implement amountDue() in Payable
    int amountDue() {
        ^
  attempting to assign weaker access privileges; was public
HierarchyErrors.java:16: error: constructor Person in class Person cannot be applied to given types;
    Tenant(String name, int rent) {
                                  ^
  required: String
  found:    no arguments
  reason: actual and formal argument lists differ in length
2 errors

What this code does

  • Error 1: interface methods are public. A method without public is less visible, which is not allowed. Fix: public int amountDue().
  • Error 2: the constructor has no super(...), so Java adds super();, but Person needs a String. Fix: super(name); as the first line.

The four messages and their fixes:

  • constructor Person in class Person cannot be applied to given types → the hidden super(); finds no matching parent constructor. Call super(name) first.
  • is not abstract and does not override abstract method → a class forgot to implement an abstract or interface method.
  • attempting to assign weaker access privileges; was public → interface methods are public; the class must write public too.
  • method does not override or implement a method from a supertype → @Override caught a wrong name or parameter type.

Fix the error

Fix the compile error

Read the error, then pick the line that fixes it.

Round 1 of 2

Every vehicle must say its toll.

abstract class Vehicle {
abstract int toll();
}
class Car extends Vehicle {
int tolls() {
return 80;
}
}

Error

Car.java:4: error: Car is not abstract and does not override abstract method toll() in Vehicle
class Car extends Vehicle {
^

Next step

Check your understanding

12 quick questions