Interview
I/O, NIO & Serialization — Interview Questions (82+)
See `pkg9io` and `pkg20serialization`.
Detailed Questions
1. Byte streams vs character streams?
- Short:
InputStream/OutputStreamfor bytes;Reader/Writerfor chars with encoding. - Detailed: Text always needs charset (
UTF-8).InputStreamReaderbridges bytes→chars. Use streams for images/binary; readers for text. - Example:
Files.newBufferedReader(path, UTF_8).
2. Buffered I/O why?
- Short: Reduces system calls by batching reads/writes.
- Detailed:
BufferedInputStream/BufferedReaderwrap raw streams. Default buffer sizes (~8K). Especially important for many small reads. - Example:
new BufferedReader(new FileReader(f))— preferFiles.newBufferedReader.
3. try-with-resources for I/O?
- Short: Mandatory pattern for streams, readers, channels.
- Detailed: All standard I/O classes implement
AutoCloseable. Closing flushes buffers. Suppressed exceptions on close failures preserved. - Example:
try (var out = Files.newOutputStream(path)) { ... }
4. NIO.2 `Path` and `Files` API?
- Short: Modern file API: walk tree, copy, move, attributes, watch service.
- Detailed:
Paths.get/Path.of.Files.readString,writeString,walk,list,copywithStandardCopyOption. Better than legacyFile. - Example:
Files.walk(path).filter(Files::isRegularFile).forEach(...).
5. NIO channels and buffers?
- Short:
FileChannel,SocketChannel,ByteBufferfor block-oriented I/O. - Detailed: Buffers have position/limit/capacity; flip for read→write. Channels support scatter/gather, memory-mapped files (
map), non-blocking mode with selector. - Example: Memory-mapped file for large read-mostly data.
6. Selector and non-blocking I/O?
- Short: Multiplex many channels on one thread; event-driven.
- Detailed:
Selector.select()returns ready keys (ACCEPT, READ, WRITE). Foundation of scalable network servers. Netty builds on similar ideas. - Example: Single thread serving thousands of idle connections.
7. Java serialization — how it works?
- Short:
ObjectOutputStreamwrites object graph via reflection; needsSerializable. - Detailed: Writes class metadata + field values. Handles object references and cycles.
serialVersionUIDfor version compatibility. Security risk — don't deserialize untrusted data. - Example:
implements Serializable+private static final long serialVersionUID = 1L;
8. transient and Externalizable?
- Short:
transientskips fields;Externalizablefor custom read/write. - Detailed: Skip sensitive or derivable fields with
transient.Externalizablereplaces default mechanism — full control but more work. - Example:
transientpassword hash; recompute on deserialize.
9. Why avoid Java native serialization?
- Short: Security, performance, brittleness, cross-language poor.
- Detailed: Gadget chains → RCE (Apache Commons Collections history). Slow, verbose. Prefer JSON (Jackson), Protobuf, Avro for services.
- Example: `pkg20serialization` compares formats.
10. Jackson vs JAXB vs YAML?
- Short: Jackson — JSON default; JAXB — XML binding; YAML — human config.
- Detailed: Jackson modules for dates, polymorphism (
@JsonSubTypes). JAXB annotations on fields/getters. YAML via SnakeYAML — watch unsafe deserialization settings. - Example:
serialization1JacksonDemo.java.
11. Protobuf / Avro for services?
- Short: Schema-first, compact, evolvable wire formats.
- Detailed: Protobuf from
.proto; backward compatible field numbers. Avro with schema registry for Kafka. Both faster and safer than Java serialization. - Example:
serialization4ProtobufDemo.java.
12. File locking and concurrent access?
- Short:
FileChannel.lock()shared/exclusive; coordinate writers. - Detailed: OS-level advisory locks. Doesn't replace application-level consistency for databases.
Files.moveatomic on same filesystem. - Example: Exclusive lock during log file rotation.
Rapid-Fire (Q → A)
- File vs Path? → Prefer NIO.2 Path.
- Absolute vs relative Path? → resolve/normalize.
- Files.exists? → Also isDirectory, isRegularFile.
- CREATE_NEW? → Fails if exists.
- REPLACE_EXISTING? → Copy option.
- ATOMIC_MOVE? → Same filesystem atomic.
- DirectoryStream? → Try-with-resources glob.
- WatchService events? → CREATE, MODIFY, DELETE.
- StandardOpenOption APPEND? → Append to file.
- StandardOpenOption DSYNC? → Sync data.
- InputStream read returns -1? → EOF.
- readAllBytes Java 9? → On InputStream.
- transferTo InputStream? → Java 9+ to OutputStream.
- ObjectInputStream risk? → Deserialization attacks.
- ObjectInputFilter? → JDK 9+ allowlist filter.
- serialVersionUID why? → Version mismatch InvalidClassException.
- custom serialization? → writeObject/readObject private.
- readResolve writeReplace? → Control deserialized instance.
- Serializable marker? → Empty interface flags serializable.
- NotSerializableException? → Non-serializable field.
- static fields serialized? → No.
- parent class not Serializable? → Parent fields default values.
- Externalizable extends? → Serializable.
- DataInputStream? → Primitive binary reads.
- RandomAccessFile mode? → r, rw, rws, rwd.
- FileChannel position? → seek-like.
- ByteBuffer allocate vs allocateDirect? → Direct for native I/O.
- ByteOrder? → BIG_ENDIAN default; set LITTLE_ENDIAN.
- Charset.forName? → Prefer StandardCharsets constants.
- MalformedInputException? → Bad charset decode.
- CodingErrorAction REPLACE? → Replace bad chars.
- Console class? → System.console() for password read.
- System.in wrapped? → Scanner or BufferedReader.
- PrintWriter autoFlush? → println flushes.
- flush vs close? → flush pushes buffer; close flushes+closes.
- Socket streams? → getInputStream/getOutputStream.
- ServerSocket accept? → Blocks for connection.
- try-with-resources socket? → Close closes streams too.
- HttpClient replaces? → URLConnection for many cases.
- URI vs URL? → URI identifies; URL accesses (legacy).
- Base64 encoder? → java.util.Base64.
- ZipInputStream? → Stream zip entries.
- GZIPOutputStream? → Compress stream wrapper.
- Serializable collections? → ArrayList etc. serializable.
- HashMap serialization? → Yes but key/value types must be too.
- JSON date format ISO? → Jackson JavaTimeModule.
- @JsonIgnore? → Skip property.
- @JsonProperty? → Name mapping.
- YAML SnakeYAML safe? → Constructor restrict types.
- Protobuf field numbers? → Never reuse.
- Avro schema evolution? → Add fields with defaults.
- Kafka serializer? → String, Avro, JSON common.
- Deep copy via serialization? → Slow; prefer copy constructors.
- Cloneable pitfalls? → Shallow clone default.
- copyOf for collections? → Immutable copy not deep clone.
- Files.size? → File size bytes.
- Files.probeContentType? → MIME guess.
- UserPrincipal? → File owner attribute.
- PosixFilePermissions? → chmod-like on POSIX.
- isSymbolicLink? → Files.isSymbolicLink.
- readSymbolicLink? → Target path.
- Path relativize? → Relative path between.
- normalize dots? → Removes . and ..
- SPI CharsetProvider? → Custom charset provider.
- Reader mark/reset? → BufferedReader supports mark.
- LineNumberReader? → Track line numbers.
- StreamTokenizer legacy? → Prefer Scanner/ split.
- ObjectOutputStream flush? → Flush before close.
- SocketChannel non-blocking? → configureBlocking(false).
- CompletableFuture supplyAsync IO? → Use virtual threads executor Java 21.