Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

Lesson 5: Classes, Objects, Constructors, static & Garbage Collection

Lesson 6 of 18 in the free Programming in Java notes on Siksha Sarovar, written by Rohit Jangra.

5.1 Class vs Object — Blueprint vs Instance

A class is a template defining state (fields) and behaviour (methods); an object is a runtime instance with its own copy of instance fields. new does three things: allocates heap memory, initializes fields (defaults → initializers → constructor), and returns a reference.

Memory model in words: Student s = new Student(); — the reference s is a local variable in the current stack frame; the object (its instance fields + header with a pointer to class metadata) lives in the heap; static fields and method bytecode live in the method area, shared by all instances.

5.2 Constructors & Overloading

A constructor has the class's exact name and no return type (not even void — adding void turns it into an ordinary method, a classic trap). If you write no constructor, the compiler inserts a public no-arg default constructor; the moment you define any constructor, the default disappears.

class Box {
    double w, h, d;
    Box()                    { this(1, 1, 1); }            // constructor chaining
    Box(double side)         { this(side, side, side); }
    Box(double w, double h, double d) { this.w = w; this.h = h; this.d = d; }
    double volume()          { return w * h * d; }
}

Rules for this(...): must be the first statement; you cannot use both this() and super() in one constructor; no recursive constructor chains.

Uses of this: disambiguate shadowed fields (this.x = x), invoke another constructor, pass the current object (list.add(this)), return the current object for fluent APIs.

5.3 static — Class-Level Members

AspectInstance memberstatic member
CopiesOne per objectOne per class
MemoryHeap (inside object)Method area / metaspace
AccessVia referenceVia class name
this available?YesNo
Can accessBoth static & instanceOnly static directly

A static method cannot use this/super or touch instance fields directly — that's why main can't call a non-static method of its own class without creating an object. Static methods are not overridden, they are hidden (resolved at compile time by reference type).

5.4 Initialization Blocks & Order

class Init {
    static { System.out.println("1. static block (once, at class load)"); }
    { System.out.println("2. instance block (every new, before ctor)"); }
    Init() { System.out.println("3. constructor"); }
}
new Init(); new Init();

Output:

1. static block (once, at class load)
2. instance block (every new, before ctor)
3. constructor
2. instance block (every new, before ctor)
3. constructor

Full order: static fields/blocks (textual order, once) → instance fields/blocks (textual order) → constructor body. With inheritance, the parent's phases run before the child's.

5.5 Pass-by-Value — Always

Java is strictly pass-by-value. For objects, the value passed is the reference (a copy of it): a method can mutate the object it points to, but reassigning the parameter never affects the caller's variable. "Java is pass-by-reference" is a mark-losing myth.

5.6 Garbage Collection Basics

The GC automatically reclaims heap objects that are unreachable from any live thread's stack, static fields, or JNI roots. Objects become eligible by: nulling the last reference, reassigning it, references going out of scope, or islands of isolation (two objects referencing each other but nothing referencing them).

  • Generational hypothesis: most objects die young → heap split into Young (Eden + Survivors, minor GC) and Old generation (major GC).
  • System.gc() is only a request — the JVM may ignore it.
  • finalize() is deprecated (Java 9+) — unpredictable, at-most-once; use try-with-resources / AutoCloseable for cleanup instead.
  • You can never get a dangling pointer or double-free in Java — that entire C++ bug class is eliminated.

🎯 Exam Focus

  1. Define class and object. Explain what happens in memory when new executes (stack vs heap diagram in words).
  2. What is constructor overloading? Write a class with three chained constructors using this() and show the invocation order.
  3. Differentiate static and instance members. Why can't a static method access instance variables or use this?
  4. Predict the output of a class containing static blocks, instance blocks and a constructor when two objects are created.
  5. "Java is pass-by-value." Prove it with a program that tries (and fails) to swap two Integer references.
  6. When does an object become eligible for garbage collection? Explain islands of isolation and why finalize() is deprecated.