LearnFrenzy
Sign in Take a free test

Java Programming · Topic 7 of 28

Classes and Objects

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

Classes and Objects · Study material

Classes and objects are the heart of Java. A class is a blueprint that describes what something has (fields) and what it does (methods); an object is one concrete thing built from that blueprint, with its own values. A BankAccount class can create millions of account objects; a Product class models every item in a shop. Understanding how objects are created with new, how variables hold references to them, what null means, and the difference between == and equals() is essential before learning constructors, encapsulation, inheritance and polymorphism – and it is tested in every Java interview. This page explains it all with programs you can run. Then practise with 60 questions – 20 MCQs, 20 predict-the-output puzzles, 10 find-the-error programs and 10 complete programs – compiled and run on Java 21.

On this page

  • Classes, objects, fields and methods
  • Creating objects with new; reference variables and aliasing
  • null and NullPointerException
  • Identity (==) vs equality (equals), toString and hashCode
  • Arrays and lists of objects; passing and returning objects
  • Garbage collection; nested, inner, local and anonymous classes

Classes, objects, fields and methods

A class groups fields (the data every object carries) and methods (the operations on that data). new BankAccount() allocates an object on the heap with its own copy of every field (initialised to default values) and returns a reference to it. Methods use the fields of the object they are called on.

// A class is a blueprint: it declares the state (fields) and behaviour (methods) of its objects
class BankAccount {
    String owner;          // fields (instance variables) – each object has its own copy
    double balance;

    void deposit(double amount) {           // methods work on THIS object's fields
        if (amount > 0) balance += amount;
    }

    boolean withdraw(double amount) {
        if (amount <= 0 || amount > balance) return false;
        balance -= amount;
        return true;
    }

    String summary() {
        return owner + ": Rs " + balance;
    }
}

public class Main {
    public static void main(String[] args) {
        BankAccount a = new BankAccount();      // new creates an OBJECT on the heap
        a.owner = "Asha";
        a.deposit(5000);
        BankAccount b = new BankAccount();      // a second, independent object
        b.owner = "Ravi";
        b.deposit(1200);
        System.out.println(a.withdraw(2000) + " " + b.withdraw(2000));
        System.out.println(a.summary() + " | " + b.summary());
    }
}

Output

true false
Asha: Rs 3000.0 | Ravi: Rs 1200.0

Reference variables

A variable of a class type does not contain the object – it contains a reference (an address) to it. Assigning one reference variable to another makes both refer to the same object (aliasing). null means "refers to no object"; using it with . throws NullPointerException.

class Point {
    int x, y;
}

public class Main {
    public static void main(String[] args) {
        Point p = new Point();
        p.x = 3; p.y = 4;
        Point q = p;                 // copies the REFERENCE: p and q are the same object
        q.x = 10;
        Point r = new Point();       // a different object
        r.x = 10; r.y = 4;

        System.out.println(p.x + " " + (p == q) + " " + (p == r) + " " + p.equals(r));

        q = null;                    // q no longer refers to anything; p still does
        System.out.println(p.x + " " + (q == null));
        try {
            System.out.println(q.x);
        } catch (NullPointerException e) {
            System.out.println("NullPointerException");
        }
    }
}

Output

10 true false false
10 true
NullPointerException

toString, equals and hashCode

Every class inherits these from java.lang.Object. The default toString() prints the class name and a hash (Product@1b6d3586), and the default equals() is the same as ==. Override toString() for readable output, and override equals() together with hashCode() when two objects with the same content should count as equal – for example as keys in a HashMap. (Records, covered later, generate all three automatically.)

import java.util.Objects;

class Product {
    String name;
    double price;

    @Override
    public String toString() {                // used by println and string concatenation
        return name + " (Rs " + price + ")";
    }

    @Override
    public boolean equals(Object o) {          // "same content" instead of "same object"
        if (this == o) return true;
        if (!(o instanceof Product other)) return false;
        return Double.compare(price, other.price) == 0 && Objects.equals(name, other.name);
    }

    @Override
    public int hashCode() {                    // equal objects must have equal hash codes
        return Objects.hash(name, price);
    }
}

public class Main {
    public static void main(String[] args) {
        Product a = new Product(); a.name = "Pen"; a.price = 20;
        Product b = new Product(); b.name = "Pen"; b.price = 20;
        System.out.println(a);
        System.out.println((a == b) + " " + a.equals(b) + " " + (a.hashCode() == b.hashCode()));
    }
}

Output

Pen (Rs 20.0)
false true true

Arrays and lists of objects

new Student[3] creates an array of three references, all null – no Student objects exist until you create them. Collections such as ArrayList<Student> work the same way: they store references.

import java.util.ArrayList;
import java.util.List;

class Student {
    String name;
    int marks;

    Student(String name, int marks) { this.name = name; this.marks = marks; }   // constructors: next topic

    boolean passed() { return marks >= 40; }
}

