ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 1 · Core Java & Modern Java
  4. Volume I
  5. Objects
Book 1 · Volume I — Java Language Fundamentals & Object-Oriented Programming · Topic 4.2

Objects

Object creation, new, references, identity, state and behaviour

13 min readStage 1 · Foundations14 interview questions
Prerequisites
4.1 Classes · 3.3 Primitive vs Reference
Covers
Object creation · new · Object references · Object identity · Object state · Object behavior
Related
4.3 Constructors · 5.1 Encapsulation · Book 2 Vol II (object layout, allocation, GC) · Book 5 (value objects, entities)
On this page
  1. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts
  4. 4. How It Works Internally
  5. 5. APIs / Features / Syntax
  6. 6. Practical Examples
  7. 7. Common Problems & Mistakes
  8. 8. Performance & Production Considerations
  9. 9. Architecture & Design Considerations
  10. 10. Interview Questions & Answers
  11. Key Takeaways

1Concept / Definition

An object is a run-time instance of a class: a block of heap memory that has an identity (it is itself and no other object), state (the current values of its fields) and behaviour (the methods its class defines). Programs never hold objects directly; they hold references to them.

Three questions define an object precisely: who is it? (identity), what does it know? (state) and what can it do? (behaviour). Good object design is largely about keeping these three consistent: behaviour should change state only in ways that keep the object valid, and identity should matter only when the domain says it does.

2Why It Exists

Objects let a program model things that have their own data and lifecycle — orders, accounts, connections, sessions — and pass them around cheaply by reference. Because each object has identity, two orders with identical data can still be distinct; because objects combine state and behaviour, the rules for changing an order live in the Order class rather than being repeated wherever an order is used.

3Core Concepts

Object creation

The usual way to create an object is new, but it is not the only one. Knowing the alternatives matters because some of them bypass constructors — and therefore bypass validation.

MechanismRuns a constructor?Typical use
new Order(...)YesNormal creation
Static factory: Order.of(...), List.of(...)Yes, internallyNamed creation, caching, returning subtypes
Reflection: constructor.newInstance(...)YesFrameworks (Spring, JPA, Jackson)
clone()No — field copyLegacy copying; generally avoided
Deserialisation (ObjectInputStream)No for the Serializable class itselfLegacy serialisation; a known security risk
Records and enumsCanonical constructor / once per constantData carriers; fixed instances

new

The new operator does much more than call a constructor. It ensures the class is loaded and initialised, allocates memory, sets every field to its default, writes the object header, runs the constructor chain, and only then yields the reference.

The steps behind new
Figure 1 — The steps behind new

Most allocations are very cheap. Each thread allocates from its own thread-local allocation buffer (TLAB) in the young generation, so allocating is usually just advancing a pointer, with no locking. The real cost of objects is later: keeping them reachable, and the garbage collector's work to reclaim them.

Object references

A reference is the only way to reach an object. References can be stored in local variables, fields, array elements and collections, so objects form a graph. Several references can reach the same object, which is how objects are shared — and why a change made through one reference is visible through all of them (3.3).

Two orders share one Customer object through their references
Figure 2 — Two orders share one Customer object through their references

An object stays alive as long as it is reachable from a GC root; when the last path disappears, it becomes eligible for collection (1.3). There is no way, and no need, to delete an object explicitly.

Object identity

Every object is distinct from every other, even if their fields are equal. Identity is compared with ==. Logical equality is a separate, class-defined notion implemented by equals (3.3). System.identityHashCode exposes an identity-based hash, and identity is also what synchronized locks on.

Two variables sharing one object versus two equal objects
Figure 3 — Two variables sharing one object versus two equal objects

In design terms, some objects are defined by identity — an Account remains the same account as its balance changes — while others are defined only by their values — a Money(10.00, INR) is interchangeable with any other with the same values. Domain-driven design calls these entities and value objects respectively.

Object state

An object's state is the set of its field values at a point in time. Mutable objects change state over their life; immutable objects have all state fixed at construction (final fields, no setters, defensive copies of mutable components). Immutable objects are simpler to reason about, safe to share between threads and safe to use as map keys.

