Chaturmind
LearnDSASystem DesignInterview PrepDevOpsEngineering GrowthBlog
Start learning
Chaturmind

Structured learning paths for engineers who want to go deep. Written by practitioners.

Learn

  • Java
  • DSA
  • System Design
  • Spring Boot
  • AI / ML
  • DevOps
  • Engineering Growth
  • Java Interview Prep

Company

  • Blog
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Chaturmind. All rights reserved.

Built for engineers who want to go deep.


← Java Interview Prep: Fresher to 2 Years

Java Basics, JVM & Memory

  • JDK, JRE, JVM & the main Method — Interview Questions
  • JVM Memory & Garbage Collection — Interview Questions
  • Data Types, Wrapper Classes & Equality — Interview Questions

Object-Oriented Programming

  • Classes, Objects, Packages & Access Modifiers — Interview Questions
  • Inheritance, Composition, this & super — Interview Questions
  • Polymorphism, Overloading & Overriding — Interview Questions
  • Abstraction, Interfaces & Encapsulation — Interview Questions
  • Constructors, Singleton, Anonymous Classes & Immutability — Interview Questions
  • Design Patterns & SOLID Basics — Interview Questions

Strings, Keywords, Exceptions & Serialization

  • Strings, String Pool, StringBuilder & StringBuffer — Interview Questions
  • static & final Keywords — Interview Questions
  • Exceptions, Generics, Enums & Reflection — Interview Questions
  • Serialization & transient — Interview Questions

Collections Framework

  • Collections Framework Basics — Interview Questions
  • HashMap, HashSet & TreeMap Internals — Interview Questions

Multithreading Basics

  • Threads, Synchronization & volatile Basics — Interview Questions

Java 8+ & Stream API

  • Java 8 to Java 21 Features — Interview Questions
  • Stream API Coding Questions (Part 1) — Interview Questions
  • Stream API Coding Questions (Part 2) — Interview Questions

Coding Round Programs

  • Classic Number & String Programs — Interview Questions
  • String & Collection Programs — Interview Questions
  • Array & String Problem Solving — Interview Questions

Spring Framework Core

  • Spring IoC, Dependency Injection & Beans — Interview Questions
  • Spring Injection Types, Scopes, Profiles & WebFlux — Interview Questions

Spring Boot Essentials

  • Spring Boot Fundamentals — Interview Questions
  • Spring Boot Runners, Servers & Configuration — Interview Questions
  • Spring Boot Controllers, Profiles, Actuator & DevTools — Interview Questions
  • Spring Boot Testing, Exceptions & Auto-Configuration — Interview Questions
  • REST APIs, Swagger, Embedded Servers & Key Annotations — Interview Questions

Spring MVC

  • Spring MVC Architecture & DispatcherServlet — Interview Questions
  • Spring MVC Request Mapping & Controllers — Interview Questions
  • Spring MVC Forms, Views & Interceptors — Interview Questions
  • Spring MVC Exceptions, Security & Dependency Injection — Interview Questions
  • Spring MVC Data Binding, Static Resources & Path Variables — Interview Questions
  • Spring MVC i18n, Testing, File Uploads & Scaling — Interview Questions

Hibernate & Spring Data JPA

  • Hibernate & JPA Core Concepts — Interview Questions
  • Hibernate Performance, Mapping & Scenarios — Interview Questions

SQL

  • SQL Basics, Keys, Normalization & Transactions — Interview Questions
  • SQL Joins, Triggers, Procedures, Functions & Indexes — Interview Questions
  • SQL "Difference Between" Questions — Interview Questions
  • SQL Query Writing (Part 1) — Interview Questions
  • SQL Query Writing (Part 2) — Interview Questions

Microservices Basics

  • Microservices, API Gateway & Communication — Interview Questions
  • Service Discovery, Data Consistency & Deployment — Interview Questions
  • Microservices Monitoring, Security & Resilience — Interview Questions

Maven & Git

  • Maven — Interview Questions
  • Git — Interview Questions
Chaturmind
← Java Interview Prep: Fresher to 2 Years

Java Basics, JVM & Memory

  • JDK, JRE, JVM & the main Method — Interview Questions
  • JVM Memory & Garbage Collection — Interview Questions
  • Data Types, Wrapper Classes & Equality — Interview Questions

Object-Oriented Programming

  • Classes, Objects, Packages & Access Modifiers — Interview Questions
  • Inheritance, Composition, this & super — Interview Questions
  • Polymorphism, Overloading & Overriding — Interview Questions
  • Abstraction, Interfaces & Encapsulation — Interview Questions
  • Constructors, Singleton, Anonymous Classes & Immutability — Interview Questions
  • Design Patterns & SOLID Basics — Interview Questions

