0% found this document useful (0 votes)
214 views31 pages

oops pyq solved gtu

Uploaded by

luhanasoham8
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)
214 views31 pages

oops pyq solved gtu

Uploaded by

luhanasoham8
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/ 31

Q1 (a) Explain the basic structure of a Java program.

(3 Marks)

A basic Java program consists of the following components:

1. Package Declaration:
○ Declares the package to which the class belongs.
○ Example: package mypackage;
○ Optional, but useful for organizing classes.
2. Import Statements:
○ Allows importing built-in or user-defined classes.
○ Example: import java.util.Scanner;
3. Class Declaration:
○ Declares the class and defines its name.

Syntax:
java
Copy code
public class MyClass {
// class body
}


4. Main Method:
○ The starting point for program execution.

Syntax:
java
Copy code
public static void main(String[] args) {
// Code to execute
}


5. Statements:
○ Contains the logic or operations of the program.

Q1 (b) List out different features of Java. Explain any two. (4 Marks)

Java has several features that make it a powerful programming language:

1. Platform Independent
2. Object-Oriented
3. Secure
4. Robust
5. Multithreaded
6. High Performance
7. Dynamic and Extensible

Explanation of Two Features:

1. Platform Independent:
○ Java compiles source code into bytecode. This bytecode can be executed on
any machine with a JVM (Java Virtual Machine), irrespective of the operating
system.
○ This "Write Once, Run Anywhere" feature makes Java highly portable.
2. Object-Oriented:
○ Java is based on principles of object-oriented programming (OOP), such as
encapsulation, inheritance, and polymorphism.
○ It enables modular, reusable, and maintainable code.

Q1 (c) Write a program in Java to find the sum of digits of an entered


number. (7 Marks)

Program:

java
Copy code
import java.util.Scanner;

public class SumOfDigits {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = sc.nextInt();
int sum = 0;

while (number > 0) {


sum += number % 10; // Extract the last digit
number /= 10; // Remove the last digit
}

System.out.println("Sum of digits: " + sum);


}
}

OR
Q1 (c) Write a program in Java to find the maximum from any ten
numbers using command line arguments. (7 Marks)

Program:

java
Copy code
public class MaxFromNumbers {
public static void main(String[] args) {
if (args.length < 10) {
System.out.println("Please provide 10 numbers as command
line arguments.");
return;
}

int max = Integer.MIN_VALUE; // Initialize with smallest


integer value

for (String arg : args) {


int num = Integer.parseInt(arg);
if (num > max) {
max = num; // Update max if current number is
greater
}
}

System.out.println("Maximum number is: " + max);


}
}

Q2 (a) List out different concepts of OOP. Explain any one in detail. (3
Marks)

Concepts of Object-Oriented Programming (OOP):

1. Encapsulation
2. Inheritance
3. Polymorphism
4. Abstraction

Explanation of Encapsulation:
Encapsulation is the process of wrapping data (fields) and methods (functions) that operate
on that data within a single unit, typically a class.
● Fields are often declared private, and access is provided through public methods
(getters and setters).
● This ensures data security and hides implementation details.

Example:

java
Copy code
class Employee {
private String name; // Private field

// Public getter
public String getName() {
return name;
}

// Public setter
public void setName(String name) {
this.name = name;
}
}

Q2 (b) Explain JVM in detail. (4 Marks)

The Java Virtual Machine (JVM) is a core component of the Java Runtime Environment
(JRE). It provides a platform-independent runtime environment to execute Java programs.

Key Components of JVM:

1. Class Loader:
○ Loads class files (.class) into the JVM.
○ Performs tasks such as loading, linking, and initializing classes.
2. Bytecode Verifier:
○ Ensures the code adheres to Java specifications and doesn't violate access
rights or security.
3. Execution Engine:
○ Executes the bytecode. It consists of:
■ Interpreter: Converts bytecode to machine code at runtime.
■ Just-In-Time (JIT) Compiler: Compiles frequently executed bytecode
into native machine code for better performance.
4. Memory Manager:
○ Handles memory allocation and garbage collection.
Q2 (c) Explain constructor overloading with example. (7 Marks)

Constructor Overloading:
It refers to defining multiple constructors in the same class, differentiated by the number or
type of parameters. This provides flexibility to initialize objects in different ways.

Example:

java
Copy code
class Student {
String name;
int age;

// Constructor with no parameters


Student() {
this.name = "Unknown";
this.age = 0;
}

// Constructor with one parameter


Student(String name) {
this.name = name;
this.age = 0;
}

// Constructor with two parameters


Student(String name, int age) {
this.name = name;
this.age = age;
}

void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}

public class Main {


public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student("Alice");
Student s3 = new Student("Bob", 20);
s1.display();
s2.display();
s3.display();
}
}

