Find and fix OOP bugs
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)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
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); }}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 bymain. - The message says
this.customeris 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
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()); } }}Deliver to Kochi Rejected: Order needs a customer
What this code does
this.customer = customer;sets the field. Making itprivate finalmeans javac complains if a constructor forgets it.- Checking for
nullin 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.
- Run it and copy the exact error, or write the wrong output next to the expected one.
- Go to the line the message names. Read the message in plain words.
- Ask which value is wrong there: which variable is
null, or which object has the wrong type or value. - Trace back to where that value was set. The cause is often in another class, such as a constructor.
- 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.
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.
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
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()); }}true false false
What this code does
equals(Student)is a new overload, not an override. With anObjectargument, javac picks the inheritedObject.equals, which compares addresses.hashCodewas 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
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()); }}true true true
What this code does
equals(Object o)with@Overridereally overrides, so every caller gets the roll-number comparison.hashCodeuses the same field asequals(roll), so equal students always get equal hash codes.
Four silent bugs come up again and again:
- Shadowing:
customer = customer;orint price = newPrice;sets a parameter or a new local, not the field. Usethis.and do not re-declare. - equals overload:
equals(Student s)does not overrideequals(Object), so code that holds anObjectuses the wrong method.@Overridecatches 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
staticfield 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 2Crashes: 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
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()); } }}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.
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
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()); }}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 errorsWhat this code does
- Error 1: interface methods are
public. A method withoutpublicis less visible, which is not allowed. Fix:public int amountDue(). - Error 2: the constructor has no
super(...), so Java addssuper();, butPersonneeds aString. 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 hiddensuper();finds no matching parent constructor. Callsuper(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 arepublic; the class must writepublictoo.method does not override or implement a method from a supertype→@Overridecaught 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.
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