Classes and objects

Parallel arrays for names, roll numbers and marks get messy fast. A class lets you describe a student once, with its data and its actions together, and then create as many student objects as you need. You'll see what new really does, where objects live, why copying a reference doesn't copy the object, what null means, and then practise with 10 problems.

Module 6 · OOP Basics⏱ 24 minBeginner10 practice problems
1 The story

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.

The blueprint (class) class Student { String name; int roll; int fees; void printCard() } new Objects made from it #1 Riya 101 1500 #2 Kabir 102 1500 #3 Meera 103 1200 Each object keeps its own name, roll, fees myphatshala.in
Riya

Sir, I sorted one array and the others didn't move with it. Now Kabir has Meera's roll number.

Arjun Sir

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.

Riya

So the class is like the blank registration form, and each filled form is an object?

Arjun Sir

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.

2 Definition

What are classes and objects?

Formal definition (write this in exams)

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.

In simple words

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

ClassThe blueprint: a new type you define with class Student { … }.
Object (instance)One thing built from the class with new.
FieldA variable declared in the class; each object has its own copy.
MethodAn action declared in the class; it works on the object it's called on.
Reference variableA variable like Student s that holds the address of an object.
nullThe value of a reference that points to no object.

Classes and objects at a glance

Defineclass Student { String name; int marks; void show() { … } }
CreateStudent s = new Student(); → one object on the heap, s refers to it
UseDot operator: s.name = "Riya"; and s.show();
Field defaults0, 0.0, false, '\u0000', null. Local variables get no default.
Copy a referenceStudent t = s; → still one object, two names for it
FilesMany 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.

3 Types and ways to use it

What goes inside a class

Fields (state)

What each object knows: name, roll, marks. Each object has its own copy.

Instance variables

Methods (behaviour)

What each object can do: printCard(), result(). They read and change that object's fields.

Instance methods

References (outside)

Code that uses the class holds references: Student a = new Student();

Student a

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);
    }
}
stock = 0 price = 0.0 inStock = false grade = 0 name = null

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

ClassObject
What it isA blueprint, a typeAn instance built from the blueprint
Created byYou, writing class Student { … }The JVM, when new Student() runs
How manyWritten onceAs many as you create
Takes heap memory?No (class info is kept in the JVM's method area)Yes, room for its own fields
ExampleStudentRiya'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.

4 Step by step

From blueprint to working object

  1. Write the class

    class Student {
        String name;
        int marks;
        void show() { System.out.println(name + " " + marks); }
    }
    Nothing runs yet. javac compiles this into Student.class. When the program first uses Student, the JVM loads that file and keeps the class description in its method area.
  2. Declare a reference variable

    Student s1;
    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.
  3. Create the object with new

    s1 = new Student();
    new asks the JVM for memory on the heap for one Student (room for name and marks), sets every field to its default (null, 0), and gives back the object's reference, which is stored in s1.
  4. Use the dot operator

    s1.name = "Riya";
    s1.marks = 82;
    s1.show();
    The dot means "follow the reference to the object". Calling s1.show() pushes a frame for show with a hidden variable this set to the same object, so name inside the method means this object's name.
  5. Copy the reference, or clear it

    Student s3 = s1;   // two names, one object
    s1 = null;          // s1 now points nowhere
    Assigning a reference copies the address, never the object. After s1 = null, calling s1.show() throws NullPointerException. The object still exists, because s3 refers to it. Once no reference is left, the garbage collector can free it.
5 See it happen

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.

Life of a Student object 6 steps
What you see class Student { String name; int marks; } Student s1 = new Student(); s1.name = "Riya"; s1.marks = 82; Student s2 = new Student(); Student s3 = s1; s3.marks = 90; s1 = null; s1.show(); // a blueprint: no object yet s1.name → null s1.marks → 0 s1.show() → Riya 82 s1.show() → Riya 82 s2.show() → null 0 s1 == s2 → false s1.show() → Riya 90 (!) s1 == s3 → true Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Student.show()" because "<local1>" is null A class describes students. None exist yet. One student with default values. The object now holds Riya's data. A second, separate object. Changing s3 changed s1 too! No object to call show() on: crash. myphatshala.in
Behind the screen Stack (main) Heap s1 s2 s3 null empty class Student (blueprint) name, marks kept in the method area no objects on the heap #1 Student name = null name = "Riya" marks = 0 marks = 82 marks = 90 #2 Student name = null marks = 0 The class is loaded; the heap has no Students. new: memory on the heap, fields set to defaults. s1 is unchanged; the object behind it changed. Two objects, each with its own fields. Two references, one object (#1). s1 holds null; #1 survives because s3 points to it. myphatshala.in
6 Real-world use

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.

Blueprint → objects on the heap 5 steps
Animated example class Ride { String from; String to; int fare; void book() } HEAP #1 Ride Kharghar → Vashi fare = 120 #2 Ride Panvel → CST fare = 450 #3 Ride Airport → Powai fare = 300 class = 1 blueprint objects so far: 0 objects so far: 1 objects so far: 2 objects so far: 3 r1.fare = 150 changes only #1 myphatshala.in
Studentroll 101CGPA 8.4

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.

Admission form→new Student()→Marksheet, ID card

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.

Catalogue rows→Product, Cart, Order→Checkout

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.

Account opened→acc.deposit(5000)→Updated balance

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.

Booking request→new Trip()→Driver assigned

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.

7 Run the code

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));
    }
}
101 | Riya | 82 | PASS 102 | Kabir | 35 | FAIL Same object? false
  • class Student { … }Not public, so it can live in the same file as public class Main. javac makes Student.class and Main.class.
  • Student a = new Student();Creates one object; a holds a reference to it.
  • a.printCard();Inside printCard, plain name and marks mean a's fields. For b.printCard() they mean b's.
  • a == bCompares references: two different objects, so false.
