Basic Input and Output in Java FAQs and Interview Preparation
1.How can you read a single character from the user in Java?
You can read a single character from the user using BufferedReader or Scanner classes in Java. Using BufferedReader, you can read a byte with the help of the System.in.read() method and then cast that to char to get the entered character. However, the Scanner class is most frequently used for reading input since it's so straightforward.
You may apply scanner.next().charAt(0) to read the next character of a character string entered.
The Scanner approach is much more intuitive and preferred for reading characters in interactive applications.
Example using Scanner:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a character: ");
char c = scanner.next().charAt(0) ;
// Reads a single character
2.What’s the difference between BufferedReader and Scanner for reading input in Java?
BufferedReader and Scanner are both used for reading input in Java but differ in their functionalities. A BufferedReader reads text efficiently from a character buffer and is good for large text files, for instance. BufferedReader reads input as strings.
Thus, you will need to parse them yourself into other data types. Scanner is relatively more flexible in the context that it is able to parse primitive types directly, int, double and String directly. Although, Scanner might be easier for formatted inputs, BufferedReader shines in huge text reading where it runs faster.
Use of Scanner
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer: ");
int num = scanner.nextInt(); // Reads the integer directly
3.How do you deal with exceptions that may be coming while reading data from the file in Java?
Exceptions like IOException, FileNotFoundException etc. usually come during file reading in Java. We use try-catch block to overcome these exceptions.
For example, you would enclose all of the file reading code with a try block and specific exceptions so that you can catch potential errors while reading it very elegantly.
Let's see a simple example for this:
try
{
FileReader file = new FileReader("example.txt");
BufferedReader reader = new BufferedReader(file);
}
catch (FileNotFoundException e) {
System.out.println("File not found!");
} catch (IOException e)
{
System.out.println("Error reading file!");
}
By the help of exceptions handling you can ensure that the program does not crash and gives meaningful error messages.
4.How do you read a file line by line using BufferedReader?
To read a file line by line in Java, you can use BufferedReader with the readLine() method, which reads one line at a time.
Here's an example:
BufferedReader reader = new BufferedReader(new FileReader("example.txt"));
String line;
while ((line = reader.readLine())!= null)
{
System.out.println(line);
}
reader.close();
This method is efficient for reading large files because it minimizes memory usage by reading the file one line at a time.
5.What is purpose of flush() when you write a file in Java?
It flushes all data out of the buffer and is sent to the destination at once. It is a handy method if you ever want to make sure all your buffered data has successfully reached the file or your program ends without explicitly closing the stream.
Example:
BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"));
writer.write("Hello, world!");
writer.flush(); /* Make sure the data is written to the file immediately*/
writer.close();
Calling flush() will ensure that there is no data left in the buffer.
6.How do you handle input from the command-line arguments in Java?
Command line arguments in Java are passed to the main method as an array of strings.
You can refer to the args array in order to access them.
If you run the program with arguments java MyProgram arg1 arg2 the args array will hold [ "arg1", "arg2" ].
Here is a simple example:
public class CommandLineExample
{
public static void main(String[] args){
if (args.length > 0){
System.out.println("First argument: " + args[0]);
} else {
System.out.println("No arguments passed.");
}
}
}
That's how Java handles its command-line input and you can change the behavior of your application based on their input as well.
7.What is the purpose of the PrintStream class in Java and how is it used?
This Java class is used to output formatted text to an output stream, like the console or a file. This class provides methods such as print(), println() and printf() for writing data in a readable format. Unlike other output classes, PrintStream automatically handles character encoding and can write directly primitive data types.
Below is an example of outputting to the console by using PrintStream
PrintStream ps = new PrintStream(System.out);
ps.println("Hello, world!");
ps.close();
PrintStream is primarily used for logging or outputting formatted output to the user.
8.How do you write formatted data to a file using PrintWriter in Java?
PrintWriter in Java allows writing formatted data to a file with the help of methods such as printf() and format().
It is part of the java.io package.
It supports automatic flushing of data when a file is closed.
Here's an example of writing formatted data to a file
PrintWriter writer = new PrintWriter(new FileWriter("output.txt"));
writer.printf("Name: %s, Age: %d%n", "John", 30);
writer.close();
Above it is used printf() that formats the string before putting it into the file
It is even more helpful in generating neat formatted text files.
9.How would you use DataInputStream and DataOutputStream for reading and writing primitive data types?
DataInputStream and DataOutputStream are used to read and write primitive data types such as int, float, double, etc. in a portable way.These streams allow reading and writing data in binary form which means that the data is platform independent.
Here's an example of how to use them:
DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.bin"));
dos.writeInt(123);
dos.writeDouble(45.67);
dos.close();
DataInputStream dis = new DataInputStream(new FileInputStream("data.bin"));
int num = dis.readInt();
double value = dis.readDouble();
dis.close();
These classes are helpful when you need to read and write primitive data types efficiently and in a consistent format across different platforms.platforms.
10.What are the differences between InputStream and Reader in Java I/O?
InputStream and Reader are used for reading data, but they are used to handle diffent from of data types. InputStream reads byte based data (in binary form or images and file). The Reader is used when one needs to read character based data, including text files and strings. Since InputStream works based on byte array, the byte value is obtained through methods such as read() while Reader will work based on character array returning a character through methods such as read().
It is like so:
InputStream: InputStream for binary data
Reader: Reader to work with the data of the type character stream.
Example that illustrates an InputStream where reading a file will be processed
FileInputStream fis=new FileInputStream("example.dat");
int byteData;
while ((byteData = fis.read())!=-1)
{
System.out.print ((char)byteData);
}
fis.close();
Reader is used when dealing with text files because it takes care of character encoding.
11.How to serialize and deserialize objects using ObjectInputStream and ObjectOutputStream?
ObjectInputStream and ObjectOutputStream classes are used in Java for serialization and deserialization. Serialization is the process of writing objects into a file or stream, whereas deserialization is the reverse an object is read from a file or stream. Serialization stores an object as a byte stream and may save that byte stream to a file or send it over a network. Deserialization reconstructs the original object from the byte stream.
Example:
// Serialization
ObjectOutputStream out;
out = new ObjectOutputStream(new FileOutputStream("object.ser"));
out.writeObject(new Person("John", 30));
out.close();
// Deserialization
ObjectInputStream in ;
in= new ObjectInputStream(new FileInputStream("object.ser"));
Person person = (Person) in.readObject();
in.close();
Remember that the class being serialized must implement the Serializable interface.interface.
12.How do you redirect output to a file in Java instead of the console?
In Java it is possible to redirect the standard output (System.out) to a file using PrintStream,thus, this can be used to capture console output in a file.
Here is an example of how the output can be redirected to a file:
PrintStream fileOut = new PrintStream(new FileOutputStream("output.txt"));
System.setOut(fileOut);
System.out.println("This will be written to the file.");
This will change the default output stream to a file.
Thus, subsequent System.out.println() will actually write to the file output.txt.
13.How can you use FileInputStream and FileOutputStream in Java to read and write binary data?
FileInputStream and FileOutputStream are used to read and write binary data like image files, audio files or any raw data.
These streams read and write the data in terms of bytes thus are suitable for binary data handling.
Example writing and reading of a binary file
//Writing binary data
FileOutputStream fos = new FileOutputStream("output.bin");
fos.write(65); // Writes the byte for character 'A'
fos.close();
// Reading binary data
FileInputStream fis = new FileInputStream("output.bin");
int byteData = fis.read(); // Reads a single byte
System.out.println((char) byteData); // Outputs 'A'
fis.close();
These streams are good for handling non-text data manipulation.
14.How to read and write files with Java NIO by using the Files class?
Java NIO (New I/O) has a class named Files. The class of files provides numerous methods to read, write and manipulate files. It reduces complexity in I/O operations over file and can use for text or binary file manipulation.
Read and write data Example of a file by using Files class:
// Reading data from a file
List<String> lines = Files.readAllLines(path);
for (String line : lines) {
System.out.println(line);
}
The Files class offers high level methods for file operations, reducing the need for low level stream handling.
15.How to close I/O streams properly in Java without memory leaks?
The proper closing of I/O streams is important for the release of system resources and preventing memory leaks. Streams should be closed within a finally block or by using try with resources. This guarantees the automatic closing of streams.
Try with resources example:
try (FileInputStream fis = new FileInputStream("file.txt"))
{
int data = fis.read();
// Process data
} catch (IOException e) {
e.printStackTrace();
}
/* No need to close fis explicitly, it's done by itself Using try with resources all resources are closed at the end of the block regardless of exception being thrown or not.*/
Previous Topic==> Java Control flow and Operators FAQ. || Next Topics==> Java Arrays Interview Questions
Other Topic==>
Banking Account Management Case Study in SQL
Top SQL Interview Questions
Employee Salary Management SQL FAQ!. C FAQ
Top 25 PL/SQL Interview Questions
Joins With Group by Having
Equi Join
Joins with Subqueries
Self Join
Outer Join