0% found this document useful (0 votes)
7 views20 pages

Question Paper 3 Java

Uploaded by

mohanraj08052006
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
7 views20 pages

Question Paper 3 Java

Uploaded by

mohanraj08052006
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 20

QUESTION PAPER 3

PART A (10 questions):

1. What is bytecode?
o Bytecode is an intermediate code that is generated by the Java compiler when a
Java source file (.java) is compiled. It is platform-independent and can be
executed on any system that has the Java Virtual Machine (JVM). The bytecode is
stored in .class files and is interpreted or compiled further by the JVM at
runtime.
2. Write the general form of the for-each version of the for statement.
o The for-each loop is used to iterate over collections or arrays. The general form
is:

for (type element : arrayOrCollection) {


// use element
}

o Example:

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


for (int num : numbers) {
System.out.println(num);
}

3. What is the use of the final keyword?


o The final keyword in Java is used to define constants, prevent method overriding,
and prevent inheritance.
 When used with a variable: The value of the variable cannot be changed
(constant).
 When used with a method: The method cannot be overridden by
subclasses.
 When used with a class: The class cannot be inherited.
4. How is dynamic method resolution achieved in Java?
o Dynamic method resolution is achieved through runtime polymorphism in
Java. It is based on method overriding, where a subclass can provide a specific
implementation of a method declared in the superclass. The method to be
executed is determined at runtime based on the object being referenced, not the
reference type.
o Example:

class Animal {
void makeSound() {
System.out.println("Animal sound");
}
}

class Dog extends Animal {


void makeSound() {
System.out.println("Bark");
}
}

public class Test {


public static void main(String[] args) {
Animal myAnimal = new Dog();
myAnimal.makeSound(); // Outputs: Bark
}
}

5. List the values associated with the parameters of setPriority() method of Thread
class.
o The setPriority() method in the Thread class is used to set the priority of a
thread. The valid values for the thread priority range from Thread.MIN_PRIORITY
(1) to Thread.MAX_PRIORITY (10), with Thread.NORM_PRIORITY (5) being the
default.
 Thread.MIN_PRIORITY: 1
 Thread.NORM_PRIORITY: 5
 Thread.MAX_PRIORITY: 10
6. Define deadlock.
o A deadlock occurs when two or more threads are blocked forever because each
thread is waiting for a resource held by another thread. In other words, the threads
enter a state where they cannot proceed because they are each waiting on each
other to release resources.
o Example:

class A {
synchronized void method1(B b) {
b.last();
}
synchronized void last() {}
}

class B {
synchronized void method1(A a) {
a.last();
}
synchronized void last() {}
}

7. State the purpose of the valueOf() method in the String class.


o The valueOf() method in the String class is used to convert other data types
(like integers, floats, booleans, etc.) to their String representation. It is
commonly used to convert primitive data types or objects to strings.
 Example:
int num = 100;
String str = String.valueOf(num); // Converts the integer
to String

8. List any two methods available in the DataOutput Interface.


o The DataOutput interface is used to write primitive data types to an output
stream. Two methods available in this interface are:
 void writeBoolean(boolean v): Writes a boolean value to the stream.
 void writeInt(int v): Writes an integer value to the stream.
9. What is the use of an adapter class?
o An adapter class in Java is a class that provides default (empty) implementations
of the methods in an interface. Adapter classes are commonly used in event
handling to avoid having to implement all methods of an interface. You can
extend the adapter class and override only the methods you're interested in.
o Example:
 MouseAdapter, WindowAdapter, KeyAdapter, etc., are examples of
adapter classes in Java.
10. List any two forms of CheckBoxMenuItem constructors.
o The CheckBoxMenuItem class in Java is a menu item that can be checked or
unchecked. There are two commonly used constructors:
 CheckBoxMenuItem(String text): Creates a CheckBoxMenuItem with
the specified label.
 CheckBoxMenuItem(String text, boolean selected): Creates a