Valid states are usually a small subset of all possible field combinations. An order that is SHIPPED but has no lines, or an account with a negative balance where overdrafts are not allowed, is an invalid state. A central design goal is to make such states unreachable: validate in the constructor, and allow changes only through methods that check the rules.

Object behavior

Behaviour is what an object does in response to method calls. Well-designed behaviour operates on the object's own state and moves it between valid states, rather than exposing the state for other code to manipulate. The contrast is often described as "tell, don't ask": tell an order to pay(payment), rather than asking for its status, checking it elsewhere and setting a new status.

Methods define the legal transitions between an object's states
Figure 4 — Methods define the legal transitions between an object's states

4How It Works Internally

In HotSpot an object consists of a header followed by its fields and padding. The header contains a mark word (identity hash code, lock state, GC age bits) and a class pointer identifying the object's class. Fields are laid out by the JVM — not in declaration order — to minimise padding, and the total size is rounded to a multiple of 8 bytes.

Illustrative layout of an object with a long, an int and one reference
Figure 5 — Illustrative layout of an object with a long, an int and one reference

Two further optimisations change the picture for short-lived objects. Escape analysis in the C2 compiler can prove that an object never leaves a method and replace it with plain local values, eliminating the allocation entirely (scalar replacement). And the young generation's copying collector makes short-lived objects cheap to reclaim: dead objects are simply not copied.

An object's lifecycle from creation to collection
Figure 6 — An object's lifecycle from creation to collection

5APIs / Features / Syntax

Method of java.lang.ObjectPurposeOverride?
equals(Object)Logical equalityFor value-like classes; records do it automatically
hashCode()Hash consistent with equalsAlways together with equals
toString()Readable representationUsually; never include secrets
getClass()Run-time class of the objectFinal
clone()Field-by-field copyAvoid; prefer copy constructors or factories
wait / notify / notifyAllLow-level thread coordinationFinal; prefer java.util.concurrent
finalize()Cleanup before collectionDeprecated for removal; use try-with-resources or Cleaner

6Practical Examples

Example 1 — An entity: identity plus guarded state transitions

JAVAOrder.java
public class Order {
    private final long id;                     // identity in the domain
    private final List<Line> lines = new ArrayList<>();
    private Status status = Status.NEW;

    public Order(long id) { this.id = id; }

    public void addLine(Line line) {
        requireStatus(Status.NEW);
        lines.add(Objects.requireNonNull(line));
    }

    public void pay(Payment payment) {         // behaviour moves state
        requireStatus(Status.NEW);
        if (lines.isEmpty()) throw new IllegalStateException("empty order");
        payment.capture(total());
        status = Status.PAID;
    }

    // no leaking state
    public List<Line> lines() { return List.copyOf(lines); }

    private void requireStatus(Status expected) {
        if (status != expected) {
            throw new IllegalStateException(status + " != " + expected);
        }
    }

    @Override public boolean equals(Object o) {                // equality by id
        return o instanceof Order other && id == other.id;
    }
    @Override public int hashCode() { return Long.hashCode(id); }
}

Example 2 — Mini program: an entity and a value object in one run

Problem. Example 1 shows an entity and Example 3 a value object, but neither runs on its own. This program puts a small version of both in one file and prints what section 3 describes: equality of values, identity of entities, and an order that moves only through its legal states.

JAVAOrderLifecycle.java
public class OrderLifecycle {
    record Money(BigDecimal amount) {                  // value object
        Money { amount = amount.setScale(2, RoundingMode.HALF_EVEN); }
        Money plus(Money other) { return new Money(amount.add(other.amount)); }
    }
    enum Status { NEW, PAID, SHIPPED }
 
    static final class Order {                         // entity
        private final long id;
        private final List<Money> lines = new ArrayList<>();
        private Status status = Status.NEW;
 
