Java Question Bank with Answers

Answers for Core Java Question Bank –

Chapter 4: Exception Handling, Strings, and Files

Easy Level Questions (5 Marks Each)

1. Differentiate between an Error and an Exception in Java. Provide one example of each.

Answer:
In Java, both
Error and Exception are subclasses of java.lang.Throwable and represent abnormal conditions. However, they signify different types of problems and are handled differently.

Feature

Error

Exception

Definition

Represents serious, unrecoverable problems that are typically outside the application’s control.

Represents conditions that an application might want to catch and handle.

Source

Usually indicates a problem with the JVM itself, system resources, or environment.

Often caused by the program itself, user input, or external factors that can be anticipated.

Recoverability

Generally irrecoverable. It’s usually not advisable for an application to try and handle these.

Generally recoverable. Programmers can catch and handle them to allow the program to continue execution.

Handling

Not expected to be caught or handled by regular application code.

Expected to be caught and handled using try-catch blocks.

Example

OutOfMemoryError, StackOverflowError.

NullPointerException, ArrayIndexOutOfBoundsException, IOException.

Example of an Error:

import java.util.ArrayList;

import java.util.List;

 

public class ErrorExample {

    public static void main(String[] args) {

        // This code tries to allocate large arrays repeatedly, potentially causing OutOfMemoryError

        try {

            List<byte[]> list = new ArrayList<>();

            while (true) {

                list.add(new byte[1024 * 1024]); // 1MB arrays

            }

        } catch (OutOfMemoryError e) { // Catch the specific error

            System.err.println("Caught OutOfMemoryError: " + e.getMessage());

        }

        System.out.println("Program continues after handling OutOfMemoryError.");

    }

}

Example of an Exception:

public class ExceptionExample {

    public static void main(String[] args) {

        String text = null;

        try {

            // This line will throw a NullPointerException

            System.out.println(text.length());

        } catch (NullPointerException e) { // Catch the specific exception

            System.err.println("Caught NullPointerException: Cannot get length of a null string.");

        }

        System.out.println("Program continues after exception handling.");

    }

}

2. What are Checked Exceptions in Java? Give two examples of checked exceptions.

Answer:
Checked Exceptions are exceptions that the Java compiler checks at compile-time. If a method might throw a checked exception, the compiler mandates that the method either:

1.     Handle the exception using a try-catch block.

2.     Declare the exception using the throws keyword in its method signature, indicating to callers that they must handle or declare it.

If a checked exception is neither handled nor declared, the program will not compile. These exceptions typically represent conditions that are external to the application’s control but can often be anticipated and recovered from, such as I/O issues, network problems, or database connectivity errors.

Two Examples of Checked Exceptions:

1.     IOException: This general exception is thrown when an input or output operation fails or is interrupted. For instance, trying to read from a file that doesn’t exist will lead to a FileNotFoundException (a subclass of IOException).

o    Example: new FileInputStream("nonexistent.txt")

2.     SQLException: This exception is thrown when there’s an error during database access or operations.

o    Example: Attempting to connect to a database with invalid credentials.

3.     ClassNotFoundException: Thrown when an application tries to load a class using its string name (e.g., with Class.forName()), but no definition for the class could be found.

3. Explain the purpose of the try-catch block in Java exception handling.

Answer:
The
try-catch block is a fundamental construct in Java’s exception handling mechanism, designed to manage runtime errors gracefully.

Purpose of the try block:
The
try block is used to enclose the segment of code that is prone to throwing an exception. When an exception occurs within this block, the normal execution flow of the try block is immediately terminated, and control is transferred to the associated catch block.

Purpose of the catch block:
The
catch block immediately follows a try block and specifies the type of exception it can handle. If an exception of that specific type (or its subclass) is thrown in the try block, the code inside the catch block is executed. This block contains the logic to recover from the error, log the incident, provide a user-friendly message, or take corrective actions.

Overall Purpose:
The primary purposes of using a
try-catch block are:

1.     Prevent Abnormal Termination: To prevent the program from crashing due to an unexpected error.

2.     Graceful Error Recovery: To allow the program to handle errors and potentially continue its execution in a controlled manner, rather than just stopping.

3.     Separation of Concerns: It helps in separating the normal program logic from the error-handling logic, making the code cleaner, more readable, and easier to maintain.

4. What is the StringBuffer class in Java? How does it differ from the String class in terms of mutability?

Answer:
The
StringBuffer class in Java represents a mutable sequence of characters. It is designed for situations where the content of a string needs to be modified frequently (e.g., appending characters, inserting substrings, or deleting parts).

