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 mistakes with classes and objects fall into two groups. Some stop javac, and the message names the line. Others compile and run, but crash or print a wrong answer, and you find them by tracing which variable leads to which object.
Mistakes and fixes at a glance
Most compile errors in this module name the exact line. The most common one is a misspelt name: javac looks inside the class, finds no field or method with that name, and reports cannot find symbol.
Example 1 · cannot find symbol: a misspelt field
class Student { String name; int marks;}
public class SymbolDemo { public static void main(String[] args) { Student s = new Student(); s.name = "Aarav"; s.mark = 88; System.out.println(s.name + " " + s.marks); }}SymbolDemo.java:10: error: cannot find symbol
s.mark = 88;
^
symbol: variable mark
location: variable s of type Student
1 errorWhat this code does
- The field is
marks, but line 10 saysmark.javaclooks inside the Student class and finds no field with that name. location: variable s of type Studenttells you where it looked. Fix the spelling:s.marks = 88;.
Review: Write your first class (opens in a new tab). The other common mistakes, each with what goes wrong and the fix:
variable s might not have been initialized→Student s;has no object yet →Student s = new Student();. Review: Create objects with new (opens in a new tab)<identifier> expected→ a step such asmarks = 90;sits in the class body → move it into a method, or writeint marks = 90;. Review: Write your first class (opens in a new tab)- A field does not change → the method wrote to a local variable →
marks = marks + bonus;. Review: State and behaviour (opens in a new tab) - A "copy" changes the original →
b = ashares one object →newplus each field copied. Review: Many objects, references and null (opens in a new tab) NullPointerException→ a slot or variable is stillnull→ create the object first, or check!= nullwhen empty is normal. Review: Many objects, references and null (opens in a new tab)
Why main needs an object
main writes total = 90; and javac refuses. main is static: it belongs to the class and has no object, while a field without static lives only inside an object, so Java asks "whose total?"
Example 2 · A field used from main without an object
public class MarksApp { int total;
public static void main(String[] args) { total = 90; System.out.println(total); }}MarksApp.java:5: error: non-static variable total cannot be referenced from a static context
total = 90;
^
MarksApp.java:6: error: non-static variable total cannot be referenced from a static context
System.out.println(total);
^
2 errorsWhat this code does
totalbelongs to a MarksApp object, butmainis static and has no object, so both lines fail.- Fix:
MarksApp app = new MarksApp();, then useapp.totalon both lines. The program then prints90.
Adding static everywhere is not the fix: there would be one total for the whole program, never one per object. When static is the right choice is covered in Static and final (opens in a new tab).
One object in every slot
A loop fills three slots, yet every slot prints Kavya. The rule behind it: one new builds one object, so filling an array with different objects needs a new on every pass of the loop.
Example 3 · Silent bug: one object in every slot
class Student { String name;}
public class OneObjectBug { public static void main(String[] args) { String[] names = {"Rohan", "Diya", "Kavya"}; Student[] list = new Student[3]; Student s = new Student(); for (int i = 0; i < list.length; i++) { s.name = names[i]; list[i] = s; } for (int i = 0; i < list.length; i++) { System.out.println(list[i].name); } }}Kavya Kavya Kavya
What this code does
- Only one
newran, before the loop, so all three slots hold a reference to that single object. - Each pass overwrites the same
name, so the last value, Kavya, is all you see. No error, just a wrong answer.
Example 4 · The fix: new inside the loop
class Student { String name;}
public class OneObjectFix { public static void main(String[] args) { String[] names = {"Rohan", "Diya", "Kavya"}; Student[] list = new Student[3]; for (int i = 0; i < list.length; i++) { Student s = new Student(); s.name = names[i]; list[i] = s; } for (int i = 0; i < list.length; i++) { System.out.println(list[i].name); } }}Rohan Diya Kavya
What this code does
- Now
new Student()runs once per pass, so each slot gets its own object. sis a fresh local variable on each pass; the array keeps the references, so all three objects stay alive.
Spot the bug
Each snippet below looks almost right. Read what it should do, tap the wrong line, then check the fix. Ask three questions: is there an object, is it the object you think, and is every answer kept?
Find the bug
Find the classes and objects bug
Select the line that is wrong.
This should store two names in the array.
Round 1 of 5When in doubt, trace the references
A program with shared references prints numbers you did not expect. Trace it: for every variable, write which object it leads to; for every object, write its fields; then update both line by line.
Trace the code
Trace three variables and two objects
Variables
- a
- bottle 1, 0 ml
Output
(nothing printed yet)Line 7new builds bottle 1 with ml = 0, and a holds its reference.
Module quiz
Questions from the whole module. Your first answer is your score.
Problems
Graded easy to hard, using everything from this module.
Try each one yourself first. Use the hint if you get stuck. Mark it as done when it works.
Exercise 1· Easy
This program has two compile errors. Fix them so it prints the expected output.
class Movie { String title; int rating;}
public class MovieFix { public static void main(String[] args) { Movie m; m.title = "3 Idiots"; m.ratting = 9; System.out.println(m.title + ": " + m.rating + "/10"); }}3 Idiots: 9/10
Exercise 2· Easy
Fix the static context errors without adding the word static anywhere.
public class Attendance { int present;
void markPresent() { present++; }
public static void main(String[] args) { markPresent(); markPresent(); System.out.println("Present days: " + present); }}Present days: 2
Exercise 3· Medium
Every city prints as Pune. Fix the loop so each slot gets its own object.
class City { String name; int pin;}
public class CityFix { public static void main(String[] args) { String[] names = {"Chennai", "Jaipur", "Pune"}; int[] pins = {600001, 302001, 411001}; City[] cities = new City[3]; City c = new City(); for (int i = 0; i < cities.length; i++) { c.name = names[i]; c.pin = pins[i]; cities[i] = c; } for (int i = 0; i < cities.length; i++) { System.out.println(cities[i].name + " " + cities[i].pin); } }}Chennai 600001 Jaipur 302001 Pune 411001
Exercise 4· Medium
Write a class Player with name and score, and a method addScore(int points). Make an array of 3 players (Aarav, Diya, Rohan). Give Aarav 30 then 20, Diya 45, Rohan 10 then 25 then 5. Print every player, then the team total and the top scorer.
Aarav: 50 Diya: 45 Rohan: 40 Team total: 135 Top scorer: Aarav
Exercise 5· Medium
This library program has two bugs: it crashes, and after the crash is fixed the fine is still 0. Fix both.
class Member { String name; int fine;
void lateReturn(int days) { int newFine = fine + days * 2; }}
public class FineDemo { public static void main(String[] args) { Member[] members = new Member[2]; members[0] = new Member(); members[0].name = "Kavya"; members[1].name = "Arjun"; members[0].lateReturn(3); members[1].lateReturn(5); members[1].lateReturn(1); for (int i = 0; i < members.length; i++) { System.out.println(members[i].name + ": Rs. " + members[i].fine); } }}Kavya: Rs. 6 Arjun: Rs. 12
Exercise 6· Medium
Mess wallets: write a class Wallet with owner and balance. In the Demo class write static boolean transfer(Wallet from, Wallet to, int amount): it moves the money and returns true only if from has enough, otherwise it changes nothing and returns false. Aarav has Rs. 500 and Priya Rs. 300. Try 200 from Aarav to Priya, then 600 from Priya to Aarav, printing OK or FAILED for each, then both balances.
Aarav -> Priya Rs. 200: OK Priya -> Aarav Rs. 600: FAILED Aarav: Rs. 300 Priya: Rs. 500
Exercise 7· Hard
Trace this program and write exactly what it prints. Watch shared references, the method call and the default values.
class Cup { int ml;
void pour(Cup other, int amount) { ml = ml - amount; other.ml = other.ml + amount; }}
public class CupTrace { public static void main(String[] args) { Cup a = new Cup(); Cup b = new Cup(); Cup c = a; a.ml = 300; a.pour(b, 100); c.pour(b, 50); b.pour(c, 30); Cup[] shelf = {a, b, c}; for (int i = 0; i < shelf.length; i++) { System.out.println(shelf[i].ml); } }}180 120 180
Exercise 8· Hard
Canteen tokens: write a class Order with student, amount and ready. Keep Order[] orders = new Order[4];. Write static helpers: place(orders, student, amount) puts the order in the first empty slot and prints its token (slot + 1); markReady(orders, token); and showPending(orders) that prints every order not yet ready and the pending total. Place Aarav 60, Diya 45, Rohan 80, mark token 2 ready, then show pending.
Token 1 for Aarav Token 2 for Diya Token 3 for Rohan Pending: token 1 Aarav Rs. 60 Pending: token 3 Rohan Rs. 80 Pending total: Rs. 140
Interview questions
Questions interviewers ask on this topic.
Finish up
Mark complete & continue
Next: Must-do problems: Classes and Objects