        Order(long id) { this.id = id; }
        void add(Money price) { require(Status.NEW); lines.add(price); }
        void pay() {
            require(Status.NEW);
            if (lines.isEmpty()) throw new IllegalStateException("empty order");
            status = Status.PAID;
        }
        void ship() { require(Status.PAID); status = Status.SHIPPED; }
        Money total() {
            return lines.stream()
                        .reduce(new Money(BigDecimal.ZERO), Money::plus);
        }
        private void require(Status s) {
            if (status != s)
                throw new IllegalStateException(status + " != " + s);
        }
        @Override public boolean equals(Object o) {
            return o instanceof Order other && id == other.id;
        }
        @Override public int hashCode() { return Long.hashCode(id); }
        @Override public String toString() {
            return "Order#" + id + " " + status + " " + total().amount();
        }
    }
 
    static void attempt(String what, Runnable step) {
        try { step.run(); System.out.println("  ok       " + what); }
        catch (IllegalStateException e) {
            System.out.println("  rejected " + what
                    + " (" + e.getMessage() + ")");
        }
    }
 
    public static void main(String[] args) {
        Money a = new Money(new BigDecimal("499.5"));
        Money b = new Money(new BigDecimal("499.50"));
        System.out.println("values:   a == b " + (a == b)
                + ", equals " + a.equals(b));
 
        Order first = new Order(42);
        Order other = new Order(42);           // same id, another object
        System.out.println("entities: == " + (first == other) + ", equals "
                + first.equals(other) + ", set size "
                + new HashSet<>(List.of(first, other)).size());
 
        System.out.println("lifecycle:");
        attempt("pay", first::pay);
        attempt("add 499.50", () -> first.add(a));
        attempt("add 120", () -> first.add(new Money(new BigDecimal("120"))));
        attempt("pay", first::pay);
        attempt("add 499.50", () -> first.add(b));
        attempt("ship", first::ship);
        System.out.println("result:   " + first + "; other is " + other);
    }
}
OUTPUT
values:   a == b false, equals true
entities: == false, equals true, set size 1
lifecycle:
  rejected pay (empty order)
  ok       add 499.50
  ok       add 120
  ok       pay
  rejected add 499.50 (PAID != NEW)
  ok       ship
result:   Order#42 SHIPPED 619.50; other is Order#42 NEW 0.00

Why it behaves this way. The two Money values are different objects, so == is false, while equals is true. That depends on the compact constructor: BigDecimal.equals also compares the scale, so 499.5 and 499.50 would be unequal if the constructor did not set both to two decimal places. The two orders with ID 42 are distinct objects that are equal by ID, so the HashSet keeps only one: in the domain they are the same order, even though one has lines and the other has none. Every state change goes through a method that checks the current status, so paying an empty order and adding a line after payment are rejected, and the order can only move from NEW to PAID to SHIPPED, the main path of Figure 4.

Example 3 — A value object: no identity, immutable

JAVAMoney.javaequality over all fields, generated by the record
public record Money(BigDecimal amount, Currency currency) {
    public Money {
        Objects.requireNonNull(currency);
        amount = amount.setScale(currency.getDefaultFractionDigits(),
                                 RoundingMode.HALF_EVEN);
    }
    public Money plus(Money other) {
        if (!currency.equals(other.currency)) {
            throw new IllegalArgumentException("currency mismatch");
        }
        return new Money(amount.add(other.amount), currency);   // new object
    }
}

Example 4 — Ask versus tell

JAVABehaviour belongs with the state it changes
// Ask: rules scattered in callers
if (order.getStatus() == Status.NEW && !order.getLines().isEmpty()) {
    order.setStatus(Status.PAID);
}

// Tell: rules live inside the object
order.pay(payment);

Example 5 — A mutable key lost inside a HashMap

Problem. Q6 says that an entry whose key is mutated is effectively lost. This program shows what that means in practice: the entry is still in the map, but no lookup can reach it.

JAVALostKey.java
public class LostKey {
    static final class Sku {                        // mutable key
        String code;
        Sku(String code) { this.code = code; }
        @Override public boolean equals(Object o) {
            return o instanceof Sku s && s.code.equals(code);
        }
        @Override public int hashCode() { return code.hashCode(); }
    }
    record SkuKey(String code) {}                   // immutable key
 
