0% found this document useful (0 votes)
15 views15 pages

AOOP MID 2 Question Bank Answers

The document is a question bank for an AOOP MID exam covering advanced OOP concepts, multithreading, exception handling, file handling, and collections in Java. It includes definitions, explanations, example programs, and differences between key concepts such as abstract classes, interfaces, and various inheritance types. Additionally, it provides code snippets for practical implementations of multithreading, exception handling, and data structures like LinkedList, ArrayList, HashSet, and HashMap.

Uploaded by

Manthan Patel
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)
15 views15 pages

AOOP MID 2 Question Bank Answers

The document is a question bank for an AOOP MID exam covering advanced OOP concepts, multithreading, exception handling, file handling, and collections in Java. It includes definitions, explanations, example programs, and differences between key concepts such as abstract classes, interfaces, and various inheritance types. Additionally, it provides code snippets for practical implementations of multithreading, exception handling, and data structures like LinkedList, ArrayList, HashSet, and HashMap.

Uploaded by

Manthan Patel
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/ 15

AOOP MID 2 Question Bank Answers (Java)

UNIT-3: Advanced OOP Concepts

1. Define Terms (a) Abstract Class, (b) Interface

• Abstract Class: An abstract class in Java is a class that cannot be instantiated and is meant to be
extended by subclasses. It can contain both abstract methods (without implementation) and
concrete methods (with implementation). It is declared using the abstract keyword.
Example: public abstract class Shape { public abstract void draw(); }

• Interface: An interface in Java is a blueprint of a class that contains only abstract methods (prior to
Java 8) and constants. It is used to achieve abstraction and multiple inheritance. Classes implement
interfaces using the implements keyword.
Example: public interface Drawable { void draw(); }

2. Define Terms (a) String Class, (b) Final Class

• String Class: The String class in Java represents a sequence of characters. It is immutable, meaning
its value cannot be changed after creation. It belongs to the java.lang package and provides
methods like length(), substring(), and concat().
Example: String str = "Hello";

• Final Class: A final class in Java cannot be extended (i.e., it cannot have subclasses). It is declared
using the final keyword to prevent inheritance.
Example: public final class MyClass { }

3. Explain Multilevel Inheritance. Write a Program in Java to Implement Multilevel Inheritance

Multilevel Inheritance: In multilevel inheritance, a class inherits from a parent class, and another class
inherits from that child class, forming a chain of inheritance. For example, Class A → Class B → Class C.

Java Program:

