Skip to lesson

Common mistakes and practice

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Most static and final bugs come from two questions: does this value belong to each object or to the whole class, and may it change after it is set? Some mistakes stop javac; others compile and quietly print wrong values.

Mistakes and fixes at a glance

Most compile errors in this module come from one question: does this code have an object? A static method or block that uses an instance field gets non-static variable ... cannot be referenced from a static context.

Example 1 · A static method that uses an instance field

RentDemo.javaJava
class Room {    private int rent;
    Room(int rent) {        this.rent = rent;    }
    static void printRent() {        System.out.println("Rent: Rs. " + rent);    }}
public class RentDemo {    public static void main(String[] args) {        Room r = new Room(6000);        Room.printRent();    }}
Sample compiler output
RentDemo.java:9: error: non-static variable rent cannot be referenced from a static context
        System.out.println("Rent: Rs. " + rent);
                                          ^
1 error

What this code does

  • printRent() is static, so it runs with no Room object, while rent belongs to one room: Java cannot tell whose.
  • Fix: remove static and call r.printRent();. The method is about one room, so it is an instance method; the program then prints Rent: Rs. 6000.

Review: Static methods and why main is static (opens in a new tab). The other common mistakes, each with what goes wrong and the fix:

A counter that shows 1

Three students joined, yet the app prints 1. Without static, every object gets its own count, so each constructor adds 1 to a different copy and no field holds the total.

Example 2 · Bug: a counter that shows 1

CountBugDemo.javaJava
class Student {    private int count = 0;
    Student() {        count++;    }
    int getCount() {        return count;    }}
public class CountBugDemo {    public static void main(String[] args) {        Student a = new Student();        Student b = new Student();        Student c = new Student();        System.out.println("Students: " + c.getCount());    }}
Output
Students: 1

What this code does

  • count is an instance field, so each object has its own count that goes from 0 to 1.
  • Fix: private static int count = 0; and a static getter called as Student.getCount().

Example 3 · The fix: one static counter

CountFixDemo.javaJava
class Student {    private static int count = 0;
    Student() {        count++;    }
    static int getCount() {        return count;    }}
public class CountFixDemo {    public static void main(String[] args) {        new Student();        new Student();        new Student();        System.out.println("Students: " + Student.getCount());    }}
Output
Students: 3

What this code does

  • static gives one count for the class, so all three constructors add to the same field.
  • The getter is static too and is called with the class name: no object is needed to ask how many exist.

Choosing the right kind of field

Ask two questions for every field: is it different for each object? and can it change after it is set? The answers pick an instance field, static, final or static final.

Example 4 · Everything together: an employee ID generator

EmployeeDemo.javaJava
class Employee {    static final String PREFIX = "EMP-";    private static int nextNo = 1001;    private final String id;    private final String name;    private int salary;
    Employee(String name, int salary) {        this.name = name;        this.salary = salary;        id = PREFIX + nextNo;        nextNo++;    }
    void raise(int percent) {        salary += salary * percent / 100;    }
    static int count() {        return nextNo - 1001;    }
    void show() {        System.out.println(id + " " + name + ": Rs. " + salary);    }}
public class EmployeeDemo {    public static void main(String[] args) {        Employee e1 = new Employee("Priya", 40000);        Employee e2 = new Employee("Rahul", 35000);        e1.raise(10);        e1.show();        e2.show();        System.out.println("Employees: " + Employee.count());    }}
Output
EMP-1001 Priya: Rs. 44000
EMP-1002 Rahul: Rs. 35000
Employees: 2

What this code does

  • PREFIX is a constant, nextNo is the shared counter, id and name are fixed per object, and salary can change.
  • count() uses only a static field, so it is static; raise and show work on one employee, so they are instance methods.
  • Name, marks → instance field (per object, can change).
  • Roll number, account number → private final (per object, fixed).
  • Object counter, next ID, a fee that may change → private static.
  • Pass mark, GST rate, maximum seats → static final constant.

Methods follow the same idea: an instance method when it uses one object's fields, a static method when it needs only its parameters and static fields.

Spot the bug

Each snippet below looks almost right. Read what it should do, tap the wrong line, then check the fix. Ask two questions: does this code have an object, and may this value change?

Find the bug

Find the static and final bug

Select the line that is wrong.

setRate(15) should change the rate for every cab.

Round 1 of 5

When in doubt, trace the class

A program mixes a static block, a static counter, a final field and a shared fare. Trace it: note when the class loads, then, for each new, which fields are shared and which belong to the new object.

Trace the code

Trace a static block, a counter and a final field

class Ticket {
static int fare = 100;
private static int sold = 0;
private final int no;
static {
fare = fare + 20;
System.out.println("Counter open");
}
Ticket() {
sold++;
no = sold;
System.out.println("Ticket " + no + ": Rs. " + fare);
}
}
public class TicketTrace {
public static void main(String[] args) {
System.out.println("Start");
Ticket t1 = new Ticket();
Ticket.fare = 90;
Ticket t2 = new Ticket();
}
}

Variables

None yet.

Output

Start

Line 20main runs. Ticket has not been used yet, so its static setup has not run.

Step 1 of 11

Finish up

Mark complete & continue

Next: Must-do problems: Static and Final