    public static void main(String[] args) {
        Map<Sku, Integer> stock = new HashMap<>();
        Sku pen = new Sku("PEN-01");
        stock.put(pen, 40);
        pen.code = "PEN-02";                  // key changed inside the map
 
        System.out.println("get(pen)           = " + stock.get(pen));
        System.out.println("get(Sku PEN-01)    = "
                + stock.get(new Sku("PEN-01")));
        System.out.println("containsKey(pen)   = " + stock.containsKey(pen));
        System.out.println("size               = " + stock.size());
        System.out.println("key seen in a loop = "
                + stock.keySet().iterator().next().code);
        stock.remove(pen);
        System.out.println("size after remove  = " + stock.size());
 
        Map<SkuKey, Integer> fixed = new HashMap<>();
        fixed.put(new SkuKey("PEN-01"), 40);
        System.out.println("record key lookup  = "
                + fixed.get(new SkuKey("PEN-01")));
    }
}
OUTPUT
get(pen)           = null
get(Sku PEN-01)    = null
containsKey(pen)   = false
size               = 1
key seen in a loop = PEN-02
size after remove  = 1
record key lookup  = 40
The entry stays in the bucket chosen at put time; lookups go to another bucket or fail equals
Figure 7 — The entry stays in the bucket chosen at put time; lookups go to another bucket or fail equals

Why it behaves this way. HashMap files each entry in a bucket chosen from the key's hash code at the time of put. After pen.code changes, get(pen) computes the hash of PEN-02 and searches a different bucket, which is empty. A fresh Sku("PEN-01") finds the right bucket, but equals now compares PEN-02 with PEN-01 and fails (Figure 7). The entry is still there, as the size and the loop show, yet containsKey and remove cannot reach it, so in a long-lived map such entries pile up as a memory leak. A record key cannot change after put, which is why keys should be immutable.

Example 6 — Objects created without a constructor: clone() versus a copy constructor

Problem. The table in section 3 notes that clone() creates an object without running a constructor. This program counts the constructor runs and checks what the copies share with the original.

JAVACloneVsCopy.java
public class CloneVsCopy {
    static int constructed;
 
    static class Basket implements Cloneable {
        final List<String> items = new ArrayList<>();
 
        Basket() { constructed++; }                  // counts constructor runs
        Basket(Basket other) {                       // copy constructor
            this();
            items.addAll(other.items);
        }
        @Override public Basket clone() {
            try { return (Basket) super.clone(); }   // field-by-field copy
            catch (CloneNotSupportedException e) {
                throw new AssertionError(e);
            }
        }
    }
 
    public static void main(String[] args) {
        Basket original = new Basket();
        original.items.add("tea");
        Basket cloned = original.clone();
        Basket copied = new Basket(original);
        original.items.add("sugar");       // change the original later
 
        System.out.println("constructors run: " + constructed
                + " for 3 objects");
        System.out.println("clone: " + cloned.items + ", same list = "
                + (cloned.items == original.items));
        System.out.println("copy:  " + copied.items + ", same list = "
                + (copied.items == original.items));
    }
}
OUTPUT
constructors run: 2 for 3 objects
clone: [tea, sugar], same list = true
copy:  [tea], same list = false

Why it behaves this way. Three baskets exist but only two constructors ran: Object.clone() allocates the copy and copies the fields directly, so any validation or counting in a constructor is skipped. The copy is also shallow: the clone's items field refers to the same ArrayList as the original's, so adding "sugar" to the original changes the clone too. The copy constructor runs the normal constructor chain and copies the contents into a new list, so the copy is independent. That is why section 5 recommends copy constructors or factories instead of clone().

7Common Problems & Mistakes