class Grandparent {

void displayGrandparent() {

System.out.println("I am the Grandparent class");

class Parent extends Grandparent {

void displayParent() {
System.out.println("I am the Parent class");

class Child extends Parent {

void displayChild() {

System.out.println("I am the Child class");

public class MultilevelInheritanceDemo {

public static void main(String[] args) {

Child child = new Child();

child.displayGrandparent();

child.displayParent();

child.displayChild();

Output:

I am the Grandparent class

I am the Parent class

I am the Child class

4. Discuss the Various Levels of Protection Available for Packages & Their Implications

Java provides four levels of access modifiers for packages and their members:

1. Public: Accessible from everywhere.


Implication: No restrictions; can be accessed by any class in any package.
Example: public class MyClass { }

2. Protected: Accessible within the same package and also in subclasses (even in different packages).
Implication: Useful for inheritance but limits access to non-subclasses outside the package.
Example: protected void myMethod() { }
3. Default (Package-Private): No modifier specified; accessible only within the same package.
Implication: Restricts access to classes outside the package, enhancing encapsulation.
Example: class MyClass { }

4. Private: Accessible only within the same class.


Implication: Not accessible outside the class, even in the same package; used for data hiding.
Example: private int myVar;

5. Explain Hierarchical Inheritance with Example

Hierarchical Inheritance: In hierarchical inheritance, multiple classes inherit from a single parent class,
forming a tree-like structure. For example, Class A (parent) → Class B, Class C (children).

Example:

class Animal {

void eat() {

System.out.println("This animal eats food.");

class Dog extends Animal {

void bark() {

System.out.println("Dog barks.");

class Cat extends Animal {

void meow() {

System.out.println("Cat meows.");

public class HierarchicalInheritanceDemo {

public static void main(String[] args) {


Dog dog = new Dog();

Cat cat = new Cat();

dog.eat();

dog.bark();

cat.eat();

cat.meow();

Output:

This animal eats food.

Dog barks.

This animal eats food.

Cat meows.

6. List Out Any Three Differences Between Abstract Class and Interface

Aspect Abstract Class Interface

Methods Can have both abstract and concrete methods Only abstract methods (prior to Java 8)

Inheritance Supports single inheritance Supports multiple inheritance

Variables Can have instance variables Only constants (public static final)

UNIT-4: Multithreading and Exception Handling

7. Explain Life Cycle of a Thread

The life cycle of a thread in Java consists of the following states:

1. New: Thread is created but not yet started (new Thread()).

2. Runnable: Thread is ready to run after calling start(); it waits for CPU allocation.

3. Running: Thread is executing (CPU is allocated).

4. Blocked/Waiting: Thread is not running due to waiting for a resource, sleep, or wait().

5. Terminated/Dead: Thread completes execution or is stopped.


8. List Out Any Three Differences Between Throw Keyword and Throws Keyword

Aspect Throw Keyword Throws Keyword

Declares exceptions a method might


Purpose Used to explicitly throw an exception
throw

Used in method body (e.g., throw new Used in method signature (e.g., throws
Usage
IOException()) IOException)

Number of
Throws one exception at a time Can declare multiple exceptions
Exceptions

9. Explain Basic Concept of Exception Handling

Exception handling in Java manages runtime errors to prevent program crashes. It ensures the program can
handle unexpected situations gracefully.

Key Concepts:

• Exception: An event that disrupts normal program flow (e.g., ArithmeticException).

• Try-Catch: try block contains code that might throw an exception; catch block handles it.

• Finally: Executes code (e.g., resource cleanup) regardless of exception occurrence.

• Throw/Throws: throw creates an exception; throws declares exceptions a method might throw.

10. Explain try...catch...finally Clause with Syntax and Example

The try-catch-finally clause is used to handle exceptions in Java.

Syntax:

try {

// Code that might throw an exception

} catch (ExceptionType e) {

// Handle the exception

} finally {

// Code that always executes

Example:

public class TryCatchFinallyDemo {


public static void main(String[] args) {

try {

int result = 10 / 0; // Throws ArithmeticException

} catch (ArithmeticException e) {

System.out.println("Error: " + e.getMessage());

} finally {

System.out.println("This block always executes.");

Output:

Error: / by zero

This block always executes.

11. Write a Program in Java to Develop User-Defined Exception for 'Divide by Zero' Error

Java Program:

class DivideByZeroException extends Exception {

public DivideByZeroException(String message) {

super(message);

public class UserDefinedExceptionDemo {

public static void divide(int a, int b) throws DivideByZeroException {

if (b == 0) {

throw new DivideByZeroException("Division by zero is not allowed");

System.out.println("Result: " + (a / b));

}
public static void main(String[] args) {

try {

divide(10, 0);

} catch (DivideByZeroException e) {

System.out.println("Error: " + e.getMessage());

Output:

Error: Division by zero is not allowed

12. Write Short Note: Thread Priorities

Thread priorities in Java determine the order in which threads are scheduled for execution. They range
from 1 (lowest, Thread.MIN_PRIORITY) to 10 (highest, Thread.MAX_PRIORITY), with 5 being the default
(Thread.NORM_PRIORITY). Higher-priority threads get preference, but the actual scheduling depends on
the JVM and OS. Priorities can be set using setPriority(int priority) and retrieved using getPriority().

13. Write a Program That Executes Two Threads: One Thread Prints Even Numbers and Another Prints
Odd Numbers from 1 to 200

Java Program:

class EvenThread extends Thread {

public void run() {

for (int i = 2; i <= 200; i += 2) {

System.out.println("Even: " + i);

class OddThread extends Thread {

public void run() {

for (int i = 1; i <= 200; i += 2) {


System.out.println("Odd: " + i);

public class EvenOddThreads {

public static void main(String[] args) {

EvenThread even = new EvenThread();

OddThread odd = new OddThread();

even.start();

odd.start();

Output: (Output may interleave due to thread scheduling)

Odd: 1

Even: 2

Odd: 3

Even: 4

...

Odd: 199

Even: 200

14. Write a Program That Executes Two Threads: One Displays "Thread1" Every 1000 ms, Another
Displays "Thread2" Every 2000 ms

Java Program:

class Thread1 extends Thread {

public void run() {

try {

for (int i = 0; i < 5; i++) {

System.out.println("Thread1");
Thread.sleep(1000);

} catch (InterruptedException e) {

System.out.println("Thread1 interrupted");

class Thread2 extends Thread {

public void run() {

try {

for (int i = 0; i < 5; i++) {

System.out.println("Thread2");

Thread.sleep(2000);

} catch (InterruptedException e) {

System.out.println("Thread2 interrupted");

public class ThreadDisplay {

public static void main(String[] args) {

Thread1 t1 = new Thread1();

Thread2 t2 = new Thread2();

t1.start();

t2.start();

Output:
Thread1

Thread1

Thread2

Thread1

Thread1

Thread2

Thread1

Thread2

Thread2

Thread2

15. What is Multithreading? Write Advantages of Multithreading

Multithreading: Multithreading in Java allows multiple threads to run concurrently within a single program,
sharing the same memory space. Each thread executes a separate task.

Advantages:

1. Improved Performance: Utilizes CPU efficiently by running tasks in parallel.

2. Resource Sharing: Threads share memory and resources, reducing overhead.

3. Responsiveness: Enhances user experience (e.g., UI remains responsive while background tasks
run).

UNIT-5: File Handling and Collections

16. WAP Which Reads from the File Using InputStreamClass

Java Program:

import java.io.FileInputStream;

import java.io.IOException;

public class ReadFileDemo {

public static void main(String[] args) {

try (FileInputStream fis = new FileInputStream("input.txt")) {

int data;
while ((data = fis.read()) != -1) {

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

} catch (IOException e) {

System.out.println("Error: " + e.getMessage());

Note: This program assumes an input.txt file exists. It reads bytes from the file and prints them as
characters.

17. WAP Which Writes into the File Using OutputStreamClass

Java Program:

import java.io.FileOutputStream;

import java.io.IOException;

public class WriteFileDemo {

public static void main(String[] args) {

try (FileOutputStream fos = new FileOutputStream("output.txt")) {

String data = "Hello, this is a test file!";

fos.write(data.getBytes());

System.out.println("Data written to file successfully.");

} catch (IOException e) {

System.out.println("Error: " + e.getMessage());

Output: Creates output.txt with the content "Hello, this is a test file!".
18. Write a Program in Java to Demonstrate Use of List. Create LinkedList and Add Months (in String
Form), Display

Java Program:

import java.util.LinkedList;

public class LinkedListDemo {

public static void main(String[] args) {

LinkedList<String> months = new LinkedList<>();

months.add("January");

months.add("February");

months.add("March");

months.add("April");

months.add("May");

months.add("June");

months.add("July");

months.add("August");

months.add("September");

months.add("October");

months.add("November");

months.add("December");

System.out.println("Months in the LinkedList:");

for (String month : months) {

System.out.println(month);

Output:

Months in the LinkedList:

January
February

March

April

May

June

July

August

September

October

November

December

19. Write a Program in Java to Demonstrate Use of List. Create ArrayList and Add Weekdays (in String
Form)

Java Program:

import java.util.ArrayList;

public class ArrayListDemo {

public static void main(String[] args) {

ArrayList<String> weekdays = new ArrayList<>();

weekdays.add("Monday");

weekdays.add("Tuesday");

weekdays.add("Wednesday");

weekdays.add("Thursday");

weekdays.add("Friday");

System.out.println("Weekdays in the ArrayList:");

for (String day : weekdays) {

System.out.println(day);

}
}

Output:

Weekdays in the ArrayList:

Monday

Tuesday

Wednesday

Thursday

Friday

20. Write a Program in Java to Create a New HashSet, Add Colors (in String Form), and Iterate Using for-
each Loop to Display

Java Program:

import java.util.HashSet;

public class HashSetDemo {

public static void main(String[] args) {

HashSet<String> colors = new HashSet<>();

colors.add("Red");

colors.add("Blue");

colors.add("Green");

colors.add("Yellow");

colors.add("Purple");

System.out.println("Colors in the HashSet:");

for (String color : colors) {

System.out.println(color);

}
Output (order may vary due to HashSet):

Colors in the HashSet:

Red

Blue

Green

Yellow

Purple

21. Write a Java Program to Create a New HashMap, Add 5 Students' Data (Enrolment No and Name),
Retrieve and Display the Student's Name Using Enrolment No

Java Program:

import java.util.HashMap;

public class HashMapDemo {

public static void main(String[] args) {

HashMap<String, String> students = new HashMap<>();

students.put("E001", "Alice");

students.put("E002", "Bob");

students.put("E003", "Charlie");

students.put("E004", "Diana");

students.put("E005", "Eve");

String enrolmentNo = "E003";

String name = students.get(enrolmentNo);

System.out.println("Student with enrolment no " + enrolmentNo + ": " + name);

Output:

Student with enrolment no E003: Charlie

You might also like