CheckBoxMenuItem with the specified label and initial selection state
(true for selected, false for unselected).

PART B

11. (a) Explain in detail about Java's iteration statements with example.

Java provides several control flow structures, and iteration statements allow repeated execution
of code based on certain conditions. The primary iteration statements in Java are the for, while,
and do-while loops. Each of these loops serves different purposes and is used in various
scenarios.

1. For Loop:

The for loop is typically used when the number of iterations is known in advance. It consists of
three parts: initialization, condition, and increment/decrement. All of these parts are optional,
though the condition is necessary for the loop to function.

Syntax:

for (initialization; condition; update) {


// body of the loop
}
Example:

public class ForLoopExample {


public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println("i = " + i); // Prints numbers 0 to 4
}
}
}

 Initialization: int i = 0 initializes the loop variable.


 Condition: i < 5 is checked before each iteration.
 Update: i++ increments the variable i after each iteration.

2. While Loop:

The while loop is used when the number of iterations is not known in advance and depends on a
condition being true. The loop checks the condition before executing the body of the loop. If the
condition is false initially, the body of the loop is never executed.

Syntax:

while (condition) {
// body of the loop
}

Example:

public class WhileLoopExample {


public static void main(String[] args) {
int i = 0;
while (i < 5) {
System.out.println("i = " + i); // Prints numbers 0 to 4
i++;
}
}
}

 Condition: The loop continues as long as i < 5.


 Update: i++ increments the value of i after each iteration.

3. Do-While Loop:

The do-while loop is similar to the while loop, except that it checks the condition after the loop
body is executed, ensuring that the body is always executed at least once.

Syntax:
do {
// body of the loop
} while (condition);

Example:

java
Copy code
public class DoWhileLoopExample {
public static void main(String[] args) {
int i = 0;
do {
System.out.println("i = " + i); // Prints numbers 0 to 4
i++;
} while (i < 5);
}
}

 Condition: The loop continues as long as i < 5.


 Update: i++ increments the value of i after each iteration.

11. (b) What is a Constructor? Explain with example.

A constructor is a special type of method in Java used to initialize objects when they are
created. A constructor has the same name as the class and is automatically invoked when an
object of the class is created. Constructors are used to set initial values for object attributes.

There are two types of constructors in Java:

1. Default Constructor: A constructor without parameters that initializes an object with default
values.
2. Parameterized Constructor: A constructor that allows the object to be initialized with specific
values at the time of creation.

Example 1: Default Constructor

class Car {
String color;
int year;

// Default constructor
Car() {
color = "Red";
year = 2020;
}

void display() {
System.out.println("Car color: " + color);
System.out.println("Car year: " + year);
}
}

public class Main {


public static void main(String[] args) {
Car car1 = new Car(); // Default constructor is called
car1.display(); // Displays default values
}
}

In this example, the default constructor initializes the color and year attributes with default
values "Red" and 2020, respectively.

Example 2: Parameterized Constructor:

class Car {
String color;
int year;

// Parameterized constructor
Car(String color, int year) {
this.color = color;
this.year = year;
}

void display() {
System.out.println("Car color: " + color);
System.out.println("Car year: " + year);
}
}

public class Main {


public static void main(String[] args) {
Car car2 = new Car("Blue", 2022); // Parameterized constructor is
called
car2.display(); // Displays "Blue" and "2022"
}
}

Here, the constructor is parameterized and takes two arguments to initialize the object.

12. (a) What is a package? Explain in detail about how the packages provide access control to
various categories of visibility for class members.

A package in Java is a namespace that organizes a set of related classes and interfaces. Packages
help avoid naming conflicts, control access, and make the code more manageable. In Java, there
are two types of packages:
1. Built-in Packages: These are predefined packages provided by Java, such as java.util,
java.io, etc.
2. User-defined Packages: These are created by the programmer to group related classes and
interfaces.

Packages also provide a mechanism to control access to class members. Java has different levels
of visibility for class members (variables, methods), which are controlled by access modifiers.