This is a partial response due to length constraints. Let me know if you'd like the remaining
questions answered in a similarly detailed format!

4o

You said:
YES CONTINUE IN SIMILAR FORM

ChatGPT said:
ChatGPT

Here is the continuation of the detailed answers for the remaining questions:

Q3 (a) Explain any four string functions in Java with examples. (3 Marks)
length(): Returns the number of characters in the string.
Example:
java
Copy code
String str = "Hello";
System.out.println(str.length()); // Output: 5

1.

toUpperCase(): Converts all characters of the string to uppercase.


Example:
java
Copy code
String str = "hello";
System.out.println(str.toUpperCase()); // Output: HELLO

2.

substring(int beginIndex, int endIndex): Extracts a portion of the string from


beginIndex to endIndex (excluding endIndex).
Example:
java
Copy code
String str = "HelloWorld";
System.out.println(str.substring(0, 5)); // Output: Hello

3.

charAt(int index): Returns the character at the specified index.


Example:
java
Copy code
String str = "Java";
System.out.println(str.charAt(1)); // Output: a

4.

Q3 (b) List out different types of inheritance. Explain multilevel


inheritance. (4 Marks)

Types of Inheritance in Java:

1. Single Inheritance: A class inherits from one superclass.


2. Multilevel Inheritance: A class inherits from another class, which itself inherits from
another class.
3. Hierarchical Inheritance: Multiple classes inherit from a single superclass.
4. Hybrid Inheritance: Combination of different inheritance types, achieved via
interfaces in Java.

Explanation of Multilevel Inheritance:


In multilevel inheritance, a child class is derived from a parent class, and the parent class is
derived from a grandparent class.

Example:

java
Copy code
class GrandParent {
void display() {
System.out.println("I am the GrandParent");
}
}

class Parent extends GrandParent {


void show() {
System.out.println("I am the Parent");
}
}

class Child extends Parent {


void print() {
System.out.println("I am the Child");
}
}

public class Main {


public static void main(String[] args) {
Child c = new Child();
c.display(); // From GrandParent
c.show(); // From Parent
c.print(); // From Child
}
}

Q3 (c) What is an interface? Explain multiple inheritance with an


example. (7 Marks)

Interface:
An interface in Java is a reference type, similar to a class, but it only contains method
signatures (abstract methods) and constants. Interfaces are implemented by classes to
achieve abstraction.

Multiple Inheritance:
Java doesn’t support multiple inheritance with classes to avoid ambiguity. However, it can be
achieved using interfaces.

Example:

java
Copy code
interface A {
void methodA();
}

interface B {
void methodB();
}

class C implements A, B {
public void methodA() {
System.out.println("Method A from Interface A");
}

public void methodB() {


System.out.println("Method B from Interface B");
}
}

public class Main {


public static void main(String[] args) {
C obj = new C();
obj.methodA();
obj.methodB();
}
}

OR

Q3 (c) What is a package? Write steps to create one and provide an


example. (7 Marks)

Package:
A package is a namespace used to organize related classes and interfaces, providing better
modularity and reusability.

Steps to Create a Package:

1. Define the package keyword at the top of the file.


Example: package mypackage;
2. Save the file in a directory with the package name.
3. Compile using javac -d . MyClass.java.
4. Import and use the package in another class.

Example:

java
Copy code
// File: MyPackageClass.java
package mypackage;

public class MyPackageClass {


public void displayMessage() {
System.out.println("This is a package example.");
}
}

// File: TestPackage.java
import mypackage.MyPackageClass;

public class TestPackage {


public static void main(String[] args) {
MyPackageClass obj = new MyPackageClass();
obj.displayMessage();
}
}

Q4 (a) Explain thread priorities with a suitable example. (3 Marks)