8 Line by line

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.

Example 1Banking · savings accounts

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.

Input
riya.deposit(5000)
kabir.withdraw(1000)   // kabir has Rs 0
Expected output
Riya: Rs 5000.0
Kabir: Rs 0.0, withdrawal ok? false

Approach

  1. Write the Account class once: fields holder and balance, plus the two methods.
  2. Create two objects with new. Each gets its own balance, starting at the default 0.0.
  3. withdraw refuses (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.

Example 2E-commerce · checkout

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.

Input
("Earphones", 799, 1)
("Phone cover", 249, 2)
Expected output
Items: 2, total Rs 1297

Approach

  1. A helper method make creates a Product, fills its fields and returns the reference.
  2. The array cart holds references to the two Product objects, not the products themselves.
  3. 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.

Example 3Logistics · delivery addresses

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.

Input
home = Pune 411001
second.shipTo = first.shipTo
second.shipTo.city = "Mumbai"
Expected output
Order 1 ships to Mumbai
Order 2 ships to Mumbai
Same Address object? true

Approach

  1. An Order object holds a reference to an Address object in its field shipTo.
  2. second.shipTo = first.shipTo copies that reference, so both orders point to one Address object.
  3. 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.

9 Quiz and revision

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();: s is 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 = s copies the reference: one object, two names. == compares references.
  • Calling a method or reading a field through null → NullPointerException at run time.
  • Only one public top-level class per file; each class becomes its own .class file.

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.

P1Easy

A Book class

Create a class Book with fields title, author and price, and a method display(). Create two books and display both.

Input
Book 1: "Wings of Fire", "A.P.J. Abdul Kalam", 350
Book 2: "Godaan", "Premchand", 199
Expected output
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();
    }
}
Wings of Fire by A.P.J. Abdul Kalam - Rs 350 Godaan by Premchand - Rs 199

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.

P2Easy

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.

Input
length = 12, width = 5
Expected output
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());
    }
}
Area: 60 Perimeter: 34

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.

P3Easy

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.

Input
c1 clicked 3 times, c2 clicked once
Expected output
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);
    }
}
c1 = 3 c2 = 1

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.

P4Easy

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.

Input
p1 = Point(2, 3); p2 = p1; p3 = new Point(2, 3); p2.x = 10
Expected output
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));
    }
}
p1.x = 10 p3.x = 2 p1 == p2: true p1 == p3: false

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.

P5Medium

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.

Input
("Riya", 82), ("Kabir", 91), ("Meera", 76), ("Aman", 88)
Expected output
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 + ")");
    }
}
Topper: Kabir (91)

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.

P6Medium

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).

Input
Delhi 42.5 °C, Shimla 18.0 °C
Expected output
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();
    }
}
Delhi: 42.5 C = 108.5 F, hot? true Shimla: 18.0 C = 64.4 F, hot? false

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.

P7Medium

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.

Input
balance = 1000; pay(300); pay(900)
Expected output
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);
    }
}
Pay 300: true, balance 700 Pay 900: false, balance 700

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.

P8Business problem

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.

Input
("Masala Dosa", 120, 2), ("Filter Coffee", 40, 3), ("Gulab Jamun", 60, 1)
Expected output
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));
    }
}
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

How it works:

  1. Each line of the bill is one object, so name, price and quantity can't get mixed up between items.
  2. The line amount is calculated by the object itself (amount()); main only adds the results.
  3. GST is applied once on the subtotal. Real billing systems round money carefully (and often use BigDecimal); here the values are exact.
P9Business problem

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.

Input
("Atta 5kg", 12, 10), ("Toor Dal 1kg", 4, 8), ("Sugar 1kg", 25, 15), ("Mustard Oil 1L", 6, 6)
Expected output
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");
    }
}
Reorder Toor Dal 1kg: 12 units Reorder Mustard Oil 1L: 6 units 2 of 4 products need reordering

How it works:

  1. Every product carries its own reorder level, so different items can have different rules.
  2. The decision (needsReorder) and the calculation (unitsToOrder) are methods of Product, so the loop in main reads like plain English.
  3. Toor Dal: 2 × 8 − 4 = 12 units. Mustard Oil is exactly at its level (6 ≤ 6), so it is included.
P10Business problem

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.

Input
("Sneha", basic 30000, HRA 12000), ("Rahul", basic 45000, HRA 18000)
Expected output
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();
    }
}
Sneha: gross Rs 42000, PF Rs 3600, net Rs 38400 Rahul: gross Rs 63000, PF Rs 5400, net Rs 57600

How it works:

  1. 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.
  2. net() reuses gross() and pf(); change the PF rule in one place and every slip follows.
  3. 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.

E-commerce · cartsFresher

“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.cart copies the reference, so both variables point to the same Cart object. Adding to newCart changed 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.

Banking · KYCFresher

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 nominee still has its default value, null. Reading .name through 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.

Fintech · onboarding1–3 years

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).

Logistics · code review1–3 years

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 Shipment class with awb, city and weight fields, and keep one Shipment[] (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.