Java 2024 (Reg/Rep) Solved Question Paper Object Oriented Concepts Using Java Programming
Time: 2 Hrs | Max. Marks: 60
1. Answer any Six questions. (6×2=12)
1. a) Define variables in java.
Variables are named memory locations that store data values. They must be declared with a data type.
Example:
int age = 25;
b) Define Method overloading.
Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its superclass using the same name, return type, and parameters.
Example:
void add(int a, int b) {}
void add(double a, double b) {}
c) Define polymorphism.
Polymorphism is the ability of a method or object to behave in different forms. It is of two types:
Compile-time (Method Overloading)
Run-time (Method Overriding)
d) Define packages in Java.
A package in Java is a collection of related classes and interfaces grouped together under a common name. It helps organize code and avoid naming conflicts.
e) Define Event. Mention any two types of Events.
An Event in Java is an object that describes a change in state, such as a button click. that triggers program logic.
Two types of events:
ActionEvent
MouseEvent
f) Define Border Layout.
BorderLayout is one of the layout managers provided by the AWT (Abstract Window Toolkit) package. It is used to arrange components in five regions: North, South, East, West, and Center.
g) What is Exception Handling?
Exception Handling is a process to manage run-time errors using blocks like try
, catch
, throw
, and finally
, to prevent program crashes.
h) What is byte stream?
- A Byte Stream in Java is used to perform input and output of 8-bit bytes.
- Used for reading/writing binary data like images or audio files.
Example: FileInputStream
, FileOutputStream
Answer any Three questions. (3×4=12)
2. a) Briefly explain oops concepts in java.
1. Encapsulation
- Wrapping of data (variables) and methods into a single unit (class)
- Example: Using
private
variables withgetter/setter
methods.
2. Inheritance
- Allows one class to acquire properties of another class using
extends
keyword. - Promotes code reusability.
3. Polymorphism
Allows one method to behave in multiple forms.
Compile-time (method overloading)
Run-time (method overriding)
4. Abstraction
- Hiding internal details and showing only essential features.
- Achieved using abstract classes and interfaces.
b) Define operator. Explain Arithmetic operators with an example.
try
Block:
- The code that might raise an exception is placed inside the
try
block. - Python runs this code and checks for errors during execution.
except
Block:
- If an exception occurs in the
try
block, Python jumps to theexcept
block. - This block contains code that handles the error.
finally
Block:
- The
finally
block is always executed, whether an exception occurred or not. - It is often used to release resources, like closing files or database connections
Example:
try:
a = int(input("Enter a number: "))
b = 10 / a
print("Result:", b)
except ZeroDivisionError:
print("Cannot divide by zero.")
finally:
print("Execution completed.")
c) Explain any two looping statements in java.
Java provides several looping statements to execute a block of code repeatedly.
1. for Loop
The for
loop is used when you know exactly how many times you want to iterate through a block of code.
Syntax:
for (initialization; condition; update) { // code to be executed }
Example:
for (int i = 1; i <= 5; i++) { System.out.println("Iteration " + i); }
Output:
Iteration 1 Iteration 2 Iteration 3 Iteration 4 Iteration 5
uses:
When you know the exact number of iterations needed
For iterating through arrays or collections
When you need a counter variable
2. While Loop
The while
loop executes a block of code as long as a specified condition is true.
Syntax:
while (condition) { // code to be executed }
Example:
int count = 1; while (count <= 5) { System.out.println("Count is: " + count); count++; }
Output:
Count is: 1 Count is: 2 Count is: 3 Count is: 4 Count is: 5
uses:
When you don’t know exactly how many iterations are needed
When the loop might need to execute zero times (condition checked first)
For reading input until a sentinel value is encountered
d) Write a java program to Print Prime Numbers between 1 to 10.
public class PrimeNumbers1To10 {
public static void main(String[] args) {
System.out.println("Prime numbers between 1 and 10 are:");
for (int number = 2; number <= 10; number++) {
boolean isPrime = true;
for (int i = 2; i <= number / 2; i++) {
if (number % i == 0) {
isPrime = false;
break; // Not prime, exit inner loop
}
}
if (isPrime) {
System.out.println(number);
}
}
}
}
Answer any Three questions. (3×4=12)
3. a) Explain super and sub class in java with example.
Super Class:
A superclass (or parent/base class) is a class that is extended by another class.
It contains common properties and methods that can be inherited.
Sub Class:
A subclass (or child/derived class) is a class that inherits from the superclass using the
extends
keyword.It can reuse, override, or extend the functionality of the superclass.
Example:
// Superclass
class Animal {
void sound() {
System.out.println("Animals make sounds");
}
}
// Subclass
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
// Main class
public class Test {
public static void main(String[] args) {
Dog d = new Dog();
d.sound(); // Inherited from Animal
d.bark(); // Defined in Dog
}
}
Output:
Animals make sounds
Dog barks
b) Define method overriding. Write a program to demonstrate method overriding.
Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its superclass.
The method in the subclass must have the same name, return type, and parameters.
Used to achieve runtime polymorphism.
Example:
// Superclass
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
// Subclass overrides the method
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
// Main class
public class TestOverride {
public static void main(String[] args) {
Animal a = new Animal();
Dog d = new Dog();
a.sound(); // Calls Animal's method
d.sound(); // Calls Dog's overridden method
}
}
c) Explain how to importing user defined packages.
A package in Java is a namespace that organizes classes and interfaces. User-defined packages are packages created by the programmer to group related classes.
Steps to Import and Use a User-Defined Package:
Step 1: Create the Package
Save this code in a file named MyClass.java
inside a folder named mypack
:
// File: mypack/MyClass.java
package mypack;
public class MyClass {
public void display() {
System.out.println("Hello from MyClass in mypack!");
}
}
Step 2: Compile the Package
From the terminal (inside the folder where mypack
exists):
javac mypack/MyClass.java
Step 3: Use the Package in Another Class
// File: MainApp.java
import mypack.MyClass;
public class MainApp {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.display();
}
}
Step 4: Compile and Run
javac MainApp.java
java MainApp
d) Explain interfaces in java with example.
An interface in Java is a reference type that contains only abstract methods (before Java 8), default methods, static methods, and constant declarations
Use Interfaces:
To achieve abstraction
To support multiple inheritance
To define contracts for unrelated classes
For loose coupling
In strategy design pattern
Example:
// Define the interface
interface Animal {
void sound(); // abstract method
}
// Implement the interface in a class
class Dog implements Animal {
public void sound() {
System.out.println("Dog barks");
}
}
// Another class
public class InterfaceDemo {
public static void main(String[] args) {
Dog d = new Dog();
d.sound(); // Calls the implemented method
}
}
Answer any Three questions. (3×4=12)
4. a) Define Event Handling in java. Explain any two mouse Events in java.
Event Handling is a mechanism that allows Java programs to respond to user interactions such as clicks, key presses, mouse movements, etc.
It is a part of AWT and Swing libraries and follows the event delegation model which includes:
Event Source (e.g., button)
Event Listener (e.g.,
ActionListener
,MouseListener
)Event Object (e.g.,
ActionEvent
,MouseEvent
)
Two Mouse Events in Java:
MouseClicked Event:
Occurs when a mouse button is pressed and released (clicked)
Part of
MouseListener
interfaceExample:
component.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { System.out.println("Mouse clicked at: " + e.getX() + ", " + e.getY()); } });
MouseMoved Event:
Occurs when the mouse pointer moves without any buttons pressed
Part of
MouseMotionListener
interfaceExample:
component.addMouseMotionListener(new MouseMotionAdapter() { public void mouseMoved(MouseEvent e) { System.out.println("Mouse moved to: " + e.getX() + ", " + e.getY()); } });
b) Explain following GUI components. i) Buttons ii) Text fields
i) Buttons
Buttons (JButton
) are components that trigger an action when clicked.
Features:
Can display text, icons, or both
Generate
ActionEvent
when clickedCan be customized (size, color, font)
Can have keyboard mnemonics
Example:
JButton btn = new JButton("Click Me"); btn.addActionListener(e -> { System.out.println("Button was clicked!"); }); frame.add(btn);
ii) Text Fields
Text fields (JTextField
) allow single-line text input.
Features:
Can set/get text content
Can limit input length
Can add action listeners for Enter key
Supports input validation
Example:
JTextField textField = new JTextField(20); // 20 columns wide textField.addActionListener(e -> { System.out.println("Text entered: " + textField.getText()); }); frame.add(textField);
c) Explain Grid Layout with example.
GridLayout
arranges components in a grid (rows × columns).Each cell is of equal size, and components are placed left to right, top to bottom.
Constructor:
new GridLayout(int rows, int cols)
Example:
import java.awt.*;
import javax.swing.*;
public class GridLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame("GridLayout Demo");
frame.setLayout(new GridLayout(2, 2)); // 2 rows, 2 columns
frame.add(new JButton("Button 1"));
frame.add(new JButton("Button 2"));
frame.add(new JButton("Button 3"));
frame.add(new JButton("Button 4"));
frame.setSize(300, 200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Output:
The window displays a 2×2 grid of buttons:
[Button1] [Button2]
[Button3] [Button4]
d) Write a Java program which create and displays a message on the window.
import javax.swing.*; // Import Swing package
public class MessageWindow {
public static void main(String[] args) {
// Create a new frame (window)
JFrame frame = new JFrame("Message Window");
// Create a label with a message
JLabel label = new JLabel("Welcome to Java GUI Programming!", JLabel.CENTER);
// Set size and layout
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(label); // Add the label to the frame
// Set visibility to true
frame.setVisible(true);
}
}
Answer any Three questions. (3×4=12)
5. a) Define Thread. Explain Thread life cycle with diagram.

