WalzoneInterview Prep
πŸ“ž Interviewing soon? Practice with a realistic AI mock phone interview β€” it calls you, then scores you. First 15 min FREE β†’

Core Java Β· Intermediate Β· question 39 of 100

What is the difference between a stream and a reader/writer in Java?

πŸ“• Buy this interview preparation book: 100 Core Java questions & answers β€” PDF + EPUB for $5

In Java, both streams and readers/writers are used for input and output operations, but they have some key differences.

A stream is a sequence of bytes or characters that can be read from or written to. Streams are used to transfer data between a program and an input/output device, such as a file, network connection, or console. Streams are low-level constructs that deal with binary data, and are typically used for handling large amounts of data.

On the other hand, a reader/writer is a higher-level abstraction that deals with characters instead of bytes. Readers/writers are used to read and write text data, and are often used for working with files or user input/output. Readers/writers are built on top of streams and provide methods that make it easy to read and write text data.

Here is an example of how to read a file using a stream:

try (InputStream in = new FileInputStream("file.txt")) {
    int data;
    while ((data = in.read()) != -1) {
        // Do something with the data
    }
} catch (IOException e) {
    // Handle the exception
}

In this example, we use a stream (FileInputStream) to read a file byte by byte. We read each byte into an integer variable data, which is set to -1 when the end of the file is reached.

Here is an example of how to read a file using a reader:

try (Reader reader = new FileReader("file.txt")) {
    int data;
    while ((data = reader.read()) != -1) {
    // Do something with the data
    }
} catch (IOException e) {
    // Handle the exception
}

In this example, we use a reader (FileReader) to read a file character by character. We read each character into an integer variable data, which is set to -1 when the end of the file is reached.

In summary, streams and readers/writers are used for input and output operations in Java, but they have different levels of abstraction and are used for different types of data. Streams are low-level constructs that deal with binary data, while readers/writers are higher-level abstractions that deal with character data. Both streams and readers/writers have their own set of classes and methods for handling input and output operations.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Core Java interview β€” then scores it.
πŸ“ž Practice Core Java β€” free 15 min
πŸ“• Buy this interview preparation book: 100 Core Java questions & answers β€” PDF + EPUB for $5

All 100 Core Java questions Β· All topics