ProblemConsequenceBetter approach
Anemic objects: only getters and settersBusiness rules duplicated in services; invalid states possiblePut behaviour with state; tell, don't ask
Mutable objects used as HashMap keys or in HashSetsEntries become unreachable after mutationImmutable keys; records
equals without hashCode (or vice versa)Hash-based collections misbehaveOverride both, or use a record
Entity equality over all mutable fieldsEquality changes as state changesCompare by stable identifier
Exposing internal collectionsCallers mutate state bypassing rulesReturn copies or unmodifiable views
Relying on finalize()Unpredictable, deprecatedtry-with-resources; Cleaner for native resources
Comparing value objects with ==Equal values are usually different objects, so the check fails, e.g. for strings built at run time or Integer values above 127Compare with equals; records and value objects define it
Shallow clone() of an object with mutable fieldsThe copy shares the original's list or array, so a change to one shows up in the otherCopy constructors or factories that copy mutable parts (Example 6)
hashCode based on a generated or mutable IDAn entity added to a HashSet before it is saved cannot be found once the ID is assignedUse a natural key, or a constant hashCode for entities (Q14)

8Performance & Production Considerations

  • Allocation is cheap, retention is expensive. Heap problems usually come from objects kept alive too long (caches, listeners, sessions), not from creating many short-lived ones.
  • High allocation rates still cost CPU through more frequent young collections. JFR's allocation profiling shows which call sites allocate most.
  • For very large numbers of small objects, object headers dominate memory. Compact object headers (Java 25), primitive arrays and fewer wrapper objects all help.
  • Immutable objects can be cached and shared without copying or locking, which often outweighs the cost of creating new instances on change.
  • Identity is a resource too. synchronized and System.identityHashCode use the object header. Never lock on value-based classes such as Integer or LocalDate, or on string literals: equal values may be the same shared object, so unrelated code ends up sharing a lock. -XX:DiagnoseSyncOnValueBasedClasses=1 makes the JVM report synchronisation on JDK value-based classes.
  • Heap dumps show objects by retained size. When memory grows, a heap dump's dominator tree names the one object, often a map or a cache, that keeps millions of others alive; that holder, not the small objects, is what to fix.

9Architecture & Design Considerations

Two object-design decisions shape whole systems.

DecisionOptionsGuidance
IdentityEntity (identity + lifecycle) or value object (defined by values)Entities: equality by ID, controlled mutation. Values: immutable records, equality by all fields.
MutabilityMutable with guarded methods, or immutable with copy-on-changeDefault to immutable; use mutation where identity and lifecycle require it, and keep it inside the object.

10Interview Questions & Answers

Q1L1 · BasicConcept

What is an object, and how does it differ from a class?

A class is a blueprint loaded once; an object is a run-time instance created from it, with its own identity, state and behaviour. There can be any number of objects of one class.

Q2L1 · BasicInternals

What does the new operator do?

It ensures the class is initialised, allocates heap memory, sets fields to default values and writes the object header, runs the constructor chain, and returns a reference to the new object.

Q3L2 · IntermediateConcept

What is the difference between object identity and object equality?

Identity means being the same object, compared with ==. Equality means representing the same value according to the class's equals method. Two distinct objects can be equal but never identical.

Q4L2 · IntermediateTricky

Can you create an object without calling its constructor?

Yes: clone() copies fields without running the constructor, and Java deserialisation creates Serializable objects without running their constructors. Both bypass validation, which is why they are discouraged and why deserialisation of untrusted data is a security risk. Example 6 shows both effects of clone(): no constructor run and a shared list.

Q5L3 · Senior EngineerInternals

Why must equals and hashCode be overridden together?

Hash-based collections first use hashCode to find a bucket and then equals to compare. If equal objects have different hash codes, lookups fail and duplicates appear. The contract requires equal objects to have equal hash codes.

Q6L3 · Senior EngineerTricky

What happens if you mutate an object that is a key in a HashMap?

If the mutation changes its hashCode, the entry stays in the bucket for the old hash, so get and remove can no longer find it; the entry is effectively lost and leaks. Keys should be immutable. Example 5 demonstrates it.

Q7L3 · Senior EngineerInternals

Is object allocation expensive in Java?

Usually not: threads allocate from thread-local buffers by bumping a pointer, and short-lived objects die cheaply in the young generation. Escape analysis can remove some allocations altogether. The expensive part is retaining objects, which increases heap size and GC work, and very high allocation rates in hot paths.

Q8L3 · Senior EngineerTrade-off