Access Modifiers in Java:

1. Public: A class or member declared as public can be accessed from any other class, whether in
the same package or a different one.

public class MyClass {


public int x; // Public member
}

2. Protected: A member declared as protected can be accessed within the same package and by
subclasses (even if they are in different packages).

protected class MyClass {


protected int x; // Protected member
}

3. Default (Package-private): If no access modifier is specified, the member is accessible only


within the same package.

class MyClass {
int x; // Package-private member
}

4. Private: A member declared as private can only be accessed within the same class.

class MyClass {
private int x; // Private member
}

Example of Packages and Access Control:

// In file MyPackage/MyClass.java
package MyPackage;

public class MyClass {


public int x;
protected int y;
private int z;
public MyClass() {
x = 10;
y = 20;
z = 30;
}
}

// In another file
import MyPackage.MyClass;

public class Test {


public static void main(String[] args) {
MyClass obj = new MyClass();
System.out.println(obj.x); // Accessible
// System.out.println(obj.y); // Error: protected member
// System.out.println(obj.z); // Error: private member
}
}

12. (b) Explain in detail about the basics of inheritance and elaborate on any two inheritance
mechanisms in Java.

Inheritance in Java is a fundamental concept of Object-Oriented Programming (OOP) that


allows a class to inherit properties and methods from another class. The main benefit of
inheritance is code reuse, where a subclass can use fields and methods defined in a superclass
without having to define them again.

There are several types of inheritance in Java:

1. Single Inheritance: A subclass inherits from only one superclass.


2. Multilevel Inheritance: A class inherits from a subclass, forming a chain of inheritance.
3. Hierarchical Inheritance: Multiple classes inherit from a single superclass.
4. Multiple Inheritance (through interfaces): A class can implement multiple interfaces, though
Java does not allow multiple inheritance through classes to avoid ambiguity.

Mechanisms in Java:

1. Method Overriding: A subclass can provide its own implementation of a method that is
already defined in the superclass. This allows the subclass to define behavior specific to
itself while maintaining the same method signature.

class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}

class Dog extends Animal {


@Override
void sound() {
System.out.println("Dog barks");
}
}

public class Main {


public static void main(String[] args) {
Animal myDog = new Dog();
myDog.sound(); // Output: Dog barks
}
}

2. Constructor Inheritance: Constructors are not inherited, but a subclass can call the
constructor of its superclass using the super() keyword. This helps initialize the
inherited fields of the superclass.

class Animal {
Animal() {
System.out.println("Animal constructor");
}
}

class Dog extends Animal {


Dog() {
super(); // Calls Animal's constructor
System.out.println("Dog constructor");
}
}

public class Main {


public static void main(String[] args) {
Dog d = new Dog(); // Output: Animal constructor
// Dog constructor
}
}

These two mechanisms—method overriding and constructor inheritance—are key to


implementing inheritance in Java, allowing for more flexible and reusable code structures.

13. (a) Explain in detail about Java's Built-in Exceptions. Explain any three exceptions.

Java provides a rich set of built-in exceptions to handle errors in programs. Exceptions are
objects that describe conditions that disrupt the normal flow of the program. Java has two
categories of exceptions:

 Checked exceptions: These exceptions are checked at compile-time and need to be handled
explicitly (e.g., IOException).
 Unchecked exceptions: These exceptions are checked at runtime and don't require explicit
handling (e.g., NullPointerException, ArithmeticException).
Three common built-in exceptions:

1. NullPointerException: This exception is thrown when an application attempts to use


null where an object is required. For example, trying to call a method on a null object
reference.

Example:

public class Test {


public static void main(String[] args) {
String str = null;
System.out.println(str.length()); // Throws
NullPointerException
}
}

2. ArithmeticException: This exception is thrown when an exceptional arithmetic


condition occurs, such as dividing by zero.

Example:

