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
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(); }}RentDemo.java:9: error: non-static variable rent cannot be referenced from a static context
System.out.println("Rent: Rs. " + rent);
^
1 errorWhat this code does
printRent()is static, so it runs with no Room object, whilerentbelongs to one room: Java cannot tell whose.- Fix: remove
staticand callr.printRent();. The method is about one room, so it is an instance method; the program then printsRent: 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:
cannot assign a value to final variable id→ a method or setter changes a final field → leave it alone, or dropfinalif it really must change. Review: final variables and constants (opens in a new tab)variable accountNo might not have been initialized→ a constructor skips a blank final → set it there, or start withthis(...). Review: final variables and constants (opens in a new tab)- Every object shows a count of 1 → the counter has no
static→private static int count. Review: Static variables (opens in a new tab) - Every object shows the last name set → a per-object field was made
static→ removestatic. Review: Instance members and static members (opens in a new tab) - A change through one object shows in all of them → that field is static → write
ClassName.field, or make it an instance field. Review: Static variables (opens in a new tab) - Setup prints once per object → it sits in the constructor → move it to
static { }. Review: Static blocks (opens in a new tab) - A "final" array still changes →
finalfixes only the reference, not the contents. Review: final variables and constants (opens in a new tab)
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
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()); }}Students: 1
What this code does
countis an instance field, so each object has its owncountthat goes from 0 to 1.- Fix:
private static int count = 0;and astaticgetter called asStudent.getCount().
Example 3 · The fix: one static counter
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()); }}Students: 3
What this code does
staticgives onecountfor 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
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()); }}EMP-1001 Priya: Rs. 44000 EMP-1002 Rahul: Rs. 35000 Employees: 2
What this code does
PREFIXis a constant,nextNois the shared counter,idandnameare fixed per object, andsalarycan change.count()uses only a static field, so it is static;raiseandshowwork 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 finalconstant.
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 5When 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
Variables
None yet.
Output
Start
Line 20main runs. Ticket has not been used yet, so its static setup has not run.
Finish up
Mark complete & continue
Next: Must-do problems: Static and Final