0% found this document useful (0 votes)
8 views18 pages

Iat 2 - Oops

Hh

Uploaded by

ahamedahusan910
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views18 pages

Iat 2 - Oops

Hh

Uploaded by

ahamedahusan910
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

COMMON TO THE DEPARTMENT OF

COMPUTER SCIENCE AND BUISNESS STUDIES


INFORMATION TECHNOLOGY
INTERNAL ASSESSMENT TEST – II (SET-1)
SUBJECT CODE/NAME:CS3391/ Object oriented Programming DATE
BRANCH / SEMESTER: CSE/IT/CSBS / III TIME : 09.45am To 11.15am
ACADEMIC YEAR : 2024 – 2025 MARKS : 50
CO 2:To know the principles of packages, inheritance and interfaces
CO3: To develop a java application with threads and generics classes
CO 4:To define exceptions and use I/O streams
BLOOM'S TAXONOMY
Remembering Applying Evaluating
Understanding Analyzing Creating

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:

Checked exceptions are checked at compile-time. This means the compiler


ensures that these exceptions are either caught or declared in the method
signature using the `throws` keyword. This ensures robust error handling from
the outset.

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:

Common examples include `IOException`, `SQLException`, and


`FileNotFoundException`. These exceptions usually arise from external sources
(e.g., file handling, database connections) and require the programmer to address
them.

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:

Handling these exceptions is optional. They typically indicate programming


errors, such as logic flaws or improper API usage, and are usually not expected
to be caught by the programmer.

3.Examples

Common examples include `NullPointerException`,


`ArrayIndexOutOfBoundsException`, and `ArithmeticException`. These
exceptions usually result from logic errors within the code itself.

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:

1.Error Handling Strategy:

Checked Exceptions enforce a mandatory error handling strategy at compile-


time.

Unchecked Exceptions leave error handling to the discretion of the


programmer, enforcing it only at runtime.

2. Use Cases:

Checked Exceptions are suitable for recoverable conditions and external


sources of error.

Unchecked Exceptions are suited for programming errors and logic flaws that
usually require fixing in the code itself, rather than recovery at runtime.

3.Code Predictability and Safety:

Checked Exceptions contribute to predictable and stable code by enforcing


error handling.

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

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:

Checked exceptions are those that are checked at compile-time.

Unchecked Exceptions:

Unchecked exceptions are those that occur at runtime and are not checked at
compile-time.

Three Built-in Exceptions are

1. NullPointerException:

Type: Unchecked Exception (RuntimeException)

Description:This exception occurs when an application attempts to use `null` in


a case where an object is required. For example, invoking a method on a `null`
object, accessing or modifying a `null` object's field, or taking the length of
`null` as if it were an array.

Example:

java