Thread priorities determine the importance of a thread, influencing the order in which threads
are scheduled for execution. Priorities range from 1 (MIN_PRIORITY) to 10
(MAX_PRIORITY), with 5 being the default (NORM_PRIORITY).

Example:

java
Copy code
class MyThread extends Thread {
public void run() {
System.out.println(Thread.currentThread().getName() + " with
priority " + Thread.currentThread().getPriority());
}
}

public class Main {


public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.MAX_PRIORITY);

t1.start();
t2.start();
}
}
Q4 (b) What is a thread? Explain the thread life cycle. (4 Marks)

Thread:
A thread is the smallest unit of a process that can be executed concurrently. In Java, threads
are represented by the Thread class or by implementing the Runnable interface.

Thread Life Cycle:

1. New: Thread is created but not started.


Example: Thread t = new Thread();
2. Runnable: Thread is ready to run after calling start().
3. Running: The thread is executing.
4. Blocked/Waiting: Thread is paused and waiting for resources or a signal.
5. Terminated: Thread has finished execution.

Q4 (c) Write a program in Java to create multiple threads by


implementing the Thread class. (7 Marks)

Program:

java
Copy code
class MyThread extends Thread {
private String threadName;

MyThread(String name) {
this.threadName = name;
}

public void run() {


for (int i = 1; i <= 5; i++) {
System.out.println(threadName + " is running: " + i);
}
}
}

public class Main {


public static void main(String[] args) {
MyThread t1 = new MyThread("Thread 1");
MyThread t2 = new MyThread("Thread 2");
t1.start();
t2.start();
}
}

Q4 (a) Explain the basic concept of Exception Handling. (3 Marks)

Exception handling is a mechanism in Java used to handle runtime errors and maintain the
normal flow of the application. It involves identifying exceptions (unexpected errors) and
taking corrective measures.

Key Concepts:

1. try block: Code that might throw an exception is placed inside a try block.
2. catch block: This block handles specific exceptions thrown by the try block.
3. finally block: Code inside the finally block is executed regardless of whether an
exception occurs.
4. throw: Used to explicitly throw an exception.
5. throws: Declares the exceptions that a method can throw.

Example:

java
Copy code
public class ExceptionExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will throw an
ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Exception caught: Division by
zero!");
} finally {
System.out.println("Execution completed.");
}
}
}

Q4 (b) Explain multiple catch blocks with a suitable example. (4 Marks)

In Java, multiple catch blocks allow handling different types of exceptions that may be
thrown from a try block.
Example:

java
Copy code
public class MultiCatchExample {
public static void main(String[] args) {
try {
int arr[] = {1, 2, 3};
System.out.println(arr[5]); //
ArrayIndexOutOfBoundsException
int result = 10 / 0; // ArithmeticException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index is out of bounds!");
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
} finally {
System.out.println("End of program.");
}
}
}

Q4 (c) What is an exception? Write a program that shows the use of


ArithmeticException. (7 Marks)

Exception:
An exception is an event that disrupts the normal flow of a program. In Java, exceptions are
objects of classes that extend the Throwable class.

● Common exceptions: ArithmeticException, NullPointerException,


ArrayIndexOutOfBoundsException.

Program:

java
Copy code
public class ArithmeticExceptionExample {
public static void main(String[] args) {
try {
int num = 10, divisor = 0;
int result = num / divisor; // This will throw
ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Exception caught: Division by zero
is not allowed.");
}
}
}

Q5 (a) Explain ArrayIndexOutOfBoundsException in Java with an


example. (3 Marks)

ArrayIndexOutOfBoundsException:
This exception occurs when trying to access an index of an array that is outside its bounds.

Example:

java
Copy code
public class ArrayExample {
public static void main(String[] args) {
try {
int arr[] = {10, 20, 30};
System.out.println(arr[5]); // Invalid index, throws
exception
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception caught: Array index out of
bounds.");
}
}
}

Q5 (b) Explain the basics of stream classes. (4 Marks)

Stream Classes in Java:


Stream classes are part of the java.io package and are used for reading and writing data.

Types of Streams:

1. Input Streams: For reading data. Example: FileInputStream,


BufferedInputStream.
2. Output Streams: For writing data. Example: FileOutputStream,
BufferedOutputStream.
Characteristics:

● Streams handle byte-level and character-level input/output.