public class Main {
    public static void main(String[] args) {
        Student[] arr = new Student[3];               // 3 REFERENCES, all null – no Student objects yet
        System.out.println(arr[0]);
        arr[0] = new Student("Asha", 91);
        arr[1] = new Student("Ravi", 35);
        arr[2] = new Student("Meena", 78);

        int passed = 0;
        for (Student s : arr) if (s.passed()) passed++;

        List<Student> toppers = new ArrayList<>();
        for (Student s : arr) if (s.marks > 75) toppers.add(s);
        System.out.println(passed + " passed, toppers: " + toppers.size() + " " + toppers.get(0).name);
    }
}

Output

null
2 passed, toppers: 2 Asha

Passing and returning objects

A method that receives an object gets a copy of the reference, so it can change the caller's object. Methods can also return new objects – a style that avoids surprising side effects.

class Rect {
    double w, h;
    Rect(double w, double h) { this.w = w; this.h = h; }
    double area() { return w * h; }

    Rect scaled(double factor) {                // returns a NEW object, leaves this one alone
        return new Rect(w * factor, h * factor);
    }

    boolean isBiggerThan(Rect other) {          // takes another object of the same class
        return area() > other.area();
    }
}

public class Main {
    static void grow(Rect r) { r.w += 1; }       // changes the caller's object

    public static void main(String[] args) {
        Rect a = new Rect(2, 3);
        Rect b = a.scaled(2);
        grow(a);
        System.out.println(a.w + "x" + a.h + " " + b.w + "x" + b.h + " " + a.area() + " " + b.isBiggerThan(a));
    }
}

Output

3.0x3.0 4.0x6.0 9.0 true

Nested, inner, local and anonymous classes

KindDeclaredHas access to an outer object?Typical use
Static nested classstatic class X inside a classnohelpers that belong with the outer class (Map.Entry, builders)
Inner classclass X inside a classyes (created with outer.new X())iterators, objects tied to one outer instance
Local classinside a methodyes, plus effectively final localsrare; small helpers
Anonymous classnew Interface() { … }yesone-off implementations (now usually lambdas)
import java.util.Arrays;
import java.util.Comparator;

public class Main {
    private int base = 100;

    static class Counter {                       // static nested class: no link to an outer object
        int count;
        void inc() { count++; }
    }

    class Adder {                                // inner class: belongs to an outer object, sees its fields
        int add(int x) { return base + x; }
    }

    public static void main(String[] args) {
        Counter c = new Counter();
        c.inc(); c.inc();

        Main outer = new Main();
        Main.Adder adder = outer.new Adder();    // inner objects need an outer object

        class Square {                           // local class: visible only in this method
            int of(int n) { return n * n; }
        }

        String[] words = {"banana", "fig", "apple"};
        Arrays.sort(words, new Comparator<String>() {      // anonymous class: a one-off implementation
            @Override
            public int compare(String a, String b) { return a.length() - b.length(); }
        });

        System.out.println(c.count + " " + adder.add(5) + " " + new Square().of(7) + " " + Arrays.toString(words));
    }
}

Output

2 105 49 [fig, apple, banana]

Objects and memory

Objects live on the heap; local reference variables live in the method's stack frame. When no live reference can reach an object, it becomes eligible for garbage collection, and the JVM reclaims its memory automatically – Java has no delete.

Common mistakes

  • Forgetting new – declaring Student s; creates no object.
  • Using elements of a new object array before creating the objects – NullPointerException.
  • Thinking b = a copies the object – it copies the reference.
  • Comparing objects with == when you mean equal content.
  • Overriding equals without hashCode – HashSet and HashMap break.
  • Accessing instance fields from static main without an object.
  • Public fields everywhere – see Encapsulation.

Key points to remember

  • A class is a blueprint; an object is an instance created with new.
  • Each object has its own copy of the instance fields.
  • Variables hold references; assignment aliases, it does not copy.
  • null refers to no object; dereferencing it throws NullPointerException.
  • == tests identity; override equals and hashCode for content equality.
  • Unreachable objects are garbage collected automatically.

Frequently asked questions

What is the difference between a class and an object?

A class is a definition written in code; an object is a run-time instance of it, occupying memory with its own field values.

Where are objects stored?

On the heap. Local variables, including references, are stored in stack frames.

Can we force garbage collection?

No. System.gc() only suggests it; the JVM decides when to collect.

Where can I learn more?

Read Java Classes and Objects and The Java Object Class, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About Java Programming

Java is one of the most used languages in the world – for enterprise software, Android apps, banking systems and backend services. This section covers core Java from syntax and data types to OOP, strings, arrays, exceptions, collections and multithreading, with clear explanations and practice questions for every topic.

Why it matters

  • Java is the main language in service-company placement tests and many product companies
  • OOP, String, collections and exception questions appear in nearly every Java interview
  • Strong core Java is the base for Spring Boot, Android and backend development
  • Java questions are common in university exams and certification tests

Who it is for

  • School students (Class 11–12 / ICSE computer applications) learning Java
  • College students (B.Tech, BCA, MCA) preparing for exams, labs and projects
  • Freshers preparing for placements, Java developer roles and technical interviews
  • Developers revising core Java before an interview

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • Java developer interviews
  • Service company tests
  • University exams
  • Certification exams
  • Government IT exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links