← Home
☕Java Developer Interview Questions — Fresher to 5 YOEJava Dev InterviewNEW
🗂️

I/O, Serialization & Misc

Streams, serialization, odds & ends · 10 questions

1

What is serialization, and what does the Serializable interface do?

Must Know🌱 Fresher

Serialization converts an object's state into a byte stream (so it can be saved to disk, sent over a network, or stored in a cache), and deserialization reconstructs an equivalent object from those bytes. A class opts in simply by implementing the marker interface Serializable — it declares no methods; it just signals to ObjectOutputStream/ObjectInputStream that this class is allowed to be serialized.

Writing and reading an objectjava
try (var out = new ObjectOutputStream(new FileOutputStream("user.ser"))) {
    out.writeObject(user);
}
try (var in = new ObjectInputStream(new FileInputStream("user.ser"))) {
    User restored = (User) in.readObject();
}
Serialization
2

What is the difference between a static nested class and a (non-static) inner class?

Must Know🌱 Fresher

A static nested class is essentially a regular top-level class that happens to be declared inside another for namespacing — it holds no implicit reference to an enclosing instance, and can be instantiated independently. A (non-static) inner class holds an implicit reference to the specific enclosing instance that created it, and can access that outer instance's fields/methods directly — but it can't exist without one.

Static nested vs innerjava
class Outer {
    static class Nested { }     // Outer.Nested nested = new Outer.Nested(); -- no outer instance needed
    class Inner { }             // Outer.Inner inner = outer.new Inner(); -- needs an Outer instance
}

The implicit outer reference in a non-static inner class is also a classic memory-leak source — if an inner class instance outlives its intended lifetime while held elsewhere, it drags the entire outer instance along with it.

Nested Classes
3

What is serialVersionUID, and why should you define it explicitly?

Important📊 Mid

serialVersionUID is a version identifier stored alongside a serialized object; during deserialization the JVM checks it against the current class's serialVersionUID and throws InvalidClassException if they don't match. If you don't declare one explicitly, the compiler generates one automatically based on class details (fields, methods, etc.) — meaning even a harmless-looking change (adding a method) can silently change the generated value and break deserialization of previously saved data. Declaring it explicitly (private static final long serialVersionUID = 1L;) gives you control over exactly when compatibility is intentionally broken versus preserved.

Serialization
4

What does the `transient` keyword do?

Important🌱 Fresher

A transient field is excluded from the default serialization process — on deserialization it comes back as the type's default value (null, 0, false), not whatever it held before serializing. Used for fields that are either not meaningfully serializable (a Thread, a socket, a file handle) or sensitive (a password/secret you never want written to disk in plain form).

transient fieldjava
class Session implements Serializable {
    String userId;
    transient String temporaryToken; // excluded -- comes back null after deserialization
}
Serialization
5

What is the difference between java.io and java.nio?

Important📊 Mid
java.iojava.nio
ModelStream-oriented — read/write one byte/char at a time (usually buffered)Buffer/channel-oriented — read a chunk into a reusable ByteBuffer, operate on channels
BlockingAlways blockingSupports non-blocking mode (Selector, multiplexed I/O over many channels on one thread)
Typical useSimple file/console I/OHigh-throughput servers handling many concurrent connections (or memory-mapped file access)
I/ONIO
6

What is the difference between an anonymous class, a local class, and a lambda?

Important📊 Mid
Anonymous classLocal classLambda
Named?NoYes, but scoped to a methodNo
Can implementAny interface/class (multiple abstract methods too)Any interface/classOnly a single-abstract-method functional interface
Has its own this?Yes — shadows the enclosing class's thisYesNo — this inside a lambda refers to the enclosing instance
VerbosityHighHighMinimal
Nested ClassesLambda
7

What are autoboxing and unboxing, and what pitfalls should you watch for?

Important📊 Mid

Autoboxing is the compiler automatically wrapping a primitive into its wrapper class (int → Integer); unboxing is the reverse. It's convenient but hides real costs and gotchas:

  • Unboxing a null — Integer i = null; int x = i; throws a NullPointerException at the unboxing point, easy to miss in code that looks purely numeric.
  • == on boxed values — the JVM caches Integer values from -128 to 127, so Integer a = 100, b = 100; a == b is true (same cached object), but Integer a = 200, b = 200; a == b is false (different objects outside the cache range) — a classic interview trap. Always use .equals() for boxed-type comparison, never ==.
  • Performance in loops — using a boxed type as a loop counter/accumulator causes repeated box/unbox churn and extra allocation versus a primitive.
The Integer cache gotchajava
Integer a = 100, b = 100;
System.out.println(a == b); // true  -- both from the cached [-128,127] pool

Integer c = 200, d = 200;
System.out.println(c == d); // false -- outside the cache, two distinct objects
AutoboxingInteger Cache
8

What is the difference between BufferedReader and Scanner?

Optional🌱 Fresher

BufferedReader just reads raw text efficiently (buffered, line-by-line via readLine()) — no parsing built in. Scanner adds parsing on top (tokenizing by whitespace/regex, converting to int/double/etc. via nextInt(), nextDouble()...), which is convenient but has noticeably more per-call overhead — for reading large files as plain text quickly, BufferedReader is faster; Scanner is more convenient for quick parsing of structured input like competitive-programming-style stdin.

I/O
9

What is the difference between Serializable and Externalizable?

Optional📊 Mid

Serializable is a marker interface — the JVM handles the entire serialization format for you automatically (reflection-based, reading/writing every non-transient field). Externalizable extends Serializable but requires you to implement writeExternal/readExternal yourself, giving you full manual control over exactly what bytes get written and how — more work, but useful when you need a custom, compact, or versioned wire format rather than the default reflection-based one.

Serialization
10

Can you use serialization to deep-copy an object? What are the trade-offs?

Optional📊 Mid

Yes — serialize the object to a byte array, then immediately deserialize it back; since deserialization reconstructs the whole object graph from scratch, the result is a genuine deep copy with no shared references to the original's nested objects.

Trade-offs: every class in the object graph must implement Serializable (including every field's type, transitively), it's noticeably slower than a hand-written copy constructor (reflection + stream overhead), and transient fields come back as defaults rather than copied — for most real code, an explicit copy constructor/method or a library (e.g. Jackson round-tripping to/from JSON) is a more predictable and faster choice.

Serialization