What are compact object headers in Java 25, and when would you consider them?

An opt-in HotSpot feature (JEP 519, -XX:+UseCompactObjectHeaders) that reduces the object header to 8 bytes on 64-bit platforms. They help applications with very many small objects, where headers are a significant fraction of heap. Enable only after measuring heap and throughput under representative load.

Q9L4 · Technical ArchitectDesign

How do you decide whether a domain object should be an entity or a value object?

Ask whether the business cares which instance it is over time. If yes — an account, an order — it is an entity: give it a stable ID, equality by ID and controlled mutation. If only its values matter — money, address, date range — make it an immutable value object with equality over all fields, typically a record.

Q10L4 · Technical ArchitectTrade-off

What is an anemic domain model, and when is it acceptable?

A model whose objects only hold data with getters and setters, while all rules live in service classes. It spreads rules and allows invalid states. It is acceptable for simple CRUD systems or pure data transfer, but for rule-heavy domains, behaviour-rich objects that protect their invariants are easier to keep correct.

Q11L5 · Solution ArchitectScenario

A large service keeps tens of millions of small domain objects in memory and struggles with heap size and GC. What options would you evaluate?

First measure with heap histograms and JFR. Then consider: reducing object count (primitive arrays or columnar structures instead of many small objects), removing wrappers and duplicate strings, compact object headers in Java 25, moving cold data out of the heap (an external cache or database), and whether the whole dataset really needs to be in one JVM. Choose by measured gain against complexity, and record the decision.

Q12L2 · IntermediateCode

What does this program print?

JAVAIdentityQuiz.java
public class IdentityQuiz {
    record Point(int x, int y) {}
 
    public static void main(String[] args) {
        Point a = new Point(1, 2);
        Point b = new Point(1, 2);
        Point c = a;
        System.out.println((a == b) + " " + a.equals(b) + " " + (a == c));
        Set<Point> set = new HashSet<>(List.of(a, b, c));
        System.out.println(set.size());
    }
}

It prints false true true and then 1. a and b come from two new expressions, so they are different objects and a == b is false; a record's generated equals compares all components, so they are equal. c is a second reference to the object a refers to, so a == c is true. List.of accepts duplicates, but the HashSet keeps one element per equal value, so the three references become one element.

Q13L3 · Senior EngineerInternals

Is System.identityHashCode the object's memory address?

No. In HotSpot the identity hash is generated the first time it is requested, by default from a thread-local pseudo-random sequence, and stored in the object header (section 4), so that it stays the same for the object's whole life. It cannot be an address, because the garbage collector moves objects while their hash code must not change. Different objects can have the same identity hash, so it is suitable for hash tables but not as a unique ID.

Q14L3 · Senior EngineerScenario

A new Customer entity is added to a HashSet before it is saved. After the save, set.contains(customer) returns false. Why, and how do you fix it?

The class's equals and hashCode use the database-generated ID, which is null when the entity enters the set and is assigned by the save. The entity sits in the bucket for the null hash, but contains now searches the bucket for the new ID's hash, so it reports false, and a second add creates a duplicate: the same failure as Example 5. Either base equality on a natural key that exists from the start, such as a customer number, or keep equality by ID but return a constant hashCode, for example getClass().hashCode(), and treat two unsaved entities as unequal; the second is the usual choice for JPA entities.

Test your knowledge on this topic →Try multiple choice →Flashcards from this topic's 14 questions, filtered by level and type.

Key Takeaways

  • An object has identity, state and behaviour; programs hold references to it.
  • new: initialise class, allocate, zero, header, constructors, return reference.
  • Identity (==) and equality (equals) are different; entities compare by ID, values by content.
  • Behaviour should move objects between valid states — tell, don't ask.
  • Allocation is cheap; retention is what costs memory and GC time.
Free question pack

Get 100 free Core Java interview questions

Subscribe for the Book 1 question pack (PDF, every answer explained) and new tutorials once a week. No spam, unsubscribe anytime. What is in the pack?

Almost done! Check your inbox and click the confirmation link. Your download link arrives as soon as you confirm.