Question Paper 3 Java
Question Paper 3 Java
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:
o Example:
class Animal {
void makeSound() {
System.out.println("Animal sound");
}
}
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() {}
}
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:
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:
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);
}
}
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.
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.
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);
}
}
In this example, the default constructor initializes the color and year attributes with default
values "Red" and 2020, respectively.
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);
}
}
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.
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.
2. Protected: A member declared as protected can be accessed within the same package and by
subclasses (even if they are in different packages).
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
}
// In file MyPackage/MyClass.java
package MyPackage;
// In another file
import MyPackage.MyClass;
12. (b) Explain in detail about the basics of inheritance and elaborate on any two inheritance
mechanisms in Java.
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");
}
}
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");
}
}
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:
Example:
Example:
Example:
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:
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.
Example:
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.
To work around this, you can use the wrapper classes (Integer, Character, Double,
etc.) instead of primitive types.
Correct Usage:
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.
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.
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.
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.
The append() method modifies the original StringBuffer object, which holds the result
without creating new objects.
Memory Efficiency Creates a new object each time Modifies the existing object
Example:
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.
import java.awt.*;
import java.awt.event.*;
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);
}
}
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.
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);
}
}
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.
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:
Code:
} 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.
Sample Input/Output:
vbnet
Copy code
Error: Division by zero is not allowed.
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:
Code:
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.
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:
css
Copy code
File copied successfully from source.txt to destination.txt
javascript
Copy code
Error: Source file not found.