Strings, Keywords, Exceptions & Serialization

  • Strings, String Pool, StringBuilder & StringBuffer — Interview Questions
  • static & final Keywords — Interview Questions
  • Exceptions, Generics, Enums & Reflection — Interview Questions
  • Serialization & transient — Interview Questions

Collections Framework

  • Collections Framework Basics — Interview Questions
  • HashMap, HashSet & TreeMap Internals — Interview Questions

Multithreading Basics

  • Threads, Synchronization & volatile Basics — Interview Questions

Java 8+ & Stream API

  • Java 8 to Java 21 Features — Interview Questions
  • Stream API Coding Questions (Part 1) — Interview Questions
  • Stream API Coding Questions (Part 2) — Interview Questions

Coding Round Programs

  • Classic Number & String Programs — Interview Questions
  • String & Collection Programs — Interview Questions
  • Array & String Problem Solving — Interview Questions

Spring Framework Core

  • Spring IoC, Dependency Injection & Beans — Interview Questions
  • Spring Injection Types, Scopes, Profiles & WebFlux — Interview Questions

Spring Boot Essentials

  • Spring Boot Fundamentals — Interview Questions
  • Spring Boot Runners, Servers & Configuration — Interview Questions
  • Spring Boot Controllers, Profiles, Actuator & DevTools — Interview Questions
  • Spring Boot Testing, Exceptions & Auto-Configuration — Interview Questions
  • REST APIs, Swagger, Embedded Servers & Key Annotations — Interview Questions

Spring MVC

  • Spring MVC Architecture & DispatcherServlet — Interview Questions
  • Spring MVC Request Mapping & Controllers — Interview Questions
  • Spring MVC Forms, Views & Interceptors — Interview Questions
  • Spring MVC Exceptions, Security & Dependency Injection — Interview Questions
  • Spring MVC Data Binding, Static Resources & Path Variables — Interview Questions
  • Spring MVC i18n, Testing, File Uploads & Scaling — Interview Questions

Hibernate & Spring Data JPA

  • Hibernate & JPA Core Concepts — Interview Questions
  • Hibernate Performance, Mapping & Scenarios — Interview Questions

SQL

  • SQL Basics, Keys, Normalization & Transactions — Interview Questions
  • SQL Joins, Triggers, Procedures, Functions & Indexes — Interview Questions
  • SQL "Difference Between" Questions — Interview Questions
  • SQL Query Writing (Part 1) — Interview Questions
  • SQL Query Writing (Part 2) — Interview Questions

Microservices Basics

  • Microservices, API Gateway & Communication — Interview Questions
  • Service Discovery, Data Consistency & Deployment — Interview Questions
  • Microservices Monitoring, Security & Resilience — Interview Questions

Maven & Git

  • Maven — Interview Questions
  • Git — Interview Questions
HomeLearnJava Interview PrepJava Interview Prep: Fresher to 2 YearsStrings, Keywords, Exceptions & Serialization
✓ FreeBeginner· 6 min read

Serialization & transient — Interview Questions

What serialization is, serialVersionUID and version mismatches, transient and static fields, non-serializable members, custom writeObject/readObject, circular references, and modern alternatives.

Published September 25, 2026


How to use this lesson

Serialization questions test both mechanics and judgement. Explain how Java's built-in serialization works, and then show you know why most modern systems use JSON or Protobuf instead, and why deserializing untrusted data is dangerous.

Q1. What is serialization in Java?

Short answer: Serialization converts an object (and the objects it references) into a byte stream, so it can be stored or sent over a network. Deserialization rebuilds the object from those bytes. In Java, a class opts in by implementing the marker interface java.io.Serializable.

public class Cart implements Serializable {
    private static final long serialVersionUID = 1L;
    private String userId;
    private List<String> skus = new ArrayList<>();
}

try (var out = new ObjectOutputStream(Files.newOutputStream(path))) {
    out.writeObject(cart);                                   // serialize
}
try (var in = new ObjectInputStream(Files.newInputStream(path))) {
    Cart restored = (Cart) in.readObject();                  // deserialize
}

Key points to cover:

  • Uses: caching objects, session replication, and sending objects over RMI or older messaging systems.
  • Deserialization doesn't call the class's constructor. Fields are restored directly. The no-argument constructor of the first non-serializable superclass is run.

Q2. What is the purpose of serialVersionUID?

Short answer: It's a version number for a serializable class. During deserialization, the JVM compares the UID stored in the byte stream with the UID of the class currently loaded. If they differ, it rejects the data with an InvalidClassException, instead of silently producing a corrupt object.

