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:

  1. ActionEvent

  2. 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 with getter/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 the except 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:

  1. To achieve abstraction

  2. To support multiple inheritance

  3. To define contracts for unrelated classes

  4. For loose coupling

  5. 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:

  1. MouseClicked Event:

    • Occurs when a mouse button is pressed and released (clicked)

    • Part of MouseListener interface

    • Example:

       
      component.addMouseListener(new MouseAdapter() {
          public void mouseClicked(MouseEvent e) {
              System.out.println("Mouse clicked at: " + e.getX() + ", " + e.getY());
          }
      });
  2. MouseMoved Event:

    • Occurs when the mouse pointer moves without any buttons pressed

    • Part of MouseMotionListener interface

    • Example:

      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 clicked

  • Can 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.
Thread life cycle 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 class

  • Runnable interface

Thread Life Cycle:

A thread in Java has the following states:

  1. New – Thread is created but not started.

  2. Runnable – Thread is ready to run and waiting for CPU time.

  3. Running – Thread is executing.

  4. Blocked/Waiting – Thread is paused, waiting for a resource or condition.

  5. 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/InterfacePurpose
InputStreamBase class for reading binary data (bytes)
OutputStreamBase class for writing binary data
ReaderBase class for reading character data
WriterBase class for writing character data
FileInputStreamReads data from files in byte format
FileOutputStreamWrites byte data to a file
FileReaderReads character data from a file
FileWriterWrites characters to a file
BufferedReaderReads text from a character stream efficiently
PrintWriterWrites 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 and OutputStream

  • Reads and writes data in bytes (8 bits)

Common Classes:

ClassUse
FileInputStreamRead bytes from a file
FileOutputStreamWrite 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 and Writer

  • Reads and writes characters (16-bit Unicode)

Common Classes:

ClassUse
FileReaderRead characters from a file
FileWriterWrite characters to a file
FileReader fr = new FileReader("textfile.txt");
int c = fr.read();
fr.close();

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    error: Content is protected !!