● Common methods:
○ read(): Reads data from a stream.
○ write(): Writes data to a stream.

Q5 (c) Write a Java program to create a text file and perform a write
operation on the text file. (7 Marks)

Program:

java
Copy code
import java.io.FileWriter;
import java.io.IOException;

public class FileWriteExample {


public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("example.txt");
writer.write("This is an example of file writing in
Java.");
writer.close();
System.out.println("File written successfully.");
} catch (IOException e) {
System.out.println("An error occurred while writing to
the file.");
e.printStackTrace();
}
}
}

OR

Q5 (c) Write a Java program to display the content of a text file and
perform an append operation. (7 Marks)

Program:

java
Copy code
import java.io.FileWriter;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;

public class FileReadAppendExample {


public static void main(String[] args) {
String fileName = "example.txt";

// Append operation
try (FileWriter writer = new FileWriter(fileName, true)) {
writer.write("\nAppended text to the file.");
System.out.println("Text appended successfully.");
} catch (IOException e) {
System.out.println("An error occurred while
appending.");
e.printStackTrace();
}

// Display content
try (FileReader reader = new FileReader(fileName);
BufferedReader br = new BufferedReader(reader)) {
String line;
System.out.println("File content:");
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("An error occurred while reading the
file.");
e.printStackTrace();
}
}
}

Q5 (a) Explain Divide by Zero Exception in Java with an example. (3


Marks)
Divide by Zero Exception:
This occurs when a number is divided by zero, which is undefined. In Java, it throws an
ArithmeticException at runtime.

Example:

java
Copy code
public class DivideByZeroExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // Throws ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Exception caught: Division by zero
is not allowed.");
}
}
}

Q5 (b) Explain try and catch blocks with an example. (4 Marks)

Try and Catch:

● A try block contains code that might throw exceptions.


● A catch block handles the specific exception type.

Example:

java
Copy code
public class TryCatchExample {
public static void main(String[] args) {
try {
int[] arr = {1, 2, 3};
System.out.println(arr[5]); //
ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught an exception: " +
e.getMessage());
}
}
}
Q.1 (a) List out basic concepts of OOP. Explain any one in detail. (3
Marks)

Basic Concepts of OOP:

1. Encapsulation
2. Inheritance
3. Polymorphism
4. Abstraction

Encapsulation (Explanation):
Encapsulation is the process of bundling data and methods that operate on the data into a
single unit called a class. It ensures controlled access to the data by using access modifiers
(private, protected, public) and exposing only necessary details through getters and
setters.

Example:

java
Copy code
class Employee {
private String name;

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}
}

Q.1 (b) Explain JVM in detail. (4 Marks)

The Java Virtual Machine (JVM) is the runtime environment for executing Java
applications.

Components:

1. Class Loader: Loads Java class files.


2. Bytecode Verifier: Ensures code correctness and prevents security breaches.
3. Execution Engine: Executes bytecode using the Interpreter or Just-In-Time (JIT)
compiler.
4. Memory Manager: Manages memory allocation and garbage collection.
Role of JVM:

● Converts bytecode into machine code.


● Ensures portability of Java programs.
● Handles exceptions and garbage collection.

Q.1 (c) Write a program in Java to print the Fibonacci series for n terms.
(7 Marks)

Program:

java
Copy code
import java.util.Scanner;

public class Fibonacci {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of terms: ");
int n = sc.nextInt();

int a = 0, b = 1;
System.out.print("Fibonacci Series: " + a + " " + b);

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


int next = a + b;
System.out.print(" " + next);
a = b;
b = next;
}
}
}

OR

Q.1 (c) Write a program in Java to find the minimum from any ten
numbers using command line arguments. (7 Marks)

Program:

java
Copy code
public class MinFromNumbers {
public static void main(String[] args) {
if (args.length < 10) {
System.out.println("Please provide 10 numbers as command
line arguments.");
return;
}

int min = Integer.MAX_VALUE;

for (String arg : args) {


int num = Integer.parseInt(arg);
if (num < min) {
min = num;
}
}

System.out.println("Minimum number is: " + min);


}
}

Q.2 (a) What is a wrapper class? Explain with an example. (3 Marks)

Wrapper Class:
A wrapper class in Java is used to convert primitive data types into objects. They are part of
the java.lang package.

Example:

java
Copy code
public class WrapperExample {
public static void main(String[] args) {
int num = 10;
Integer wrappedNum = Integer.valueOf(num); // Wrapping
int unwrappedNum = wrappedNum.intValue(); // Unwrapping

System.out.println("Wrapped: " + wrappedNum);


System.out.println("Unwrapped: " + unwrappedNum);
}
}
Q.2 (b) List out different features of Java. Explain any two. (4 Marks)

Features of Java:

1. Platform Independent
2. Object-Oriented
3. Secure
4. Robust
5. Multithreaded

Explanation of Two Features:

1. Platform Independent: Java compiles code into bytecode, which can be executed
on any system with a JVM, regardless of the operating system.
2. Secure: Java provides security through the absence of explicit pointers and runtime
checks.

Q.2 (c) What is method overloading? Explain with an example. (7 Marks)

Method Overloading:
Method overloading allows multiple methods in the same class with the same name but
different parameter lists.

Example:

java
Copy code
class Calculator {
int add(int a, int b) {
return a + b;
}

int add(int a, int b, int c) {


return a + b + c;
}
}

public class OverloadExample {


public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println("Sum (2 args): " + calc.add(10, 20));
System.out.println("Sum (3 args): " + calc.add(10, 20, 30));
}
}

OR

Q.2 (c) What is a constructor? Explain parameterized constructor with an


example. (7 Marks)

Constructor:
A constructor initializes an object when it is created. It has the same name as the class and
no return type.

Parameterized Constructor:
A constructor that accepts parameters to initialize an object with specific values.

Example:

java
Copy code
class Student {
String name;
int age;

// Parameterized Constructor
Student(String name, int age) {
this.name = name;
this.age = age;
}

void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}

public class ConstructorExample {


public static void main(String[] args) {
Student s = new Student("Alice", 20);
s.display();
}
}

Q.3 (a) Explain the super keyword with an example. (3 Marks)


super Keyword:
The super keyword refers to the parent class and is used to access its fields, methods, or
constructors.

Example:

java
Copy code
class Parent {
void display() {
System.out.println("This is the parent class.");
}
}

class Child extends Parent {


void display() {
super.display(); // Call parent class method
System.out.println("This is the child class.");
}
}

public class SuperExample {


public static void main(String[] args) {
Child obj = new Child();
obj.display();
}
}

Q3 (b) List out different types of inheritance. Explain multilevel


inheritance. (4 Marks)

Types of Inheritance in Java:

1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Hybrid Inheritance (using interfaces)

Multilevel Inheritance:
In multilevel inheritance, a class is derived from another class, which in turn is derived from
another class.

Example:
java
Copy code
class GrandParent {
void display() {
System.out.println("I am the GrandParent.");
}
}

class Parent extends GrandParent {


void show() {
System.out.println("I am the Parent.");
}
}

class Child extends Parent {


void print() {
System.out.println("I am the Child.");
}
}

public class MultilevelInheritance {


public static void main(String[] args) {
Child c = new Child();
c.display(); // From GrandParent
c.show(); // From Parent
c.print(); // From Child
}
}

Q3 (c) What is an interface? Explain multiple inheritance with an


example. (7 Marks)

Interface:
An interface in Java is a collection of abstract methods and constants. It is used to achieve
abstraction and multiple inheritance in Java.

Multiple Inheritance Using Interfaces:


In Java, a class can implement multiple interfaces, achieving multiple inheritance.

Example:

java
Copy code
interface A {
void methodA();
}

interface B {
void methodB();
}

class C implements A, B {
public void methodA() {
System.out.println("Method A from Interface A");
}

public void methodB() {


System.out.println("Method B from Interface B");
}
}

public class MultipleInheritance {


public static void main(String[] args) {
C obj = new C();
obj.methodA();
obj.methodB();
}
}

OR

Q3 (c) What is a package? Write steps to create a package and give an


example of it. (7 Marks)

Package:
A package in Java is a namespace that organizes classes and interfaces, making code
easier to manage and avoid name conflicts.

Steps to Create a Package:

1. Add the package keyword at the top of the file.


Example: package mypackage;
2. Save the file in a folder with the same name as the package.
3. Compile the file using: javac -d . MyClass.java.
4. Import the package in another file using: import mypackage.MyClass;.
Example:

java
Copy code
// File: MyPackageClass.java
package mypackage;

public class MyPackageClass {


public void display() {
System.out.println("This is a package example.");
}
}

// File: TestPackage.java
import mypackage.MyPackageClass;

public class TestPackage {


public static void main(String[] args) {
MyPackageClass obj = new MyPackageClass();
obj.display();
}
}

Q4 (a) Explain thread priorities with a suitable example. (3 Marks)

Thread Priorities:
Each thread in Java has a priority ranging from 1 (MIN_PRIORITY) to 10 (MAX_PRIORITY).
Threads with higher priorities are executed before those with lower priorities, but this
depends on the thread scheduler.

Example:

java
Copy code
class MyThread extends Thread {
MyThread(String name) {
super(name);
}

public void run() {


System.out.println(Thread.currentThread().getName() + " with
priority " + Thread.currentThread().getPriority());
}
}

public class ThreadPriorityExample {


public static void main(String[] args) {
MyThread t1 = new MyThread("Thread 1");
MyThread t2 = new MyThread("Thread 2");
t1.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.MAX_PRIORITY);

t1.start();
t2.start();
}
}

Q4 (b) What is a thread? Explain the thread life cycle. (4 Marks)

Thread:
A thread is the smallest unit of a process that can be executed concurrently. Threads in Java
can be created by extending the Thread class or implementing the Runnable interface.

Thread Life Cycle:

1. New: Thread is created but not started.


Example: Thread t = new Thread();.
2. Runnable: After calling start(), the thread is ready to run.
3. Running: Thread is currently executing.
4. Blocked/Waiting: Thread is paused due to resource unavailability or
synchronization.
5. Terminated: Thread has finished execution.

Q4 (c) Write a program in Java that creates multiple threads by


implementing the Thread class. (7 Marks)

Program:

java
Copy code
class MyThread extends Thread {
private String threadName;
MyThread(String name) {
this.threadName = name;
}

public void run() {


for (int i = 1; i <= 5; i++) {
System.out.println(threadName + " is running: " + i);
}
}
}

public class MultipleThreads {


public static void main(String[] args) {
MyThread t1 = new MyThread("Thread 1");
MyThread t2 = new MyThread("Thread 2");

t1.start();
t2.start();
}
}

Q5 (a) Explain ArrayIndexOutOfBound Exception in Java with an


example. (3 Marks)

ArrayIndexOutOfBound Exception:
This exception occurs when attempting to access an index outside the bounds of an array.

Example:

java
Copy code
public class ArrayIndexExample {
public static void main(String[] args) {
try {
int[] arr = {10, 20, 30};
System.out.println(arr[5]); // Invalid index
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception caught: Array index out of
bounds.");
}
}
}

Q5 (b) Explain basics of stream classes. (4 Marks)

Stream Classes in Java:


Stream classes in Java handle input and output operations. They are part of the java.io
package.

Types:

1. Input Streams: For reading data (e.g., FileInputStream).


2. Output Streams: For writing data (e.g., FileOutputStream).
3. Character Streams: For text-based I/O (e.g., FileReader, FileWriter).
4. Buffered Streams: Enhance efficiency (e.g., BufferedReader,
BufferedWriter).

Q5 (c) Write a Java program to create a text file and perform read
operation on the text file. (7 Marks)

Program:

java
Copy code
import java.io.*;

public class FileReadExample {


public static void main(String[] args) {
try {
// Write to file
FileWriter writer = new FileWriter("example.txt");
writer.write("This is a sample file.");
writer.close();

// Read from file


FileReader reader = new FileReader("example.txt");
BufferedReader br = new BufferedReader(reader);
String line;

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


System.out.println(line);
}
br.close();
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}

OR

Q5 (c) Write a Java program to display the content of a text file and
perform append operation. (7 Marks)

Program:

java
Copy code
import java.io.*;

public class FileAppendExample {


public static void main(String[] args) {
String fileName = "example.txt";

try {
// Append to file
FileWriter writer = new FileWriter(fileName, true);
writer.write("\nAppending more data.");
writer.close();

// Display content
FileReader reader = new FileReader(fileName);
BufferedReader br = new BufferedReader(reader);
String line;

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


System.out.println(line);
}

br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

You might also like