A thread is a lightweight sub-process that represents an independent path of execution within a program. Threads allow concurrent execution of multiple operations within a single process, enabling efficient utilization of CPU resources.
Java supports multithreading using:
Thread
classRunnable
interface
Thread Life Cycle:
A thread in Java has the following states:
New – Thread is created but not started.
Runnable – Thread is ready to run and waiting for CPU time.
Running – Thread is executing.
Blocked/Waiting – Thread is paused, waiting for a resource or condition.
Terminated (Dead) – Thread has completed execution or exited due to an error.
b) Explain Exception Handling mechanism with try catch-finally.
Java’s exception handling mechanism handles runtime errors to maintain normal flow of the program.
Keywords:
try – Code that might throw an exception.
catch – Handles the exception.
finally – Block that always executes (cleanup code).
Example:
public class ExceptionExample {
public static void main(String[] args) {
try {
int a = 10 / 0; // This will cause ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
} finally {
System.out.println("Finally block executed.");
}
}
}
c) Explain Java I/O packages.
Java I/O (Input and Output) is a set of classes and interfaces in the java.io
package that allow reading and writing data (like files, streams, input from keyboard, etc.).
Key Classes in java.io
:
Class/Interface | Purpose |
---|---|
InputStream | Base class for reading binary data (bytes) |
OutputStream | Base class for writing binary data |
Reader | Base class for reading character data |
Writer | Base class for writing character data |
FileInputStream | Reads data from files in byte format |
FileOutputStream | Writes byte data to a file |
FileReader | Reads character data from a file |
FileWriter | Writes characters to a file |
BufferedReader | Reads text from a character stream efficiently |
PrintWriter | Writes formatted text to an output stream |
File | Represents a file or directory path |
Features of Java I/O:
- Both byte-oriented and character-oriented streams
- Support for buffering, filtering, and piped streams
- Object serialization/deserialization
- File system navigation and manipulation
- Support for internationalization (character encodings)
d) Explain Byte and Character Stream in java.
1. Byte Stream
Handles binary data (images, audio, video, etc.)
Based on
InputStream
andOutputStream
Reads and writes data in bytes (8 bits)
Common Classes:
Class | Use |
---|---|
FileInputStream | Read bytes from a file |
FileOutputStream | Write bytes to a file |
FileInputStream fis = new FileInputStream("file.bin");
int b = fis.read();
fis.close();
2. Character Stream
Handles text data
Based on
Reader
andWriter
Reads and writes characters (16-bit Unicode)
Common Classes:
Class | Use |
---|---|
FileReader | Read characters from a file |
FileWriter | Write characters to a file |
FileReader fr = new FileReader("textfile.txt");
int c = fr.read();
fr.close();