Back to Serialization & transient
Q2Question 2 of 11

How does transient work with a serialization example?

Key Concepts
  • This question provides a complete serialize/deserialize example showing transient fields reset to defaults
  • Password field is transient → null after deserialization
  • Balance field is NOT transient → preserved after deserialization
  • Understanding this concept is essential for Java interviews at senior level
  • This concept directly affects how banking applications manage resources

Definition

transient fields are skipped during serialization and reset to defaults on deserialization. See Q42 for the full explanation.

This is a practical example of Q42. The key point: serialize an Account with a transient password, deserialize it, and observe the password is null while the balance is preserved.

See Q42 for the bank file analogy.

Understanding the Concepts

Complete example

JAVA
import java.io.*;
import java.math.BigDecimal;

public class TransientDemo {
    public static void main(String[] args) throws Exception {
        Account original = new Account("SAV2001", new BigDecimal("500000"), "secret123");

        // Serialize
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("account.ser"))) {
            oos.writeObject(original);
        }

        // Deserialize
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("account.ser"))) {
            Account restored = (Account) ois.readObject();
            System.out.println("ID: " + restored.getAccountId());       // SAV2001
            System.out.println("Balance: " + restored.getBalance());     // 500000
            System.out.println("Password: " + restored.getPassword());   // null (transient!)
        }
    }
}

class Account implements Serializable {
    private static final long serialVersionUID = 1L;
    private String accountId;
    private BigDecimal balance;
    private transient String password;  // excluded from serialization

    Account(String id, BigDecimal bal, String pw) {
        this.accountId = id; this.balance = bal; this.password = pw;
    }
    String getAccountId() { return accountId; }
    BigDecimal getBalance() { return balance; }
    String getPassword() { return password; }
}

Output:

TEXT
ID: SAV2001
Balance: 500000
Password: null

What are common mistakes?

A common mistake is forgetting to declare serialVersionUID, which causes deserialization failures when the class changes.

Wrong approach:

JAVA
package com.bank.model;

import java.io.Serializable;

// WRONG: no serialVersionUID
public class Account implements Serializable {
    private String accountId;
    private java.math.BigDecimal balance;
}
// If you add a field later, old serialized data cannot be read

Correct approach:

JAVA
package com.bank.model;

import java.io.Serializable;
import java.math.BigDecimal;

// CORRECT: explicit serialVersionUID
public class Account implements Serializable {
    private static final long serialVersionUID = 1L;
    private String accountId;
    private BigDecimal balance;
}
// Adding new fields with defaults still allows reading old data

Another mistake is serializing sensitive fields like passwords or PINs. Always mark them transient to exclude them from the byte stream.

What should a senior engineer know?

A senior engineer should understand that Java serialization has well-known security vulnerabilities and should be avoided for external communication.

  • Deserialization attacks. Untrusted byte streams can execute arbitrary code. Use ObjectInputFilter (Java 9+) to whitelist allowed classes.
  • Alternative formats. Use JSON (Jackson/Gson) or Protocol Buffers for API communication in banking systems.
  • Serialization proxy pattern. Described in Effective Java, this pattern defends against invalid deserialized states.
  • Record serialization (Java 16+). Records use a canonical constructor for deserialization, which is inherently safer.
JAVA
package com.bank.model;

import java.io.*;

public class AccountSerializationFilter {
    public static void main(String[] args) {
        // Java 9+: restrict deserialization to safe classes
        ObjectInputFilter filter = ObjectInputFilter.Config.createFilter(
            "com.bank.model.*;!*"
        );
        // Apply to ObjectInputStream
    }
}

What are the edge cases?

Edge cases can cause unexpected behavior in banking applications. Here are some to watch for.

JAVA
package com.bank.edge;

public class EdgeCaseDemo {
    public static void main(String[] args) {
        // Edge case 1: null handling
        String accountId = null;
        try {
            System.out.println(accountId.length());
        } catch (NullPointerException e) {
            System.out.println("Null account ID");
        }

        // Edge case 2: empty vs null
        String emptyId = "";
        System.out.println(emptyId.isEmpty());  // true
        System.out.println(emptyId == null);     // false

        // Edge case 3: boundary values
        java.math.BigDecimal zero = java.math.BigDecimal.ZERO;
        java.math.BigDecimal negativeBalance = new java.math.BigDecimal("-0.01");
        System.out.println(zero.compareTo(negativeBalance) > 0);  // true
    }
}
TEXT
Null account ID
true
false
true

Always test with null values, empty strings, boundary values, and negative amounts in banking applications.

What are common interview follow-up questions?

Interviewers often follow up with these related questions:

  • How does this concept apply to a high-throughput banking transaction system?
  • What are the performance implications in a production environment?
  • How would you debug issues related to this concept?
  • What tools would you use to monitor this in production?
  • How does this behave differently in Java 8 vs Java 17+?

When answering follow-up questions, always relate your answer back to practical experience. For example, at National Bank of India, Rajesh debugged a production issue related to this concept by using JFR recordings and heap dumps. Providing concrete examples from banking systems shows the interviewer that you understand both the theory and the practice.

Visual Overview

TEXT
  Original: {id=SAV2001, balance=500000, password=secret123}
  Serialize: writes id + balance, SKIPS password (transient)
  Deserialize: restores id + balance, password = null (default)

Key Takeaway

This is a practical example of Q42. The transient password field is skipped during serialization and restored as null. The non-transient fields are preserved.

Remember one sentence: How does transient work with a serialization example is fundamental knowledge for Java interviews and production banking work.

---

Share
Use ← → arrow keys to navigate