public class Test {


public static void main(String[] args) {
int result = 10 / 0; // Throws ArithmeticException: / by zero
}
}

3. ArrayIndexOutOfBoundsException: This exception is thrown when an application tries


to access an array index that is outside of its bounds (i.e., an index less than 0 or greater
than or equal to the array size).

Example:

public class Test {


public static void main(String[] args) {
int[] arr = new int[5];
arr[10] = 100; // Throws ArrayIndexOutOfBoundsException
}
}
Handling exceptions effectively in Java ensures that your program can handle runtime issues
without crashing and can provide meaningful error messages to users.

13. (b) Discuss in detail about the methods to create a thread in Java.

In Java, a thread is an independent unit of execution within a program. There are two primary
ways to create a thread:
1. By Extending the Thread class: In this approach, you create a new class that extends the
Thread class and override its run() method. The run() method contains the code to be
executed by the thread.

Example:

class MyThread extends Thread {


public void run() {
System.out.println("Thread is running");
}
}

public class Test {


public static void main(String[] args) {
MyThread t1 = new MyThread(); // Create thread
t1.start(); // Start the thread
}
}

In the above example:

o The MyThread class extends Thread and overrides the run() method.
o The start() method is called to begin the thread execution. This invokes the run()
method in a new thread.

2. By Implementing the Runnable Interface: Instead of extending Thread, you can


implement the Runnable interface, which requires implementing the run() method. This
is a better approach when your class already extends another class, as Java does not
support multiple inheritance through classes.

Example:

class MyRunnable implements Runnable {


public void run() {
System.out.println("Thread is running");
}
}

public class Test {


public static void main(String[] args) {
MyRunnable r1 = new MyRunnable(); // Create Runnable instance
Thread t1 = new Thread(r1); // Create a thread and pass
Runnable
t1.start(); // Start the thread
}
}

In this example:
o MyRunnable implements the Runnable interface and provides the implementation of
the run() method.
o A Thread object is created by passing the Runnable instance to it. The start()
method is then called to start the execution of the thread.

14. (a) Discuss in detail about the restrictions and limitations of using generics in Java
Programming.

Generics in Java provide a way to ensure type safety while allowing classes, interfaces, and
methods to operate on objects of various types. However, there are certain restrictions and
limitations when using generics in Java:

1. No Primitive Types: Java does not allow primitive types (like int, char, double, etc.)
to be used as type parameters in generic classes or methods. This is because generics in
Java operate only on objects.

Example (incorrect usage):

// This will not compile


public class Box<int> { // Error: Cannot use primitive types
private int value;
}

To work around this, you can use the wrapper classes (Integer, Character, Double,
etc.) instead of primitive types.

Correct Usage:

public class Box<T> {


private T value;
}

2. No Creation of Generic Arrays: Java does not allow you to create an array of generic
types. This is because of the type erasure mechanism, which removes generic type
information at runtime.

Example (incorrect usage):

T[] arr = new T[10]; // Error: Cannot create a generic array of type T

The workaround is to use ArrayList or other collections that can hold generic types.

Correct Usage:
List<T> list = new ArrayList<>();

3. Type Erasure: Java uses a process called type erasure during compilation to remove the
generic type information. This means that the type information used at compile-time is
replaced by Object (for non-primitive types) during runtime. As a result, you cannot use
instanceof to check the type of a generic class.

Example (incorrect usage):

if (obj instanceof T) { // Error: Cannot use T in instanceof


// code
}

Workaround: You can use bounds on the generic type, like T extends Number to
restrict the possible types.

4. Cannot Instantiate Generic Types: You cannot create an instance of a generic class
directly using the type parameter.

Example (incorrect usage):

T obj = new T(); // Error: Cannot instantiate T

Workaround: You can create an object using a constructor or method in the class that
can handle the specific type.

14. (b) Explain the following statement: "StringBuffer class creates mutable strings". Explain
about the StringBuffer class. Compare String class with StringBuffer class.

