Iat 2 - Oops
Iat 2 - Oops
PART A (5 x 2 = 10 Marks)
CO2 R 1. Define an Interface. (2)
List the value associated with the parameters of setpriority() method of Thread class?
CO3 U 2. (2)
(Apr 2023)
CO3 R 3. Name the methods used by Java for interprocess communication to avoid (2)
poling.(Nov 2023)
CO4 A 4. Define Arithmetic Exception with examples. (2)
CO4 R 5. Mention the types of streams. (2)
PART B (2×13 = 26 Marks)
i) Compare and contrast Checked Exception and Unchecked Exception.(6)
Checked Exceptions:
1.Compile-time Checking:
2.Error Handling;
CO2 A (13)
They require explicit handling in the code, making the programmer handle
exceptions that might occur during runtime. This leads to more stable and
predictable code as potential issues are anticipated and dealt with.
3.Examples:
4.Purpose:
Checked exceptions are used for conditions from which the program can
reasonably recover. They enforce a disciplined error-handling strategy, ensuring
that critical resources are properly managed and potential errors are gracefully
handled.
Unchecked Exceptions:
1.Runtime Checking:
Unchecked exceptions are checked at runtime. The compiler does not require
methods to catch or declare these exceptions. This gives the programmer more
flexibility but also more responsibility.
2. Error Handling:
3.Examples
4. Purpose:
Unchecked exceptions are used to indicate errors that are often the result of
programming mistakes. They highlight issues like null references and out-of-
bounds array accesses, which are typically not recoverable and indicate bugs in
the code.
Comparison:
2. Use Cases:
Unchecked Exceptions are suited for programming errors and logic flaws that
usually require fixing in the code itself, rather than recovery at runtime.
Unchecked Exceptions provide flexibility but can lead to less predictable and
potentially unsafe code if not handled properly.
ii) Explain in detail about Java’s Built-in Exceptions. Explain any three
exception in detail.(7)
Java’s built-in exceptions are part of the Java Exception Hierarchy, and they
provide a standard way to handle errors and other exceptional events in the
program. These exceptions can be categorized into two main types: Checked
Exceptions and Unchecked Exceptions (Runtime Exceptions).
Checked Exceptions:
Unchecked Exceptions:
Unchecked exceptions are those that occur at runtime and are not checked at
compile-time.
1. NullPointerException:
Example:
java
2. IOException:
Example:
java
import java.io.;
try {
} catch (IOException e) {
3. ArrayIndexOutOfBoundsException:
Example:
java
(OR)
How to define an interface? How one or more classes can implement an
interface? Outline with code fragments.(Nov 2023)
Definition :
CO2 A 6.b (13)
An interface in Java is a reference type, similar to a class, that can contain only
constants, method signatures, default methods, static methods, and nested types.
Interfaces cannot contain instance fields or constructors. They are used to specify
methods that a class must implement. Here’s how you can define an interface:
// Defining an interface
void eat();
void sleep();
In this example, the `Animal` interface declares two methods: `eat()` and
`sleep()`. Any class that implements the `Animal` interface must provide
implementations for these methods.
Implementing an Interface
@Override
@Override
@Override
@Override
In this example, both `Dog` and `Cat` classes implement the `Animal` interface.
They provide their own implementations for the `eat()` and `sleep()` methods.
Java allows a class to implement multiple interfaces, enabling more flexible and
modular design:
void play();
@Override
@Override
@Override
Here, the `Dog` class implements both the `Animal` and `Pet` interfaces. This
means `Dog` must provide implementations for all the methods declared in both
interfaces.
Importance of Interfaces
Abstraction: Interfaces provide a way to define abstract types. They allow you
to specify what a class should do, without dictating how it should do it.
Multiple Inheritance: Unlike classes, a class can implement multiple interfaces,
providing a way for Java to achieve multiple inheritance.
Let's see an example of how these interfaces and classes work together:
myDog.eat();
myDog.sleep();
myPet.play();
In this `Main` class, we create instances of `Dog` using both the `Animal` and
`Pet` interfaces. This demonstrates polymorphism, where a single object (`Dog`)
can be referred to by multiple types (interfaces `Animal` and `Pet`).
Present an outline of Java’s multithreading system. Also outline the two
ways to create a thread.
Explanation:
Class Definition: A new class `MyThread` extends the `Thread` class.
run() Method: The `run()` method is overridden to define the code that
constitutes the new thread’s task.
Thread Execution: In the `main()` method, an instance of `MyThread` is
created, and `start()` is called to initiate the thread.
Example:
// Creating a thread by implementing the Runnable interface
Class MyRunnable implements Runnable {
Public void run() {
System.out.println(“Thread is running”);
}
}
Implementing `Runnable`:
- More flexible and preferred in most cases.
- Allows the class to extend another class as well.
- Promotes better object-oriented design by separating the task from the thread.
(OR)
Discuss about try, catch and finally keywords in Exception Handling with
examples.
`try` Block:
The `try` block contains the code that might throw an exception. You place code
that might generate an exception within this block. If an exception occurs, the
flow of control immediately jumps to the corresponding `catch` block.
Example:
`catch` Block:
The `catch` block handles the exception that occurs in the `try` block. You can
have multiple `catch` blocks to handle different types of exceptions separately.
Each `catch` block must contain an exception type that it can handle.
Example:
`finally` Block:
The `finally` block is used to execute important code such as closing resources,
irrespective of whether an exception is thrown or not. The code inside the
`finally` block will always be executed, even if an exception is not caught by the
`catch` block.
Example:
In the above example, regardless of whether the exception is handled or not, the
code inside the `finally` block will be executed.
Example:
```java
Public class Example {
Public static void main(String[] args) {
Try {
Int[] array = new int[5];
Array[5] = 30 / 0; // This will throw ArithmeticException first
} catch (ArithmeticException e) {
System.out.println(“ArithmeticException occurred: “ + e);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(“ArrayIndexOutOfBoundsException occurred: “ + e);
} finally {
System.out.println(“This is the finally block, executed regardless of
exceptions.”);
}
}
}
```
Usage and Importance:
1. Resource Management:
The `finally` block is often used for resource management. For example,
closing files, releasing database connections, or freeing up network resources.
3. Multi-Catch Blocks:
In Java 7 and later, you can use a single `catch` block to handle multiple
exception types, making the code more concise.
java
Catch (IOException | SQLException ex) {
Logger.log(ex);
Throw ex;
}
4. Exception Propagation:
Exceptions can be rethrown in the `catch` block to be handled by a higher-level
exception handler.
```java
Catch (IOException e) {
Throw new CustomException(“File handling error”, e);
}
PART C (1*14 = 14 Marks)
Explain in detail about File handling I/O in Java.
File Handling I/O in Java
File handling in Java is an essential feature that allows developers to create, read,
update, and delete files. Java provides a robust set of APIs and classes to handle
file operations effectively.
1.File Class:
The `File` class in the `java.io` package is the primary class for file operations. It
provides methods to create, delete, and get information about files and
directories.
2.Streams:
Java uses streams to handle input and output operations. Streams are sequences
CO4 A 8.a of data, and Java provides two types of streams: (14)
- These classes are used for reading from and writing to files in binary format.
- These classes are used for reading from and writing to files in character
format.
1.Creating a File
The `File` class can be used to create a new file. The `createNewFile()` method
returns `true` if the file was created successfully and `false` if the file already
exists.
Example:
java
import java.io.File;
import java.io.IOException;
try {
if (file.createNewFile()) {
} else {
} catch (IOException e) {
e.printStackTrace();
2.Writing to a File
Example:
java
import java.io.FileWriter;
import java.io.IOException;
try {
writer.write("Hello, World!");
writer.close();
} catch (IOException e) {
e.printStackTrace();
The `FileReader` class is used to read character data from a file. It provides
methods such as `read()` to read data and `close()` to close the stream.
Example:
java
import java.io.FileReader;
import java.io.IOException;
try {
int character;
System.out.print((char) character);
reader.close();
} catch (IOException e) {
4.Deleting a File
The `File` class provides the `delete()` method to delete a file. It returns `true` if
the file was deleted successfully and `false` otherwise.
Example:
```java
import java.io.File;
if (file.delete()) {
} else {
BufferedReader Example:
java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderExample {
String line;
System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
BufferedWriter Example:
java
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
} catch (IOException e) {
e.printStackTrace();
}
(OR)
Write a java program with nested try statements that raises divide by zero
exception and out of bound exception, if the program contains a statement
with division operator and a divisor as a command line argument.(Apr 2023)
Here’s a comprehensive Java program that uses nested try statements to handle
both divide-by-zero exceptions and array index out-of-bound exceptions. The
program takes a divisor as a command line argument and performs division
operations inside nested try blocks.
Program Overview
Java Code:
java
try {
} catch (ArithmeticException e) {
} catch (ArrayIndexOutOfBoundsException e) {
} catch (NumberFormatException e) {
Explanation:
The divisor is taken from the command line arguments and parsed into an integer
using `Integer.parseInt()`. If the input is not a valid integer, it throws
`NumberFormatException`.
- The outer try block wraps around the entire logic to catch any
`ArrayIndexOutOfBoundsException` that might occur if an invalid array index is
accessed.
- The inner try block performs the division operation. If the divisor is zero, it
throws `ArithmeticException`.
4.Catch Blocks:
- The inner catch block handles the `ArithmeticException` and prints a relevant
error message.