public class Example {

public static void main(String[] args) {

String str = null;

System.out.println(str.length()); // This will throw NullPointerException

2. IOException:

Type: Checked Exception

Description: This exception signals that an input-output operation has failed or


been interrupted. It is a general exception that many other I/O exceptions inherit,
including `FileNotFoundException` and `EOFException`.

Example:

java
import java.io.;

public class Example {

public static void main(String[] args) {

try {

FileReader file = new FileReader("nonexistentfile.txt");

} catch (IOException e) {

e.printStackTrace(); // This will catch and print the IOException

3. ArrayIndexOutOfBoundsException:

Type: Unchecked Exception (RuntimeException)

Description:This exception is thrown to indicate that an array has been accessed


with an illegal index. The index is either negative or greater than or equal to the
size of the array.

Example:

java

public class Example {

public static void main(String[] args) {

int[] numbers = {1, 2, 3};

System.out.println(numbers[5]); // This will throw


ArrayIndexOutOfBoundsException

(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

public interface Animal {

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

When a class implements an interface, it agrees to perform the specific behaviors


that the interface prescribes. Here's how one or more classes can implement an
interface:

// A class implementing the Animal interface

public class Dog implements Animal {

@Override

public void eat() {

System.out.println("Dog eats bones.");

@Override

public void sleep() {

System.out.println("Dog sleeps in the kennel.");

// Another class implementing the Animal interface

public class Cat implements Animal {

@Override

public void eat() {

System.out.println("Cat eats fish.");

@Override

public void sleep() {

System.out.println("Cat sleeps on the couch.");


}

In this example, both `Dog` and `Cat` classes implement the `Animal` interface.
They provide their own implementations for the `eat()` and `sleep()` methods.

Multiple Interface Implementations

Java allows a class to implement multiple interfaces, enabling more flexible and
modular design:

// Defining another interface

public interface Pet {

void play();

// A class implementing multiple interfaces

public class Dog implements Animal, Pet {

@Override

public void eat() {

System.out.println("Dog eats bones.");

@Override

public void sleep() {

System.out.println("Dog sleeps in the kennel.");

@Override

public void play() {

System.out.println("Dog plays fetch.");

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.

Loose Coupling: Interfaces allow for loose coupling in code by defining a


contract that different classes can implement in their own ways.

Example of Interface Usage

Let's see an example of how these interfaces and classes work together:

public class Main {

public static void main(String[] args) {

Animal myDog = new Dog();

myDog.eat();

myDog.sleep();

Pet myPet = new Dog();

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.

Java’s Multithreading System

Multithreading in Java is a feature that allows concurrent execution of two or


more parts of a program for maximum utilization of CPU. Threads are
lightweight sub-processes and the smallest unit of processing. Java provides
built-in support for multithreading at the language level.

Key Components of Java’s Multithreading System:


1.Thread Class: The `Thread` class is the main class for creating and managing
CO3 U 7.a threads in Java. It provides methods to start, run, and manage threads. (13)
2.Runnable Interface: The `Runnable` interface should be implemented by any
class whose instances are intended to be executed by a thread. It defines a single
method, `run()`.
3.Thread States: A thread can be in one of the following states:
- New: The thread instance has been created but not yet started.
- Runnable: The thread is ready to run but waiting for the CPU.
- Blocked: The thread is blocked and waiting for a monitor lock.
- Waiting: The thread is waiting indefinitely for another thread to perform a
particular action.
- Timed Waiting: The thread is waiting for another thread to perform an action
for up to a specified waiting time.
- Terminated: The thread has exited.
4.Synchronization: Java provides mechanisms such as synchronized blocks and
methods to control access to shared resources by multiple threads, preventing
thread interference and memory consistency errors.
5.Inter-thread Communication: Methods like `wait()`, `notify()`, and
`notifyAll()` facilitate communication between threads, allowing them to wait
for certain conditions to be met and notify each other when those conditions
change.
6.Thread Priorities: Threads can be assigned priorities, which are integer
values ranging from `Thread.MIN_PRIORITY` (1) to
`Thread.MAX_PRIORITY` (10), with `Thread.NORM_PRIORITY` (5) being
the default.

Two Ways to Create a Thread


1.Extending the `Thread` Class:
In this method, you create a new class that extends the `Thread` class and
override its `run()` method. Here’s how:
Example:
// Creating a thread by extending the Thread class
Class MyThread extends Thread {
Public void run() {
System.out.println(“Thread is running”);
}
}

Public class Main {


Public static void main(String[] args) {
MyThread t1 = new MyThread();
T1.start(); // Starts the 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.

2.Implementing the `Runnable` Interface:


This method involves creating a class that implements the `Runnable` interface
and passing an instance of that class to a `Thread` object. Here’s how:

Example:
// Creating a thread by implementing the Runnable interface
Class MyRunnable implements Runnable {
Public void run() {
System.out.println(“Thread is running”);
}
}

Public class Main {


Public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread t1 = new Thread(myRunnable);
T1.start(); // Starts the thread
}
}
Explanation:
Class Definition: A new class `MyRunnable` implements the `Runnable`
interface.
run() Method: The `run()` method is overridden to define the thread’s task.
Thread Execution: In the `main()` method, an instance of `MyRunnable` is
created. This instance is then passed to a `Thread` object, and `start()` is called to
initiate the thread.

Comparison of the Two Methods:


Extending `Thread`:
- Simpler to use for basic tasks.
- Inherits all properties and methods of the `Thread` class.
- Less flexible as Java does not support multiple inheritance.

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.

Exception Handling in Java: `try`, `catch`, and `finally`

Exception handling in Java is a powerful mechanism that allows developers to


handle runtime errors, ensuring the program continues to run smoothly. The
three main keywords used for this purpose are `try`, `catch`, and `finally`.

`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:

Public class Example {


Public static void main(String[] args) {
CO4 R 7.b Try { (13)
Int data = 50 / 0; // This line will throw an ArithmeticException
}
}
}

`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:

Public class Example {


Public static void main(String[] args) {
Try {
Int data = 50 / 0; // This will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println(“ArithmeticException occurred: “ + e);
}
}
}

In the above example, if an `ArithmeticException` occurs (like division by zero),


the flow jumps to the `catch` block, and the message is printed.

`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:

Public class Example {


Public static void main(String[] args) {
Try {
Int data = 50 / 0; // This will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println(“ArithmeticException occurred: “ + e);
} finally {
System.out.println(“This is the finally block, executed regardless of
exceptions.”);
}
}
}

In the above example, regardless of whether the exception is handled or not, the
code inside the `finally` block will be executed.

Detailed Example with Multiple `catch` Blocks

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.

2. Separation of Error-Handling Code from Regular Code:


The `try-catch` mechanism helps separate the error-handling code from the
regular code. This makes the code easier to read and maintain.

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.

Key Components of File Handling

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)

Byte Streams: Handle binary data (e.g., `FileInputStream`,


`FileOutputStream`).

Character Streams: Handle character data (e.g., `FileReader`, `FileWriter`).

3.FileInputStream and FileOutputStream:

- These classes are used for reading from and writing to files in binary format.

4.FileReader and FileWriter:

- These classes are used for reading from and writing to files in character
format.

Basic File Operations

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;

public class CreateFileExample {

public static void main(String[] args) {

File file = new File("example.txt");

try {

if (file.createNewFile()) {

System.out.println("File created: " + file.getName());

} else {

System.out.println("File already exists.");

} catch (IOException e) {

System.out.println("An error occurred.");

e.printStackTrace();

2.Writing to a File

The `FileWriter` class is used to write character data to a file. It provides


methods such as `write()` to write data and `close()` to close the stream.

Example:

java

import java.io.FileWriter;

import java.io.IOException;

public class WriteFileExample {


public static void main(String[] args) {

try {

FileWriter writer = new FileWriter("example.txt");

writer.write("Hello, World!");

writer.close();

System.out.println("Successfully wrote to the file.");

} catch (IOException e) {

System.out.println("An error occurred.");

e.printStackTrace();

3. Reading from a File

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;

public class ReadFileExample {

public static void main(String[] args) {

try {

FileReader reader = new FileReader("example.txt");

int character;

while ((character = reader.read()) != -1) {

System.out.print((char) character);

reader.close();

} catch (IOException e) {

System.out.println("An error occurred.");


e.printStackTrace();

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;

public class DeleteFileExample {

public static void main(String[] args) {

File file = new File("example.txt");

if (file.delete()) {

System.out.println("Deleted the file: " + file.getName());

} else {

System.out.println("Failed to delete the file.");

Advanced File Operations

1.BufferedReader and BufferedWriter

To handle larger files more efficiently, Java provides `BufferedReader` and


`BufferedWriter` classes that buffer the input and output streams, reducing the
number of I/O operations.

BufferedReader Example:

java

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;
public class BufferedReaderExample {

public static void main(String[] args) {

try (BufferedReader reader = new BufferedReader(new


FileReader("example.txt"))) {

String line;

while ((line = reader.readLine()) != null) {

System.out.println(line);

} catch (IOException e) {

System.out.println("An error occurred.");

e.printStackTrace();

BufferedWriter Example:

java

import java.io.BufferedWriter;

import java.io.FileWriter;

import java.io.IOException;

public class BufferedWriterExample {

public static void main(String[] args) {

try (BufferedWriter writer = new BufferedWriter(new


FileWriter("example.txt"))) {

writer.write("Hello, Buffered World!");

} catch (IOException e) {

System.out.println("An error occurred.");

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)

### Java Program with Nested Try Statements

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

Outer try block: Handles `ArrayIndexOutOfBoundsException`.

Inner try block: Handles `ArithmeticException` (divide-by-zero).

Java Code:

java

public class NestedTryExample {

public static void main(String[] args) {


CO3 C 8.b (14)
try {

// Parse the command line argument as the divisor

int divisor = Integer.parseInt(args[0]);

int[] numbers = {10, 20, 30, 40, 50};

try {

// Division operation that may cause ArithmeticException

int result = numbers[2] / divisor;

System.out.println("Result: " + result);

// Accessing array element that may cause


ArrayIndexOutOfBoundsException

System.out.println("Element at index 5: " + numbers[5]);

} catch (ArithmeticException e) {

System.out.println("ArithmeticException: Cannot divide by zero.");


}

} catch (ArrayIndexOutOfBoundsException e) {

System.out.println("ArrayIndexOutOfBoundsException: Invalid array


index.");

} catch (NumberFormatException e) {

System.out.println("NumberFormatException: Please provide a valid


integer as the divisor.");

Explanation:

1.Command Line Argument Parsing:

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`.

2.Outer Try Block:

- The outer try block wraps around the entire logic to catch any
`ArrayIndexOutOfBoundsException` that might occur if an invalid array index is
accessed.

- If this exception is caught, a message is printed indicating the error.

3.Inner Try Block:

- The inner try block performs the division operation. If the divisor is zero, it
throws `ArithmeticException`.

- It also attempts to access an array element at index 5, which is out of bounds,


to demonstrate how nested try-catch blocks handle multiple exceptions.

4.Catch Blocks:

- The inner catch block handles the `ArithmeticException` and prints a relevant
error message.

-The outer catch block handles the `ArrayIndexOutOfBoundsException` and


`NumberFormatException`, printing appropriate messages.

Prepared By Verified By COE Approved By

You might also like