The StringBuffer class in Java is used to create mutable strings. Unlike the String class,
which creates immutable strings, the StringBuffer class allows you to modify the contents of a
string without creating a new object each time. This makes StringBuffer more efficient when
you need to perform multiple operations on a string (such as appending, inserting, or reversing)
in scenarios like building dynamic strings in loops.

Key Features of StringBuffer:

 It allows modification of the string without creating new objects.


 It provides methods for appending, inserting, deleting, or reversing the string.
 It is not thread-safe (use StringBuffer in single-threaded applications).
 The default initial capacity of a StringBuffer is 16 characters, which expands dynamically as
needed.
Example:

public class StringBufferExample {


public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World"); // Modifies the existing StringBuffer
System.out.println(sb); // Output: Hello World
}
}

In the above example:

 The append() method modifies the original StringBuffer object, which holds the result
without creating new objects.

Comparison: String vs StringBuffer:

Feature String StringBuffer

Mutability Immutable (cannot be changed) Mutable (can be modified)

Performance Slower (creates new objects) Faster (modifies existing objects)

Thread-safety Thread-safe (but slow) Not thread-safe

Memory Efficiency Creates a new object each time Modifies the existing object

Example:

// Using String (Immutable)


String str1 = "Hello";
str1 = str1 + " World"; // Creates a new String object

// Using StringBuffer (Mutable)


StringBuffer sb = new StringBuffer("Hello");
sb.append(" World"); // Modifies the existing StringBuffer object

In the first case, the String object is immutable, and every modification creates a new object. In
contrast, StringBuffer is mutable, and modifications occur on the same object, making it more
efficient in terms of memory usage and performance for string manipulation.
15. (a) Explain in detail about the commonly used event listener interfaces with a sample
program.

Java provides a number of event listener interfaces that help to handle events such as mouse
clicks, keyboard actions, and other user interactions. These interfaces are part of the Abstract
Window Toolkit (AWT) and Swing frameworks.

Some common event listener interfaces are:

1. ActionListener: Handles action events (like button clicks).


2. MouseListener: Handles mouse events (like mouse clicks, entry, exit).
3. KeyListener: Handles keyboard events (like key presses).
4. WindowListener: Handles window events (like opening, closing, resizing).

Sample Program using ActionListener:

import java.awt.*;
import java.awt.event.*;

public class ButtonClickExample {


public static void main(String[] args) {
Frame frame = new Frame("ActionListener Example");
Button button = new Button("Click Me");

button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button was clicked!");
}
});

frame.add(button);
frame.setSize(200, 200);
frame.setVisible(true);
}
}

 ActionListener: The addActionListener() method adds an action listener to the button.


When the button is clicked, the actionPerformed() method is called.

15. (b) Write a Java Program that demonstrates mouse event handlers.

In this example, we'll handle mouse events such as mouse clicks and mouse movements using
the MouseListener and MouseMotionListener interfaces.

Sample Program using MouseListener and MouseMotionListener:

import java.awt.*;
import java.awt.event.*;
public class MouseEventExample {
public static void main(String[] args) {
Frame frame = new Frame("Mouse Event Example");
Label label = new Label("Mouse Events Demo");

label.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
label.setText("Mouse Clicked at (" + e.getX() + ", " +
e.getY() + ")");
}
});

label.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent e) {
label.setText("Mouse Moved at (" + e.getX() + ", " + e.getY()
+ ")");
}
});

frame.add(label);
frame.setSize(400, 400);
frame.setVisible(true);
}
}

In the above code:

 MouseListener: Handles mouse clicks and updates the label with the position of the mouse.
 MouseMotionListener: Updates the label as the mouse moves across the window.

Long Answer for PART C (15 Marks)

16. (a) 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.

Problem Requirement:
The program should:

 Accept a divisor as a command-line argument.


 Perform a division operation and handle divide by zero exceptions.
 Access an array element and handle array index out-of-bound exceptions.
 Use nested try-catch blocks for handling exceptions appropriately.

