Insights into Company
← Java

Object

Understand the idea. Compare it. Explain it. Test yourself.

Question 1 of 12

What is an object in Java?

Solution and explanation

What it is

An object is an instance of a class: a real entity in memory with its own state (field values), behaviour (methods) and identity (its unique place in memory).

Example: a Laptop class defines brand, RAM and price. The Dell laptop on your desk with 16 GB RAM costing ₹65,000 is one object; your friend's HP is another.

public class Laptop {
    String brand;
    int ramGb;
    double price;

    void boot() { System.out.println(brand + " is starting with " + ramGb + " GB RAM"); }
}

Laptop mine = new Laptop();
mine.brand = "Dell"; mine.ramGb = 16; mine.price = 65000;
mine.boot();   // Dell is starting with 16 GB RAM

Three properties of every object

PropertyMeaningIn the example
StateCurrent values of its fieldsbrand = Dell, ramGb = 16
BehaviourWhat it can doboot()
IdentityDistinguishes it from other objects even with equal stateits memory location; mine == other compares identity

Every object inherits from Object

Methods available on every object: toString(), equals(), hashCode(), getClass(), wait()/notify()/notifyAll() and clone() (protected).

Practice explaining this
Question 2 of 12

How do you create an object?

Solution and explanation

1. The new keyword (most common)

Student s = new Student("Anu", 21);

Steps: the class is loaded if needed → memory is allocated on the heap → fields get default values → initializers and the constructor run → the reference is returned and stored in s.

2. Factory and static methods

List<String> list = List.of("a", "b");
LocalDate today = LocalDate.now();
Integer n = Integer.valueOf(42);           // may return a cached object

3. Cloning

class Point implements Cloneable {
    int x, y;
    @Override public Point clone() throws CloneNotSupportedException { return (Point) super.clone(); }
}
Point copy = original.clone();    // new object, constructor not called

4. Reflection

Student s = Student.class.getDeclaredConstructor(String.class, int.class).newInstance("Anu", 21);

Frameworks such as Spring and Hibernate create your objects this way.

5. Deserialization

try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("student.ser"))) {
    Student s = (Student) in.readObject();   // constructor of Student not called
}

JSON libraries (Jackson) also create objects from text.

6. Builder pattern

Order order = Order.builder().id(101).customer("Ravi").amount(2499).build();
WayConstructor called?
new, factory method, reflection, builderYes
clone()No
DeserializationNo (for the Serializable class itself)
Practice explaining this
Question 3 of 12

Where is an object stored in Java memory?

Solution and explanation

Short answer

Objects live on the heap. References (variables that point to objects) that are local variables live on the stack of the thread executing the method.

public void createOrder() {
    int qty = 2;                              // primitive local → stack
    Order order = new Order("Phone", qty);    // reference 'order' → stack; Order object → heap
}
Stack (thread main)              Heap
┌───────────────────────┐        ┌────────────────────────────┐
│ createOrder() frame   │        │ Order@5e2d                  │
│   qty   = 2           │        │   item = ──► String "Phone" │
│   order = ────────────┼──────► │   qty  = 2                  │
└───────────────────────┘        └────────────────────────────┘

JVM memory areas

AreaStoresShared?
HeapAll objects and arrays, including instance variablesShared by all threads; garbage collected
Stack (one per thread)Method frames: local primitives and references, return addressesPrivate per thread
Metaspace (method area)Class metadata, method bytecode, static variables (static field values live with the Class object)Shared
PC registerCurrent instruction per threadPrivate
Native method stackNative (C/C++) callsPrivate

Heap generations

  • Young generation (Eden + two Survivor spaces): new objects; most die young and are collected quickly (minor GC).
  • Old generation: objects that survived several collections.

Escape analysis

The JIT compiler can avoid heap allocation for an object that never leaves a method (scalar replacement), but conceptually objects belong to the heap.

Errors

  • OutOfMemoryError: Java heap space – the heap is full.
  • StackOverflowError – a thread's stack is exhausted, usually by infinite recursion.
Practice explaining this
Question 4 of 12

What is the difference between an object and a reference?

Solution and explanation

Short answer

An object is the actual data on the heap. A reference is a variable that holds the address (handle) of that object, like a TV remote that controls a TV.

Car c1 = new Car("Swift");   // new Car(...) creates the object; c1 is a reference to it
Car c2 = c1;                 // copies the reference, NOT the object
c2.setModel("Dzire");
System.out.println(c1.getModel());   // Dzire — both remotes control the same TV
ObjectReference
Lives on the heapVariable on the stack (local) or inside another object (field)
Holds the stateHolds the address of an object, or null
Created with newDeclared with a type: Car c1;
Garbage collected when unreachableDisappears when it goes out of scope
One object can have many referencesOne reference points to at most one object at a time