Difference from String in Terms of Mutability:

Feature

String class

StringBuffer class

Mutability

Immutable: Once a String object is created, its value cannot be changed. Any operation that seems to modify it actually creates a new String object.

Mutable: The content of a StringBuffer object can be modified in-place after its creation. Operations like append(), insert(), delete() modify the existing object.

Memory

Each modification creates a new String object, leading to potentially many intermediate objects and increased garbage collection overhead, especially in loops.

Modifications happen on the same object, which is more memory-efficient for frequent changes.

Performance

Less efficient for extensive string manipulations due to repeated object creation.

More efficient for extensive string manipulations.

Thread-Safety

Inherently thread-safe because it’s immutable.

Thread-safe: Its methods are synchronized, making it suitable for multi-threaded environments.

5. List two common methods used for formatting string data in Java.

Answer:
Two common and effective methods used for formatting string data in Java are:

1.     String.format():

o    This is a static method that returns a formatted String using the specified format string and arguments. It works much like the printf function in C.

o    It allows for precise control over data representation (e.g., number of decimal places, alignment, padding).

o    Example:

o    String name = "Alice";

o    int age = 30;

o    String formattedOutput = String.format("My name is %s and I am %d years old.", name, age);

System.out.println(formattedOutput); // Output: My name is Alice and I am 30 years old.

2.     System.out.printf():

o    This method is part of the PrintStream class (which System.out is an instance of). It provides the same formatting capabilities as String.format() but directly prints the formatted output to the console.

o    It’s a convenient shorthand when you only need to print formatted text.

o    Example:

o    double value = 123.4567;

o    System.out.printf("The value is: %.2f%n", value); // Output: The value is: 123.46

// %n is for a platform-independent new line

6. What is a Stream in the context of Java File Handling? Name the two main types of streams.

Answer:
In the context of Java File Handling (and Input/Output in general), a
Stream is an abstract representation of a sequence of data flowing from a source to a destination. It acts as a conduit or channel for data transfer. Data can flow into a program from a source (input stream) or out of a program to a destination (output stream). Streams abstract away the complexities of dealing with physical I/O devices, allowing a consistent way to interact with different data sources (files, network sockets, memory, etc.).

The two main types of streams in Java are:

1.     Byte Streams:

o    These streams handle input and output of raw 8-bit bytes.

o    They are suitable for handling binary data, such as images, audio files, video files, or any non-textual data.

o    Examples: FileInputStream, FileOutputStream, BufferedInputStream, BufferedOutputStream.

2.     Character Streams:

o    These streams handle input and output of 16-bit Unicode characters.

o    They are designed specifically for handling text data, as they automatically manage character encoding conversions.

o    Examples: FileReader, FileWriter, BufferedReader, BufferedWriter, InputStreamReader, OutputStreamWriter.

7. How do you create a new file in Java using basic file handling operations?

Answer:
You can create a new file in Java using the
java.io.File class or by using output streams like FileOutputStream or FileWriter.

1. Using the java.io.File class (to create an empty file):
This is the most direct way to create a file without immediately writing content to it.

import java.io.File;

import java.io.IOException;

 

public class CreateEmptyFile {

    public static void main(String[] args) {

        String fileName = "myNewFile.txt";

        File file = new File(fileName);

 

        try {

            // createNewFile() returns true if the file was created, false if it already exists

            if (file.createNewFile()) {

                System.out.println("File ‘" + fileName + "’ created successfully.");

            } else {

                System.out.println("File ‘" + fileName + "’ already exists.");

            }

        } catch (IOException e) { // Specify the exception type and variable

            System.err.println("An error occurred during file creation: " + e.getMessage());

            e.printStackTrace(); // Optional: print the stack trace for debugging

        }

    }

}

2. Using FileWriter (to create and write text content):
If you intend to write text to the file immediately,
FileWriter will automatically create the file if it doesn’t exist.

import java.io.FileWriter;

import java.io.IOException;

 

public class CreateFileWithContent {

    public static void main(String[] args) {

        String fileName = "outputMessage.txt";

        String content = "This is some initial text for the new file.";

 

        // try-with-resources ensures the FileWriter is closed automatically

        try (FileWriter writer = new FileWriter(fileName)) {

            writer.write(content);

            System.out.println("File ‘" + fileName + "’ created and content written.");

        } catch (IOException e) { // Correct syntax for catching IOException

            System.err.println("Error creating or writing to file: " + e.getMessage());

            e.printStackTrace(); // Optional: for debugging

        }

    }

}