Code:

// Java program to demonstrate nested try-catch blocks


public class NestedTryDemo {
public static void main(String[] args) {
try {
// Ensure command-line argument is provided
if (args.length < 1) {
throw new IllegalArgumentException("Please provide a divisor
as a command-line argument.");
}

// Parse the divisor from the argument


int divisor = Integer.parseInt(args[0]);
int[] numbers = {10, 20, 30};

// Outer try block for division operation


try {
int result = 100 / divisor; // Division operation
System.out.println("Result of division: " + result);

// Inner try block for array access


try {
System.out.println("Accessing array element at index 5: "
+ numbers[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Array index out of bounds. " +
e.getMessage());
}

} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed. "
+ e.getMessage());
}

} catch (NumberFormatException e) {
System.out.println("Error: Invalid input. Please provide a valid
integer divisor.");
} catch (IllegalArgumentException e) {
System.out.println("Error: " + e.getMessage());
} catch (Exception e) {
System.out.println("Unexpected error: " + e.getMessage());
}
}
}

Explanation:
1. Input Validation:
o Check if a command-line argument is provided. If not, throw an
IllegalArgumentException.

2. Outer Try-Catch Block:


o Perform the division operation using the divisor.
o Catch and handle ArithmeticException if the divisor is zero.

3. Inner Try-Catch Block:


o Attempt to access an out-of-bound array index.
o Catch and handle ArrayIndexOutOfBoundsException.

4. General Exception Handling:


o Handle invalid inputs (non-integer arguments) using NumberFormatException.
o Catch any other unexpected exceptions.

Sample Input/Output:

 Input: java NestedTryDemo 0


Output:

vbnet
Copy code
Error: Division by zero is not allowed.

 Input: java NestedTryDemo 2


Output:

sql
Copy code
Result of division: 50
Error: Array index out of bounds.

Option (b):
b) Write a java Program to copy a text file into another text file and to raise
exceptions for all cases.

Problem Requirement:
The program should:

 Copy content from one text file to another.


 Handle exceptions like:
o Source file not found.
o Read or write errors.
o General exceptions.

Code:

// Java program to copy a text file with exception handling


import java.io.*;

public class FileCopyDemo {


public static void main(String[] args) {
// Ensure source and destination file paths are provided
if (args.length < 2) {
System.out.println("Usage: java FileCopyDemo <source_file>
<destination_file>");
return;
}

String sourceFile = args[0];


String destFile = args[1];

// Try-with-resources to handle file operations


try (BufferedReader reader = new BufferedReader(new
FileReader(sourceFile));
BufferedWriter writer = new BufferedWriter(new
FileWriter(destFile))) {

String line;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine(); // Add a new line in the destination file
}
System.out.println("File copied successfully from " + sourceFile +
" to " + destFile);

} catch (FileNotFoundException e) {
System.out.println("Error: Source file not found. " +
e.getMessage());
} catch (IOException e) {
System.out.println("Error: Issue while reading/writing the file. "
+ e.getMessage());
} catch (Exception e) {
System.out.println("Unexpected error: " + e.getMessage());
}
}
}

Explanation:

1. Input Validation:
o Ensure that both source and destination file paths are provided as command-line
arguments.

2. File Reading and Writing:


o Use BufferedReader to read the source file line by line.
o Use BufferedWriter to write each line to the destination file.

3. Exception Handling:
o FileNotFoundException: Triggered if the source file does not exist.
o IOException: Handles read or write errors.
o General Exception: Catches other unexpected errors.

4. Try-with-Resources:
o Ensures that the file streams are automatically closed after use, avoiding resource leaks.

Sample Input/Output:

 Input: java FileCopyDemo source.txt destination.txt


Output:

css
Copy code
File copied successfully from source.txt to destination.txt

 Input (Source File Missing): java FileCopyDemo non_existing.txt


destination.txt
Output:

javascript
Copy code
Error: Source file not found.

You might also like