Java is pass-by-value

Java passes a copy of the reference to methods. The method can change the object's state through it, but reassigning the parameter does not affect the caller.

static void rename(Car car) {
    car.setModel("Baleno");   // changes the shared object: visible to the caller
    car = new Car("Alto");    // only the local copy now points elsewhere
}

Car mine = new Car("Swift");
rename(mine);
System.out.println(mine.getModel());   // Baleno
Practice explaining this
Question 5 of 12

Can multiple references point to the same object?

Solution and explanation

Answer

Yes. Assigning one reference to another copies the address, so both refer to the same object. A change made through either reference is visible through the other. This is called aliasing.

List<String> cart = new ArrayList<>();
List<String> sameCart = cart;           // alias
sameCart.add("Shoes");
System.out.println(cart);               // [Shoes]
System.out.println(cart == sameCart);   // true — same object
cart ─────┐
          ├──► ArrayList ["Shoes"]
sameCart ─┘

Where it matters

  • Methods receive a copy of the reference, so they can modify the caller's object.
  • Collections store references: adding the same object twice stores two references to one object.
  • Returning an internal mutable field exposes it to outside modification:
public class Order {
    private final List<String> items = new ArrayList<>();
    public List<String> getItems() { return items; }                    // caller can modify our list!
    public List<String> getItemsSafe() { return List.copyOf(items); }   // defensive copy
}

Garbage collection

An object becomes eligible for garbage collection only when no live reference points to it. With two references, setting one to null does not free the object.

Need an independent copy?

Create a copy: new ArrayList<>(cart), a copy constructor, or a deep copy (see shallow vs deep copy).

Practice explaining this
Question 6 of 12

What happens when an object reference is null?

Solution and explanation

Meaning

null means the reference points to no object. Using it to access a field or call a method throws NullPointerException (NPE) at run time.

String city = null;
System.out.println(city.length());    // NullPointerException

Since Java 14, helpful NPE messages show exactly what was null:

Cannot invoke "String.length()" because "city" is null

Common causes

  • Fields of reference type are null by default if not initialised.
  • Methods returning null (map.get(key) for a missing key).
  • Unboxing a null wrapper: Integer qty = null; int q = qty; throws NPE.
  • Uninitialised array elements: String[] names = new String[3]; names[0].trim();.

What is allowed with null

String s = null;
System.out.println(s);              // prints "null"
System.out.println("x" + s);        // "xnull"
if (s == null) { }                   // comparison is fine
s instanceof String                  // false, no exception

How to avoid NPEs

// 1. Check
if (customer != null && customer.getAddress() != null) { ... }

// 2. Fail fast with a clear message
this.name = Objects.requireNonNull(name, "name must not be null");

// 3. Optional for values that may be absent
Optional<User> user = repository.findByEmail(email);
String display = user.map(User::getName).orElse("Guest");

// 4. Put the known non-null value first
"ADMIN".equals(role);                // safe even if role is null

// 5. Return empty collections instead of null
return List.of();
Practice explaining this
Question 7 of 12

What is object initialization?

Solution and explanation

What it is

Object initialization is the process of giving an object's fields their starting values when it is created. Java runs initialization in a fixed order.

Order when you call new

  1. Memory is allocated and every field gets its default value (0, false, null).
  2. The constructor is invoked; its first statement calls super(...) (explicitly or implicitly), so the parent class initialises first.
  3. Field initializers and instance initializer blocks run, top to bottom in source order.
  4. The rest of the constructor body runs.
class Base {
    Base() { System.out.println("1. Base constructor"); }
}

class Product extends Base {
    private String name = initName();                      // field initializer
    { System.out.println("3. instance initializer block"); }

    Product() {
        super();                                           // implicit if omitted
        System.out.println("4. Product constructor body");
    }

    private String initName() { System.out.println("2. field initializer"); return "Laptop"; }
}

new Product();
1. Base constructor
2. field initializer
3. instance initializer block
4. Product constructor body

Static initialization (once per class)

Static fields and static { } blocks run once, when the class is first loaded, before any object is created.

Ways to initialise fields

  • At declaration: private int stock = 0;
  • In an initializer block (shared by all constructors).
  • In the constructor (most common, especially with parameters).
  • Lazily, on first use: if (cache == null) cache = load();

Note: never call overridable methods from a constructor. The subclass version runs before the subclass's fields are initialised and may see null values.

Practice explaining this
Question 8 of 12

What is the lifecycle of an object?

Solution and explanation