Key points to cover:

  • Always declare it explicitly (private static final long serialVersionUID = 1L;). If you don't, the JVM computes one from the class's structure. Then even a harmless change, such as adding a method, or a different compiler, changes the UID and breaks compatibility with data you've already stored.
  • Keep the UID the same for compatible changes, such as adding a field (it gets its default value). Change it deliberately when the old data can no longer be read correctly.

Q3. What happens if serialVersionUID changes between serialization and deserialization?

Short answer: Deserialization fails with a java.io.InvalidClassException ("local class incompatible: stream classdesc serialVersionUID = X, local class serialVersionUID = Y"). The JVM treats the stored data and the current class as incompatible versions.

Key points to cover:

  • This typically happens after a deployment: sessions or cache entries written by the old version can't be read by the new one. Plan for it by clearing the caches, or keeping versions compatible.

Q4. How do you stop certain fields from being serialized? What does transient mean?

Short answer: Mark them transient. A transient field is skipped during serialization, and gets its default value (null, 0, false) after deserialization.

public class UserSession implements Serializable {
    private String userId;
    private transient String accessToken;       // secret: never written to disk
    private transient Map<String, Object> cache; // derived: rebuilt after loading
}

Key points to cover:

  • Use it for secrets, derived or cached values, and fields that can't be serialized (threads, sockets, loggers).
  • transient matters only to Java's built-in serialization. Jackson ignores the keyword by default (it uses @JsonIgnore), and JPA uses @Transient for fields that aren't persisted.

Q5. Can a class be serialized if one of its fields isn't serializable?

Short answer: Only if that field is transient (or null at the time), or if you handle it with custom serialization logic. Otherwise, writeObject throws a java.io.NotSerializableException naming the offending class.

Key points to cover:

  • Every object reachable from a serialized object must itself be serializable. That includes the elements of its collections.

Q6. What are writeObject() and readObject() used for?

Short answer: They're private hook methods that a serializable class can declare to customise its own serialization. You call defaultWriteObject()/defaultReadObject() for the normal fields, then write or read extra data. Typical uses: handling transient fields, validating on read, or encrypting sensitive data.

private void writeObject(ObjectOutputStream out) throws IOException {
    out.defaultWriteObject();
    out.writeUTF(encrypt(accessToken));              // custom handling of a transient field
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    in.defaultReadObject();
    accessToken = decrypt(in.readUTF());
    if (userId == null) throw new InvalidObjectException("userId required");   // validate on read
}

Common trap: saying these methods are "overridden". They're private methods with an exact signature, which the serialization machinery calls through reflection. They override nothing. (Externalizable is the alternative: you implement writeExternal/readExternal, which give you full control.)

Q7. Are static fields serialized?

Short answer: No. Serialization captures an object's state, and static fields belong to the class. After deserialization, a static field has whatever value the class currently holds in that JVM.

Q8. How are circular references handled?

Short answer: Automatically. ObjectOutputStream keeps a table of the objects already written in the stream. When it meets the same object again, it writes a back-reference (a handle) instead of serializing the object a second time. That prevents infinite recursion, and restores the exact same object graph, including shared references, when deserializing.

class Employee implements Serializable { Department dept; }
class Department implements Serializable { List<Employee> staff = new ArrayList<>(); }
// Employee → Department → staff list → the same Employee: written once, then referenced by handle

Key points to cover:

  • JSON libraries don't do this by default. Jackson loops infinitely on bidirectional JPA relationships unless you use @JsonManagedReference/@JsonBackReference or @JsonIgnore, or map to DTOs.

Follow-up questions this topic invites — and their answers

Q: Why is Java deserialization considered a security risk? A: Deserializing untrusted bytes can instantiate arbitrary classes on the classpath and trigger code in their readObject methods. That has led to remote-code-execution exploits ("gadget chains"). Never deserialize untrusted input with ObjectInputStream. If you must, use serialization filters (ObjectInputFilter, Java 9+) to allow-list the permitted classes.

Q: What do modern applications use instead of Java serialization? A: Language-neutral formats: JSON (Jackson) for APIs, Protobuf or Avro for compact, schema-evolving messages (Kafka, gRPC), and Kryo for fast JVM-only caching. Records work well with all of them.

Q: Serializable vs Externalizable? A: Serializable is automatic, with optional hooks. Externalizable requires you to write and read every field yourself, and it needs a public no-argument constructor. It's faster and fully controlled, but more work and more error-prone.

Q: How do you keep a singleton a singleton after deserialization? A: Implement readResolve() to return the existing INSTANCE, or use an enum singleton, which the serialization machinery handles correctly.

Previous

Exceptions, Generics, Enums & Reflection — Interview Questions

Next

Collections Framework Basics — Interview Questions

AI Tutor

Lesson: Serialization & transient — Interview Questions

Quick actions

AI responses can be inaccurate. Verify critical information.