Riya's three arrays
Riya is building the registration program for her college fest. She keeps String[] names, int[] rolls and int[] fees side by side, and index 7 in each array is supposed to be the same student. Then she sorts the names alphabetically for the printout, and suddenly every student has someone else's roll number.
Sir, I sorted one array and the others didn't move with it. Now Kabir has Meera's roll number.
Because nothing ties them together. Write a class called Student once: name, roll and fees in one place. Then each student is one object, and its data can never get separated.
So the class is like the blank registration form, and each filled form is an object?
Exactly. One form design, hundreds of filled copies. And the form can also have actions, like printCard(), that every copy knows how to do with its own data.
What are classes and objects?
A class is a user-defined type that describes the state (fields, also called instance variables) and behaviour (methods) shared by a group of objects. An object is an instance of a class, created at run time with the new operator; it gets its own copy of the instance fields and lives on the heap. A variable of a class type is a reference variable: it holds a reference to an object, or null.
A class is the blank form; an object is one filled-in form. The form says which boxes exist (name, roll, fees) and what you can do with it (print a card). Every filled form has its own values.
Words you'll meet in this lesson
class Student { … }.new.Student s that holds the address of an object.Classes and objects at a glance
| Define | class Student { String name; int marks; void show() { … } } |
|---|---|
| Create | Student s = new Student(); → one object on the heap, s refers to it |
| Use | Dot operator: s.name = "Riya"; and s.show(); |
| Field defaults | 0, 0.0, false, '\u0000', null. Local variables get no default. |
| Copy a reference | Student t = s; → still one object, two names for it |
| Files | Many classes may share one file, but only one top-level class may be public, named like the file. Each class compiles to its own .class file. |
Exam tip: "How many objects are created?" Count the new keywords that actually run. Student a = new Student(); Student b = a; creates one object and two reference variables.
What goes inside a class
Fields (state)
What each object knows: name, roll, marks. Each object has its own copy.
Methods (behaviour)
What each object can do: printCard(), result(). They read and change that object's fields.
References (outside)
Code that uses the class holds references: Student a = new Student();
Default values: a new object is never "empty garbage"
class Gadget {
int stock;
double price;
boolean inStock;
char grade;
String name;
}
public class Main {
public static void main(String[] args) {
Gadget g = new Gadget(); // fields get default values
System.out.println("stock = " + g.stock);
System.out.println("price = " + g.price);
System.out.println("inStock = " + g.inStock);
System.out.println("grade = " + (int) g.grade);
System.out.println("name = " + g.name);
}
}The char default is '\u0000', an invisible character, so we print it as a number. These defaults apply to fields only. A local variable inside a method has no default, and using it before assigning is a compile error.
Class vs object
| Class | Object | |
|---|---|---|
| What it is | A blueprint, a type | An instance built from the blueprint |
| Created by | You, writing class Student { … } | The JVM, when new Student() runs |
| How many | Written once | As many as you create |
| Takes heap memory? | No (class info is kept in the JVM's method area) | Yes, room for its own fields |
| Example | Student | Riya's record, Kabir's record |
Classic mistake: thinking Student s; creates a student. It only creates a reference variable that can point to one. No object exists until new Student() runs.
From blueprint to working object
Write the class
Nothing runs yet. javac compiles this intoclass Student { String name; int marks; void show() { System.out.println(name + " " + marks); } }Student.class. When the program first usesStudent, the JVM loads that file and keeps the class description in its method area.Declare a reference variable
One slot on main's stack frame, big enough for an address. No object exists, and as a local variable it can't be used until it's assigned.Student s1;Create the object with new
s1 = new Student();newasks the JVM for memory on the heap for one Student (room fornameandmarks), sets every field to its default (null,0), and gives back the object's reference, which is stored ins1.Use the dot operator
The dot means "follow the reference to the object". Callings1.name = "Riya"; s1.marks = 82; s1.show();s1.show()pushes a frame forshowwith a hidden variablethisset to the same object, sonameinside the method means this object's name.Copy the reference, or clear it
Assigning a reference copies the address, never the object. AfterStudent s3 = s1; // two names, one object s1 = null; // s1 now points nowheres1 = null, callings1.show()throwsNullPointerException. The object still exists, becauses3refers to it. Once no reference is left, the garbage collector can free it.
Objects and references: both views
Left: the code and what it prints. Right: reference variables on the stack and the objects they point to on the heap.
Student object 6 steps- Define: the class says every Student has a
nameandmarks. Writing it creates no student. - Create:
new Student()makes one object. Its fields start at default values:nulland0. - Fill: the dot operator sets the object's fields.
show()prints that object's data. - Another object: a second
newgives a completely separate student.s1 == s2is false. - Surprise:
s3 = s1copies the reference. Changing marks throughs3changes the one object both point to. - Crash: after
s1 = null, there is no object behinds1, so calling a method on it throwsNullPointerException.
- When the program first uses
Student, the JVM loads the class description into its method area. The heap has no Student objects yet. newreserves room on the heap for one Student and setsname = null,marks = 0. The stack variables1stores the object's reference.s1.name = "Riya"follows the arrow and writes into object #1. The arrow itself doesn't move.- The second
newcreates object #2 with its own fields.==compares the arrows, which point to different objects. s3 = s1copies the arrow. The write throughs3lands in #1, the same objects1uses.s1 = nullremoves s1's arrow. Following a null reference is impossible, so the JVM throws. #1 isn't garbage yet:s3still refers to it.
Classes and objects in real systems
Almost every Java application is a set of classes describing the things the business deals with, and objects for each real customer, order or account.
Watch it with an example: one Ride class, three bookings
A ride app writes the Ride class once. Every booking is a separate object made from it, with its own values.
- The class:
Ridedescribes what every ride has (from, to, fare) and can do (book). Writing it creates no ride yet. - new Ride(…): the first booking creates object #1 on the heap, with its own copy of every field.
- Second booking: object #2, same shape, different values.
- Third booking: object #3. One class, as many objects as there are bookings.
- Independent: changing
r1.farechanges only object #1. College ERPs, shopping carts and bank accounts all work this way: one class, thousands of objects.
1. College ERP and student records
A Student class with roll number, name, course and fees. Each admission creates one object; results, attendance and fee receipts all work on that object.
2. Online shopping
Every product on the site is a Product object (name, price, stock); each customer's cart is a Cart object holding references to products. Millions of objects, a handful of classes.
3. Banking
An Account class with account number, holder and balance, and methods deposit and withdraw. Because each account is its own object, a deposit into Riya's account can never touch Kabir's.
4. Ride and delivery apps
Each driver, rider and trip is an object. A Trip object holds references to its Driver and Rider objects, plus pickup, drop and fare.
Examples are simplified. Real classes also use constructors (Lesson 6.2), private fields with getters and setters (Lesson 7.1), and data loaded from databases.
Report cards, the object way
class Student {
String name;
int roll;
int marks;
void printCard() {
System.out.println(roll + " | " + name + " | " + marks + " | " + result());
}
String result() {
return marks >= 40 ? "PASS" : "FAIL";
}
}
public class Main {
public static void main(String[] args) {
Student a = new Student();
a.name = "Riya";
a.roll = 101;
a.marks = 82;
Student b = new Student();
b.name = "Kabir";
b.roll = 102;
b.marks = 35;
a.printCard();
b.printCard();
System.out.println("Same object? " + (a == b));
}
}class Student { … }Not public, so it can live in the same file aspublic class Main. javac makesStudent.classandMain.class.Student a = new Student();Creates one object;aholds a reference to it.a.printCard();InsideprintCard, plainnameandmarksmean a's fields. Forb.printCard()they mean b's.a == bCompares references: two different objects, sofalse.
One phone, two references
Watch the object on the heap change while the reference variables stay the same. Each method call pushes a frame with its own this.
Worked examples: real problems, solved and traced in memory
Three everyday business problems solved with classes and objects. Run each solution, then step through it and watch objects (#1, #2 …) appear on the heap, their fields change, and a frame with this pushed for every method call.
Two accounts, one class
Problem statement
A bank opens accounts for Riya and Kabir. Riya deposits Rs 5,000. Kabir, whose account is empty, tries to withdraw Rs 1,000. Model the account as a class with deposit and withdraw methods and print both balances.
riya.deposit(5000) kabir.withdraw(1000) // kabir has Rs 0
Riya: Rs 5000.0 Kabir: Rs 0.0, withdrawal ok? false
Approach
- Write the
Accountclass once: fieldsholderandbalance, plus the two methods. - Create two objects with
new. Each gets its ownbalance, starting at the default 0.0. withdrawrefuses (returns false) when the amount is more than the balance, so the rule lives with the data.
Solution: run it live
What happens in memory, step by step
Recorded from the real JVM: press Next to execute one line at a time. Watch method calls push and pop frames on the stack, and objects (numbered #1, #2 …) appear on the heap.
Cart total from Product objects
Problem statement
A customer's cart has earphones (Rs 799 × 1) and phone covers (Rs 249 × 2). Store each item as a Product object in an array and print the number of items and the total.
("Earphones", 799, 1)
("Phone cover", 249, 2)Items: 2, total Rs 1297
Approach
- A helper method
makecreates a Product, fills its fields and returns the reference. - The array
cartholds references to the two Product objects, not the products themselves. - Each product calculates its own line total with
lineTotal(); main just adds them up.
Solution: run it live
What happens in memory, step by step
Recorded from the real JVM: press Next to execute one line at a time. Watch method calls push and pop frames on the stack, and objects (numbered #1, #2 …) appear on the heap.
The shared address bug
Problem statement
Two orders are placed from the same home address in Pune. Later, the customer changes the delivery city of order 2 to Mumbai. Find out why order 1 also starts showing Mumbai.
home = Pune 411001 second.shipTo = first.shipTo second.shipTo.city = "Mumbai"
Order 1 ships to Mumbai Order 2 ships to Mumbai Same Address object? true
Approach
- An
Orderobject holds a reference to anAddressobject in its fieldshipTo. second.shipTo = first.shipTocopies that reference, so both orders point to one Address object.- Changing the city through either order changes the single shared object. The fix is to give order 2 its own
new Address().
Solution: run it live
What happens in memory, step by step
Recorded from the real JVM: press Next to execute one line at a time. Watch method calls push and pop frames on the stack, and objects (numbered #1, #2 …) appear on the heap.
Check yourself
Quick revision
Lesson 6.1 in one screen
- Class = blueprint (fields + methods). Object = instance created with
new, stored on the heap. Student s = new Student();:sis a reference variable holding the object's address.- Fields get defaults (0, 0.0, false, '\u0000', null); local variables don't.
- Use the dot operator:
s.name,s.show(). Methods work on the object they're called on. t = scopies the reference: one object, two names.==compares references.- Calling a method or reading a field through
null→NullPointerExceptionat run time. - Only one public top-level class per file; each class becomes its own
.classfile.
Interview and viva questions
What is the difference between a class and an object?
A class is a blueprint written in code: it declares fields and methods. An object is a concrete instance created from that class at run time with new; it occupies heap memory and has its own field values. One class can produce any number of objects.
What does the new keyword do?
It asks the JVM to allocate memory for a new object of the class on the heap, sets all its fields to default values, runs the constructor (Lesson 6.2), and returns a reference to the object, which is usually stored in a variable.
Where are objects and reference variables stored?
Objects always live on the heap. A local reference variable lives in the method's stack frame and holds only the object's address. A reference that is a field lives inside its object on the heap.
What is a NullPointerException and how do you avoid it?
It's thrown when code uses a null reference as if it pointed to an object, for example calling a method or reading a field. Avoid it by creating objects before use, checking for null where a value may be missing, and not leaving reference fields unset. Since Java 15, the message also says exactly which reference was null (helpful NullPointerException messages).
Does Student b = a; create a copy of the object?
No. It copies the reference, so a and b point to the same object and changes through either are visible through both. To get a separate object you must create one with new and copy the field values.
Practice problems
Each problem asks you to design a small class and create objects from it. Decide the fields and methods on paper first, then code. The last three are real business tasks.
A Book class
Create a class Book with fields title, author and price, and a method display(). Create two books and display both.
Book 1: "Wings of Fire", "A.P.J. Abdul Kalam", 350 Book 2: "Godaan", "Premchand", 199
Wings of Fire by A.P.J. Abdul Kalam - Rs 350 Godaan by Premchand - Rs 199
Show solution and explanation
class Book {
String title;
String author;
int price;
void display() {
System.out.println(title + " by " + author + " - Rs " + price);
}
}
public class Main {
public static void main(String[] args) {
Book b1 = new Book();
b1.title = "Wings of Fire";
b1.author = "A.P.J. Abdul Kalam";
b1.price = 350;
Book b2 = new Book();
b2.title = "Godaan";
b2.author = "Premchand";
b2.price = 199;
b1.display();
b2.display();
}
}How it works: one class, two objects. Inside display(), title means the title of whichever object the method was called on: b1's the first time, b2's the second time.
Rectangle area and perimeter
Write a class Rectangle with length and width, and methods area() and perimeter() that return the results. Print both for a 12 × 5 rectangle.
length = 12, width = 5
Area: 60 Perimeter: 34
Show solution and explanation
class Rectangle {
int length;
int width;
int area() {
return length * width;
}
int perimeter() {
return 2 * (length + width);
}
}
public class Main {
public static void main(String[] args) {
Rectangle r = new Rectangle();
r.length = 12;
r.width = 5;
System.out.println("Area: " + r.area());
System.out.println("Perimeter: " + r.perimeter());
}
}How it works: the methods need no parameters because the data they need is already inside the object. Returning the value (instead of printing inside the method) lets the caller decide what to do with it.
Independent counters
A Counter class has a field count and a method click() that adds 1. Create two counters, click the first 3 times and the second once, and print both counts.
c1 clicked 3 times, c2 clicked once
c1 = 3 c2 = 1
Show solution and explanation
class Counter {
int count;
void click() {
count++;
}
}
public class Main {
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
c1.click();
c1.click();
c1.click();
c2.click();
System.out.println("c1 = " + c1.count);
System.out.println("c2 = " + c2.count);
}
}How it works: count starts at its default value 0 in both objects. Every object has its own copy of each field, so clicking c1 never changes c2.
Spot the shared object
Predict the output, then run it. p2 is assigned from p1, and p3 is a new object with the same values.
p1 = Point(2, 3); p2 = p1; p3 = new Point(2, 3); p2.x = 10
p1.x = 10 p3.x = 2 p1 == p2: true p1 == p3: false
Show solution and explanation
class Point {
int x;
int y;
}
public class Main {
public static void main(String[] args) {
Point p1 = new Point();
p1.x = 2;
p1.y = 3;
Point p2 = p1;
Point p3 = new Point();
p3.x = 2;
p3.y = 3;
p2.x = 10;
System.out.println("p1.x = " + p1.x);
System.out.println("p3.x = " + p3.x);
System.out.println("p1 == p2: " + (p1 == p2));
System.out.println("p1 == p3: " + (p1 == p3));
}
}How it works: only two objects exist. p2 = p1 copies the reference, so changing p2.x changes the object p1 sees. p3 is a separate object: equal values, but p1 == p3 is false because == compares references.
Topper from an array of students
Store four students in a Student[] array and print the name and marks of the topper. Use a helper method make(name, marks) that creates and returns a filled Student.
("Riya", 82), ("Kabir", 91), ("Meera", 76), ("Aman", 88)Topper: Kabir (91)
Show solution and explanation
class Student {
String name;
int marks;
}
public class Main {
static Student make(String name, int marks) {
Student s = new Student();
s.name = name;
s.marks = marks;
return s;
}
public static void main(String[] args) {
Student[] cls = {
make("Riya", 82), make("Kabir", 91), make("Meera", 76), make("Aman", 88)
};
Student top = cls[0];
for (Student s : cls) {
if (s.marks > top.marks) {
top = s;
}
}
System.out.println("Topper: " + top.name + " (" + top.marks + ")");
}
}How it works: the array holds 4 references, each pointing to a Student object. top is just another reference that we move to whichever object is best so far; no student is copied. make returns the reference of the object it created, so the object survives after the method's frame is popped.
Temperature converter object
A Temperature object stores a value in Celsius. Add methods toFahrenheit() and isHot() (above 35 °C). Test it for Delhi (42.5) and Shimla (18.0).
Delhi 42.5 °C, Shimla 18.0 °C
Delhi: 42.5 C = 108.5 F, hot? true Shimla: 18.0 C = 64.4 F, hot? false
Show solution and explanation
class Temperature {
String city;
double celsius;
double toFahrenheit() {
return celsius * 9 / 5 + 32;
}
boolean isHot() {
return celsius > 35;
}
void report() {
System.out.println(city + ": " + celsius + " C = " + toFahrenheit() + " F, hot? " + isHot());
}
}
public class Main {
public static void main(String[] args) {
Temperature delhi = new Temperature();
delhi.city = "Delhi";
delhi.celsius = 42.5;
Temperature shimla = new Temperature();
shimla.city = "Shimla";
shimla.celsius = 18.0;
delhi.report();
shimla.report();
}
}How it works: report() calls toFahrenheit() and isHot() without any object name in front. Inside a method, calling another method of the same class works on the same object, so delhi's report uses delhi's temperature.
Safe withdrawal
Write a Wallet class with balance and a method pay(amount) that returns true and deducts the amount only if the balance is enough. Try paying 300, then 900, from a wallet with Rs 1000.
balance = 1000; pay(300); pay(900)
Pay 300: true, balance 700 Pay 900: false, balance 700
Show solution and explanation
class Wallet {
int balance;
boolean pay(int amount) {
if (amount > balance) {
return false;
}
balance -= amount;
return true;
}
}
public class Main {
public static void main(String[] args) {
Wallet w = new Wallet();
w.balance = 1000;
System.out.println("Pay 300: " + w.pay(300) + ", balance " + w.balance);
System.out.println("Pay 900: " + w.pay(900) + ", balance " + w.balance);
}
}How it works: the rule "never go below zero" lives inside the class, next to the data it protects, so every caller gets the same check. In Lesson 7.1 you'll make balance private so nobody can skip the method and change it directly.
Restaurant bill with GST
A restaurant order has three items. Create a MenuItem class (name, price, quantity) with a method amount(). Print each line, the subtotal, 5% GST and the grand total.
("Masala Dosa", 120, 2), ("Filter Coffee", 40, 3), ("Gulab Jamun", 60, 1)Masala Dosa x2 = Rs 240 Filter Coffee x3 = Rs 120 Gulab Jamun x1 = Rs 60 Subtotal: Rs 420 GST 5%: Rs 21.0 Total: Rs 441.0
Show solution and explanation
class MenuItem {
String name;
int price;
int qty;
int amount() {
return price * qty;
}
}
public class Main {
static MenuItem item(String name, int price, int qty) {
MenuItem m = new MenuItem();
m.name = name;
m.price = price;
m.qty = qty;
return m;
}
public static void main(String[] args) {
MenuItem[] order = {
item("Masala Dosa", 120, 2),
item("Filter Coffee", 40, 3),
item("Gulab Jamun", 60, 1)
};
int subtotal = 0;
for (MenuItem m : order) {
System.out.println(m.name + " x" + m.qty + " = Rs " + m.amount());
subtotal += m.amount();
}
double gst = subtotal * 0.05;
System.out.println("Subtotal: Rs " + subtotal);
System.out.println("GST 5%: Rs " + gst);
System.out.println("Total: Rs " + (subtotal + gst));
}
}How it works:
- Each line of the bill is one object, so name, price and quantity can't get mixed up between items.
- The line amount is calculated by the object itself (
amount()); main only adds the results. - GST is applied once on the subtotal. Real billing systems round money carefully (and often use
BigDecimal); here the values are exact.
Low-stock alert for a kirana store
A store tracks products with name, stock and reorder level. Print every product whose stock is at or below its reorder level, and how many units to order to bring it back to twice the reorder level.
("Atta 5kg", 12, 10), ("Toor Dal 1kg", 4, 8), ("Sugar 1kg", 25, 15), ("Mustard Oil 1L", 6, 6)Reorder Toor Dal 1kg: 12 units Reorder Mustard Oil 1L: 6 units 2 of 4 products need reordering
Show solution and explanation
class Product {
String name;
int stock;
int reorderLevel;
boolean needsReorder() {
return stock <= reorderLevel;
}
int unitsToOrder() {
return 2 * reorderLevel - stock;
}
}
public class Main {
static Product p(String name, int stock, int level) {
Product x = new Product();
x.name = name;
x.stock = stock;
x.reorderLevel = level;
return x;
}
public static void main(String[] args) {
Product[] shelf = {
p("Atta 5kg", 12, 10), p("Toor Dal 1kg", 4, 8),
p("Sugar 1kg", 25, 15), p("Mustard Oil 1L", 6, 6)
};
int count = 0;
for (Product item : shelf) {
if (item.needsReorder()) {
System.out.println("Reorder " + item.name + ": " + item.unitsToOrder() + " units");
count++;
}
}
System.out.println(count + " of " + shelf.length + " products need reordering");
}
}How it works:
- Every product carries its own reorder level, so different items can have different rules.
- The decision (
needsReorder) and the calculation (unitsToOrder) are methods of Product, so the loop in main reads like plain English. - Toor Dal: 2 × 8 − 4 = 12 units. Mustard Oil is exactly at its level (6 ≤ 6), so it is included.
Monthly salary slip
Create an Employee class with name, basic pay and HRA. Add methods for gross pay, PF (12% of basic) and net pay (gross − PF). Print slips for two employees.
("Sneha", basic 30000, HRA 12000), ("Rahul", basic 45000, HRA 18000)Sneha: gross Rs 42000, PF Rs 3600, net Rs 38400 Rahul: gross Rs 63000, PF Rs 5400, net Rs 57600
Show solution and explanation
class Employee {
String name;
int basic;
int hra;
int gross() {
return basic + hra;
}
int pf() {
return basic * 12 / 100;
}
int net() {
return gross() - pf();
}
void printSlip() {
System.out.println(name + ": gross Rs " + gross() + ", PF Rs " + pf() + ", net Rs " + net());
}
}
public class Main {
public static void main(String[] args) {
Employee e1 = new Employee();
e1.name = "Sneha";
e1.basic = 30000;
e1.hra = 12000;
Employee e2 = new Employee();
e2.name = "Rahul";
e2.basic = 45000;
e2.hra = 18000;
e1.printSlip();
e2.printSlip();
}
}How it works:
- Only the inputs (basic, HRA) are stored as fields. Gross, PF and net are calculated by methods, so they can never be out of date.
net()reusesgross()andpf(); change the PF rule in one place and every slip follows.- Sneha: 42000 − 3600 = 38400. Real payroll has many more components (tax, professional tax, allowances); this keeps the structure.
Real-world scenario questions (asked in company interviews)
Objects and references are where many real production bugs start. Decide your answer first, then open the model answer.
“Two customers, one cart”
For a "buy again" feature, a developer writes Cart newCart = oldOrder.cart; and then adds today's items to newCart. Customers complain that their past order history now shows items they never bought in that order. What went wrong?
The interviewer is checking: do you know that assigning a reference doesn't copy the object?
Show a strong answer
newCart = oldOrder.cartcopies the reference, so both variables point to the same Cart object. Adding tonewCartchanged the old order's cart.- Fix: create a new object (
new Cart()) and copy the items into it, so the old order stays untouched. - Past orders should ideally never change at all: store them as read-only snapshots.
Avoid: saying "Java copied the cart wrongly". Java never copies objects on assignment.
The statement job that crashes on one customer
A nightly job prints customer.nominee.name on each account statement. It runs fine for months, then crashes with a NullPointerException on a newly opened account. Why, and how would you fix it?
The interviewer is checking: do you know default null fields and defensive handling of optional data?
Show a strong answer
- The new customer has no nominee yet, so the reference field
nomineestill has its default value,null. Reading.namethrough null throws. - Fix: check before use,
if (customer.nominee != null), and print "Not registered" otherwise. - Also decide which fields are mandatory and make sure they are always set when the object is created (constructors, Lesson 6.2).
- One bad record shouldn't stop the whole batch: log it and continue with the next account.
Avoid: wrapping everything in a catch that hides the error. Handle the missing value on purpose.
Duplicate PAN check that never finds duplicates
Sign-up code builds a Customer object from the form and checks if (newCustomer == existingCustomer) against each stored customer to block duplicate PAN numbers. Duplicates are never caught, even when every field matches. Explain.
The interviewer is checking: do you understand reference equality versus comparing data?
Show a strong answer
==on references asks "same object?". The form creates a brand-new object, so it is never the same object as one already stored, whatever its fields.- Compare the identifying data instead:
newCustomer.pan.equals(existing.pan)(String comparison from Lesson 4.4). - In a real system, put a unique constraint on PAN in the database too, so two parallel sign-ups can't both succeed.
Avoid: comparing every field by hand everywhere. Later you'll define equals() once in the class (Lesson 10.3).
Parallel arrays that went out of sync
A shipment tracker keeps String[] awb, String[] city and int[] weight, linked by index. A teammate sorted weight for a "heaviest first" report, and now parcels show the wrong cities. You're asked to review the design. What do you propose?
The interviewer is checking: can you see why related data belongs in one object?
Show a strong answer
- Sorting one array moved its values but not the matching entries in the others. Nothing in the code ties index 5 of each array together.
- Create a
Shipmentclass withawb,cityandweightfields, and keep oneShipment[](or a list). - Sorting the shipments now moves whole objects, so the data can't separate. Adding a new field means changing one class, not every array.
Avoid: "Sort all three arrays the same way." It works until someone forgets one.