I/O & NIO
Java I/O across both generations: the classic stream hierarchy, file handling, serialization, NIO buffers and channels with selectors, and the console streams. Interviewers use it for resource management, encoding correctness and the non-blocking server model.
part ofJavaoverview, primer and where to startread it →on this pageshowhide
explore
- I/O Streams18 questions
- Byte vs Character Streams4 questions
- Decorator Pattern & Buffering4 questions
- Data & Object Streams5 questions
- Closing, Flushing & Encoding5 questions
- File Handling14 questions
- File Class & Metadata5 questions
- Reading & Writing Text Files5 questions
- File vs Path4 questions
- Serialization19 questions
- Serializable & transient5 questions
- serialVersionUID5 questions
- Custom Serialization Hooks5 questions
- Serialization Security & Alternatives4 questions
- NIO & NIO.246 questions
- Buffer Model: capacity/limit/position/mark5 questions
- Buffer Operations: flip/clear/rewind/compact5 questions
- Buffer Allocation: heap vs direct5 questions
- Channels & FileChannel5 questions
- Non-blocking I/O & Selectors5 questions
- Memory-Mapped Files & File Locking5 questions
- Asynchronous Channels5 questions
- Path & Files API6 questions
- WatchService5 questions
- Console & Standard Streams14 questions
- Standard Streams & Redirection5 questions
- Scanner5 questions
- Console Class & Formatted Output4 questions
questions
111 · 5 sectionsWhat is the difference between byte streams and character streams in java.io, and when do you use each?
basics
~20 sByte streams (InputStream/OutputStream) move raw bytes and suit binary data like images. Character streams (Reader/Writer) move text characters and handle the conversion between bytes and characters. Use byte streams for binary, character streams for text.
Why must I/O streams be closed, and what happens if you forget to close one?
basics
~20 sStreams hold operating-system resources like file handles or sockets. If you never close them, those resources leak and can run out, and buffered data may never be written. Always close them when you are done.
What does wrapping an InputStream in a BufferedInputStream actually do, and why does it speed things up?
basics
~20 sBufferedInputStream wraps another stream and reads a big chunk of bytes at once into an in-memory array. Your reads come from that array instead of hitting the disk or network each time, so there are far fewer slow system calls.
What do InputStreamReader and OutputStreamWriter do, and why are they called bridges?
basics
~20 sThey connect the byte world to the character world. InputStreamReader wraps a byte InputStream and decodes its bytes into characters using a charset. OutputStreamWriter wraps a byte OutputStream and encodes characters into bytes. They are the bridge between the two hierarchies.
Why should you always specify a charset when converting between bytes and text in Java, and what goes wrong if you don't?
basics
~20 sBytes are not text until you choose a character encoding (a charset) to interpret them. If you don't specify one, older Java uses the machine's default, so the same code produces different or corrupted text on different machines. Always pass an explicit charset, normally UTF-8.
What is the java.io.File class, and what does a File object actually represent?
basics
~20 sjava.io.File represents a pathname (a name/location) for a file or directory, not the file's contents. Creating a File object does not create a file on disk; it just holds the path so you can ask about or act on it.
What is the difference between java.io.File and java.nio.file.Path/Files, and why is the NIO.2 API generally preferred for new code?
basics
~20 sFile is the old class for files and folders. Path (with the Files helper) is the newer NIO.2 API. Path/Files is preferred because it reports real errors (instead of returning false), supports symbolic links, file attributes, and works across different file systems.
What is the simplest modern way to read all text from a small file and write text to a file in Java, and what should you watch out for?
basics
~20 sUse the Files helper class: Files.readString(path) reads the whole file into one String, and Files.writeString(path, text) writes a String to a file. Both are fine for small files only, because they load everything into memory at once.
How do you create, delete, and rename files and directories with java.io.File, and why are these methods considered error-prone?
basics
~20 sUse createNewFile() to make an empty file, mkdir()/mkdirs() to make directories, delete() to remove, and renameTo(target) to rename or move. They're error-prone because they return a boolean false on failure instead of throwing, so they tell you it failed but not why.
Why use BufferedReader/BufferedWriter when reading or writing text, and how do you create one correctly?
basics
~20 sBuffering reads or writes data in big chunks instead of one character at a time, which is much faster because it makes far fewer slow disk/OS calls. You wrap a reader/writer, e.g. new BufferedReader(new FileReader(file)), and read line by line with readLine().
What is the Serializable interface in Java, and what does implementing it actually do?
basics
~10 sSerializable is an empty interface a class implements to say its objects can be turned into bytes and back. It has no methods; it just marks the class as allowed to be serialized.
What is serialVersionUID and why does a Serializable class have one?
basics
~20 sserialVersionUID is a version number on a Serializable class. When Java reads back a saved object, it checks that the stored number matches the class's number. If they differ, it refuses to load the object.
What does the transient keyword do during serialization, and when would you use it?
basics
~10 stransient marks an instance field to be skipped during serialization. Its value is not written out, and after deserialization it comes back as the default for its type (0, false, or null).
What are the private writeObject and readObject methods in Java serialization, and when do you use them?
basics
~20 sThey are special private methods you add to a Serializable class. Java's serialization machinery calls them automatically to let you control how the object is written to and read from a stream, instead of using the default field-by-field behavior.
Why is Java's native serialization considered dangerous when reading data from untrusted sources?
basics
~20 sWhen Java reads a serialized object, it rebuilds objects from the bytes before you can check them. An attacker can craft bytes that, while being rebuilt, run unexpected code or cause harm, so reading untrusted serialized data is risky.
What is a Java NIO Buffer, and what do its four state markers (capacity, limit, position, mark) mean?
basics
~20 sA Buffer is a fixed-size box that holds one kind of primitive value (like bytes). It tracks where you are with four numbers: capacity (total size), limit (how far you can go), position (the next slot to read/write), and mark (a saved spot you can jump back to).
After writing data into a ByteBuffer, what must you do before reading it back, and why?
basics
~20 sCall flip() before reading. Writing moves the position forward; flip() sets the limit to where you stopped writing and resets position to 0, so reads start at the beginning and stop where the data ends.
What is a Channel in Java NIO, and how does reading and writing through a Channel differ from a classic java.io stream?
basics
~20 sA Channel is a connection to an I/O source or sink (file, socket) that you read from and write to using ByteBuffer objects. Unlike a stream that moves one byte/array directly, a channel always exchanges data through a buffer, and many channels can read and write (bidirectional).
What is the NIO.2 Path interface and how does it relate to the older java.io.File class?
basics
~10 sPath is the modern way (since Java 7) to represent a file or folder location. It replaces the old File class, working together with the Files helper class for cleaner, more reliable file operations.
What is the difference between blocking and non-blocking I/O in Java NIO, and how do you switch a channel into non-blocking mode?
basics
~10 sIn blocking I/O a read/write waits until data is ready, freezing the thread. Non-blocking I/O returns immediately, even if no data is available. You enable it with channel.configureBlocking(false).
What is java.util.Scanner and how do you use it to read tokenized input from System.in?
basics
~20 sScanner is a class that reads and parses input. You wrap a source like System.in, then call methods such as nextInt(), nextDouble(), or nextLine() to read the next piece of input as a number or text.
What are the three standard streams in Java, what type is each, and what is each used for?
basics
~10 sJava has three standard streams: System.in for reading input, System.out for normal output, and System.err for errors. System.in is an InputStream; System.out and System.err are PrintStreams.
How does Console.readPassword() work, and why does it return a char[] instead of a String?
basics
~20 sreadPassword() reads a line of input from the terminal without showing the typed characters (no echo). It returns a char[] instead of a String so you can erase the password from memory afterward by filling the array with zeros - Strings are immutable and can't be wiped.
Why does a call to nextLine() right after nextInt() often return an empty string, and how do you fix it?
basics
~20 snextInt() reads the number but leaves the leftover newline (Enter key) in the buffer. The next nextLine() then reads that empty leftover instead of the next line. Fix it by adding an extra nextLine() to consume the leftover newline.
What is the java.io.Console class, how do you obtain an instance, and why can System.console() return null?
basics
~20 sConsole is a class for reading and writing text in a terminal. You get it with System.console(). It returns null when the program is not attached to a real interactive terminal (for example, when input or output is redirected, or run inside an IDE).