Stages

  1. Class loading: before the first object, the class is loaded, linked and statically initialised (once).
  2. Creation: new allocates heap memory (usually in the Eden space) and fields get default values.
  3. Initialization: initializers and the constructor run; the object is now usable.
  4. In use (reachable): one or more live references point to it; methods are called on it.
  5. Unreachable: no live reference remains (variable out of scope, set to null, reassigned).
  6. Garbage collected: the GC detects it is unreachable and reclaims its memory. Cleanup actions registered with Cleaner may run.
public void process() {
    Invoice inv = new Invoice(101);   // 2–3 created and initialised
    inv.calculateTax();              // 4 in use
    inv = new Invoice(102);          // 5 the first Invoice is now unreachable
}                                    // 5 the second becomes unreachable when the method returns
                                     // 6 GC reclaims both at some later time

Generational journey

new object → Eden → (survives minor GC) → Survivor S0/S1 → (survives several GCs) → Old generation → major GC

Notes

  • You cannot force GC; System.gc() is only a hint.
  • finalize() is deprecated (Java 9) and removed for future use: it was unpredictable and slow. Use try-with-resources for files, sockets and DB connections, and java.lang.ref.Cleaner as a safety net.
Practice explaining this
Question 9 of 12

What is garbage collection?

Solution and explanation

What it is

Garbage collection (GC) is the JVM's automatic memory management: it finds objects that are no longer reachable from the program and frees their heap memory. Programmers do not call free() or delete as in C/C++.

How the JVM decides what is garbage

GC starts from GC roots and marks everything reachable. Anything not marked is garbage.

  • GC roots: local variables on thread stacks, static fields, active threads, JNI references.
Customer a = new Customer("A");
Customer b = new Customer("B");
a = b;      // the object "A" is now unreachable → eligible for GC
b = null;   // "B" is still reachable through a

Circular references are not a problem: two objects pointing to each other but unreachable from roots are both collected.

Basic algorithm: mark, sweep, compact

  1. Mark: traverse from roots and mark live objects.
  2. Sweep: reclaim memory of unmarked objects.
  3. Compact: move live objects together to avoid fragmentation.

Generational collection

Most objects die young, so the heap is split:

  • Young generation (Eden, Survivor spaces): minor GCs are frequent and fast.
  • Old generation: long-lived objects; major/full GCs are less frequent and more expensive.

Collectors

CollectorCharacteristicsTypical use
SerialSingle thread, stop-the-worldSmall apps, containers with 1 CPU
ParallelMany threads, maximises throughputBatch jobs
G1 (default since Java 9)Region-based, predictable pause targets (-XX:MaxGCPauseMillis)Most server applications
ZGC / ShenandoahMostly concurrent, pauses of a few milliseconds even on huge heapsLow-latency services

Memory leaks still happen

An object that is still referenced is never collected, e.g. a static Map cache that only grows, unremoved listeners, or ThreadLocals in thread pools. Diagnose with heap dumps (jmap, VisualVM, Eclipse MAT).

Useful flags

-Xms512m -Xmx2g            initial and maximum heap
-XX:+UseG1GC               choose collector
-Xlog:gc*                  GC logging (Java 9+)
Practice explaining this
Question 10 of 12

What is shallow copy?

Solution and explanation

What it is

A shallow copy creates a new object and copies the field values of the original. For primitive fields that copies the values; for reference fields it copies only the references, so the original and the copy share the same nested objects.

class Address { String city; Address(String c) { city = c; } }

class Employee implements Cloneable {
    String name;
    Address address;

    Employee(String name, Address address) { this.name = name; this.address = address; }

    @Override
    protected Employee clone() throws CloneNotSupportedException {
        return (Employee) super.clone();      // Object.clone() is a shallow copy
    }
}

Employee e1 = new Employee("Asha", new Address("Pune"));
Employee e2 = e1.clone();
e2.address.city = "Noida";
System.out.println(e1.address.city);    // Noida — the Address object is shared!
System.out.println(e1 == e2);           // false — different Employee objects
System.out.println(e1.address == e2.address);  // true
e1 ──► Employee{name, address ─┐
                               ├──► Address{city="Noida"}
e2 ──► Employee{name, address ─┘

Other shallow copies

List<Employee> copy = new ArrayList<>(original);  // new list, same Employee objects
int[] arr2 = arr1.clone();                          // fine for primitives
Employee[] staff2 = staff.clone();                  // array copied, elements shared

When shallow copy is fine

  • All fields are primitives or immutable objects (String, Integer, LocalDate).
  • Sharing nested objects is intentional.

Otherwise use a deep copy.

Practice explaining this

Showing questions 1–10 of 12